repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
dylibso/modsurfer | https://github.com/dylibso/modsurfer/blob/71ae2ca8e06917b33281bd0b75843ee60edccba8/convert/src/from_api.rs | convert/src/from_api.rs | use crate::*;
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
use crate::types::Audit;
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
use chrono::offset::TimeZone;
use modsurfer_module::{Export, Function, FunctionType, Import, ValType};
pub fn source_language(src: api::SourceLanguage) -> SourceLanguage {
match src {
api::SourceLanguage::Unknown => SourceLanguage::Unknown,
api::SourceLanguage::AssemblyScript => SourceLanguage::AssemblyScript,
api::SourceLanguage::C => SourceLanguage::C,
api::SourceLanguage::Cpp => SourceLanguage::Cpp,
api::SourceLanguage::Go => SourceLanguage::Go,
api::SourceLanguage::Rust => SourceLanguage::Rust,
api::SourceLanguage::Swift => SourceLanguage::Swift,
api::SourceLanguage::JavaScript => SourceLanguage::JavaScript,
api::SourceLanguage::Haskell => SourceLanguage::Haskell,
api::SourceLanguage::Zig => SourceLanguage::Zig,
}
}
pub fn val_types(v: Vec<protobuf::EnumOrUnknown<api::ValType>>) -> Vec<ValType> {
v.into_iter()
.map(|x| val_type(x.enum_value_or_default()))
.collect()
}
pub fn val_type(v: api::ValType) -> ValType {
match v {
api::ValType::I32 => ValType::I32,
api::ValType::I64 => ValType::I64,
api::ValType::F32 => ValType::F32,
api::ValType::F64 => ValType::F64,
api::ValType::V128 => ValType::V128,
api::ValType::FuncRef => ValType::FuncRef,
api::ValType::ExternRef => ValType::ExternRef,
}
}
pub fn sort(sort: api::Sort) -> Sort {
Sort {
order: match sort.direction.enum_value_or_default() {
api::Direction::Asc => Order::Asc,
api::Direction::Desc => Order::Desc,
},
field: match sort.field.enum_value_or_default() {
api::Field::CreatedAt => SortField::CreatedAt,
api::Field::ExportsCount => SortField::ExportsCount,
api::Field::ImportsCount => SortField::ImportsCount,
api::Field::Language => SortField::Language,
api::Field::Name => SortField::Name,
api::Field::Sha256 => SortField::Sha256,
api::Field::Size => SortField::Size,
api::Field::Complexity => SortField::Complexity,
},
}
}
pub fn import(import: api::Import) -> Import {
let name = import.func.name.to_string();
let f = import.func.into_option().unwrap_or_default();
Import {
module_name: import.module_name,
func: Function {
name,
ty: FunctionType {
params: val_types(f.params),
results: val_types(f.results),
},
},
}
}
pub fn imports(imports: Vec<api::Import>) -> Vec<Import> {
imports.into_iter().map(import).collect()
}
pub fn export(export: api::Export) -> Export {
let name = export.func.name.to_string();
let f = export.func.into_option().unwrap_or_default();
Export {
func: Function {
name,
ty: FunctionType {
params: val_types(f.params),
results: val_types(f.results),
},
},
}
}
pub fn exports(exports: Vec<api::Export>) -> Vec<Export> {
exports.into_iter().map(export).collect()
}
pub fn module(module: &modsurfer_proto_v1::api::Module) -> modsurfer_module::Module {
let modsurfer_module = &mut modsurfer_module::Module {
hash: module.hash.clone(),
imports: imports(module.imports.clone()),
exports: exports(module.exports.clone()),
size: module.size,
location: module.location.clone(),
source_language: source_language(module.source_language.enum_value_or_default()),
metadata: Some(module.metadata.clone()),
strings: module.strings.clone(),
complexity: module.complexity,
graph: module.graph.clone(),
function_hashes: module.function_hashes.clone(),
#[cfg(not(target_arch = "wasm32"))]
inserted_at: chrono::DateTime::from(
chrono::Utc.timestamp_nanos(module.inserted_at.nanos as i64),
),
#[cfg(target_arch = "wasm32")]
inserted_at: module.inserted_at.nanos as u64,
};
return modsurfer_module.clone();
}
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
pub fn search(mut req: api::SearchModulesRequest) -> Search {
Search {
page: req
.pagination
.as_ref()
.map(Pagination::from)
.unwrap_or_default(),
hash: req.hash,
location: req.location,
function_name: req.function_name,
module_name: req.module_name,
inserted_after: req.inserted_after.as_ref().and_then(|x| {
Some(chrono::DateTime::<chrono::Utc>::from_utc(
chrono::NaiveDateTime::from_timestamp_opt(x.seconds, x.nanos as u32)?,
chrono::Utc,
))
}),
inserted_before: req.inserted_before.as_ref().and_then(|x| {
Some(chrono::DateTime::<chrono::Utc>::from_utc(
chrono::NaiveDateTime::from_timestamp_opt(x.seconds, x.nanos as u32)?,
chrono::Utc,
))
}),
strings: if req.strings.is_empty() {
None
} else {
Some(req.strings)
},
sort: req.sort.take().map(sort),
source_language: req
.source_language
.map(|x| source_language(x.enum_value_or_default())),
imports: imports(req.imports),
exports: exports(req.exports),
}
}
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
pub fn audit(req: api::AuditModulesRequest) -> Audit {
Audit {
page: req
.pagination
.as_ref()
.map(Pagination::from)
.unwrap_or_default(),
outcome: types::AuditOutcome::from(req.outcome.enum_value_or_default()),
checkfile: req.checkfile,
}
}
| rust | Apache-2.0 | 71ae2ca8e06917b33281bd0b75843ee60edccba8 | 2026-01-04T20:22:33.912580Z | false |
dylibso/modsurfer | https://github.com/dylibso/modsurfer/blob/71ae2ca8e06917b33281bd0b75843ee60edccba8/convert/src/lib.rs | convert/src/lib.rs | mod types;
pub use types::{Order, Pagination, Sort, SortField};
pub use types::{Audit, AuditOutcome, Search};
pub(crate) use modsurfer_module::SourceLanguage;
pub use modsurfer_proto_v1::api;
pub mod from_api;
pub mod to_api;
| rust | Apache-2.0 | 71ae2ca8e06917b33281bd0b75843ee60edccba8 | 2026-01-04T20:22:33.912580Z | false |
dylibso/modsurfer | https://github.com/dylibso/modsurfer/blob/71ae2ca8e06917b33281bd0b75843ee60edccba8/convert/src/types.rs | convert/src/types.rs | #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
use chrono::Utc;
use modsurfer_module::{Export, Import, SourceLanguage};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Order {
Asc,
Desc,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Pagination {
pub offset: u32,
pub limit: u32,
}
impl Default for Pagination {
fn default() -> Self {
Self {
offset: 0,
limit: 10,
}
}
}
impl<'a> From<&'a modsurfer_proto_v1::api::Pagination> for Pagination {
fn from(page: &'a modsurfer_proto_v1::api::Pagination) -> Self {
Pagination {
offset: page.offset,
limit: page.limit,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SortField {
CreatedAt,
Name,
Size,
Language,
ImportsCount,
ExportsCount,
Sha256,
Complexity,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Sort {
pub order: Order,
pub field: SortField,
}
#[derive(Default)]
pub struct Search {
pub page: Pagination,
pub hash: Option<String>,
pub location: Option<String>,
pub imports: Vec<Import>,
pub exports: Vec<Export>,
pub function_name: Option<String>,
pub module_name: Option<String>,
pub source_language: Option<SourceLanguage>,
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
pub inserted_after: Option<chrono::DateTime<Utc>>,
#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
pub inserted_after: Option<u64>,
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
pub inserted_before: Option<chrono::DateTime<Utc>>,
#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
pub inserted_before: Option<u64>,
pub strings: Option<Vec<String>>,
pub sort: Option<Sort>,
}
#[derive(Debug, Clone)]
pub enum AuditOutcome {
Pass,
Fail,
}
impl std::fmt::Display for AuditOutcome {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
AuditOutcome::Pass => f.write_str("pass"),
_ => f.write_str("fail"),
}
}
}
impl From<&std::ffi::OsStr> for AuditOutcome {
fn from(value: &std::ffi::OsStr) -> Self {
value.to_str().unwrap_or_else(|| "fail").to_string().into()
}
}
impl From<String> for AuditOutcome {
fn from(value: String) -> Self {
match value.to_lowercase().as_str() {
"pass" => AuditOutcome::Pass,
_ => AuditOutcome::Fail,
}
}
}
#[derive(Debug)]
pub struct Audit {
pub page: Pagination,
pub outcome: AuditOutcome,
pub checkfile: Vec<u8>,
}
impl Default for AuditOutcome {
fn default() -> Self {
AuditOutcome::Fail
}
}
impl From<modsurfer_proto_v1::api::AuditOutcome> for AuditOutcome {
fn from(outcome: modsurfer_proto_v1::api::AuditOutcome) -> AuditOutcome {
match outcome {
modsurfer_proto_v1::api::AuditOutcome::PASS => AuditOutcome::Pass,
modsurfer_proto_v1::api::AuditOutcome::FAIL => AuditOutcome::Fail,
}
}
}
impl From<AuditOutcome> for modsurfer_proto_v1::api::AuditOutcome {
fn from(outcome: AuditOutcome) -> Self {
match outcome {
AuditOutcome::Pass => modsurfer_proto_v1::api::AuditOutcome::PASS,
AuditOutcome::Fail => modsurfer_proto_v1::api::AuditOutcome::FAIL,
}
}
}
| rust | Apache-2.0 | 71ae2ca8e06917b33281bd0b75843ee60edccba8 | 2026-01-04T20:22:33.912580Z | false |
dylibso/modsurfer | https://github.com/dylibso/modsurfer/blob/71ae2ca8e06917b33281bd0b75843ee60edccba8/convert/src/to_api.rs | convert/src/to_api.rs | use crate::*;
use modsurfer_module::{Export, Import, Module, ValType};
pub fn source_language(src: SourceLanguage) -> api::SourceLanguage {
match src {
SourceLanguage::Unknown => api::SourceLanguage::Unknown,
SourceLanguage::AssemblyScript => api::SourceLanguage::AssemblyScript,
SourceLanguage::C => api::SourceLanguage::C,
SourceLanguage::Cpp => api::SourceLanguage::Cpp,
SourceLanguage::Go => api::SourceLanguage::Go,
SourceLanguage::Rust => api::SourceLanguage::Rust,
SourceLanguage::Swift => api::SourceLanguage::Swift,
SourceLanguage::JavaScript => api::SourceLanguage::JavaScript,
SourceLanguage::Haskell => api::SourceLanguage::Haskell,
SourceLanguage::Zig => api::SourceLanguage::Zig,
_ => api::SourceLanguage::Unknown,
}
}
pub fn val_types(v: Vec<ValType>) -> Vec<protobuf::EnumOrUnknown<api::ValType>> {
v.into_iter()
.map(|x| protobuf::EnumOrUnknown::new(val_type(x)))
.collect()
}
pub fn val_type(v: ValType) -> api::ValType {
match v {
ValType::I32 => api::ValType::I32,
ValType::I64 => api::ValType::I64,
ValType::F32 => api::ValType::F32,
ValType::F64 => api::ValType::F64,
ValType::V128 => api::ValType::V128,
ValType::FuncRef => api::ValType::FuncRef,
ValType::ExternRef => api::ValType::ExternRef,
}
}
#[cfg(not(target_arch = "wasm32"))]
pub fn module(module: Module, id: i64) -> api::Module {
let mut dest = api::Module::new();
dest.id = id;
dest.location = module.location;
dest.hash = module.hash;
dest.metadata = module.metadata.unwrap_or_default();
dest.size = module.size as u64;
dest.source_language = protobuf::EnumOrUnknown::new(source_language(module.source_language));
dest.inserted_at =
protobuf::MessageField::some(protobuf::well_known_types::timestamp::Timestamp {
seconds: module.inserted_at.timestamp(),
nanos: module.inserted_at.timestamp_subsec_nanos() as i32,
special_fields: protobuf::SpecialFields::new(),
});
dest.exports = exports(module.exports);
dest.imports = imports(module.imports);
dest.strings = module.strings;
dest.complexity = module.complexity;
dest.function_hashes = module.function_hashes;
dest
}
#[cfg(target_arch = "wasm32")]
pub fn module(module: Module, id: i64) -> api::Module {
let mut dest = api::Module::new();
dest.id = id;
dest.location = module.location;
dest.hash = module.hash;
dest.metadata = module.metadata.unwrap_or_default();
dest.size = module.size as u64;
dest.source_language = protobuf::EnumOrUnknown::new(source_language(module.source_language));
dest.exports = exports(module.exports);
dest.imports = imports(module.imports);
dest.strings = module.strings;
dest.complexity = module.complexity;
dest.function_hashes = module.function_hashes;
dest
}
pub fn exports(exports: Vec<Export>) -> Vec<api::Export> {
exports
.into_iter()
.map(|e| {
let func = api::Function {
name: e.func.name,
params: to_api::val_types(e.func.ty.params),
results: to_api::val_types(e.func.ty.results),
..Default::default()
};
api::Export {
func: protobuf::MessageField::some(func),
..Default::default()
}
})
.collect()
}
pub fn imports(imports: Vec<Import>) -> Vec<api::Import> {
imports
.into_iter()
.map(|i| {
let func = api::Function {
name: i.func.name,
params: to_api::val_types(i.func.ty.params),
results: to_api::val_types(i.func.ty.results),
..Default::default()
};
api::Import {
func: protobuf::MessageField::some(func),
module_name: i.module_name,
..Default::default()
}
})
.collect()
}
| rust | Apache-2.0 | 71ae2ca8e06917b33281bd0b75843ee60edccba8 | 2026-01-04T20:22:33.912580Z | false |
ntrupin/abstractml | https://github.com/ntrupin/abstractml/blob/69342d60c6000412d6e1a202b92ac600063dde71/experimental/precompiler.rs | experimental/precompiler.rs | use std::process;
use std::env;
use std::io::Write;
use std::fs::File;
use std::io::{BufRead, BufReader};
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
println!("Please enter the aml file that must be compiled.");
process::exit(1);
}
let filename = &args[1];
let file = File::open(filename).unwrap();
let reader = BufReader::new(file);
let mut new_data: Vec<String> = [].to_vec();
for (index, line) in reader.lines().enumerate() {
let line = line.unwrap();
let new_line = parse(index, line);
new_data.push(new_line);
}
let data = new_data.join("\n");
let mut f = File::create(format!("{}.html", filename)).expect("AML Error: Unable to create file.");
f.write_all(data.as_bytes()).expect("AML Error: Unable to write data.");
}
fn error(msg: String) {
println!("{}", msg);
process::exit(1);
}
fn parse(index: usize, line: String) -> String {
let new_line: String = line.clone();
let line_splited: Vec<&str> = line.split("->").collect();
let tagname = line_splited[0].trim();
let mut part_one = "";
let mut part_two = "";
if tagname != "" {
if line_splited.len() == 2 || line_splited.len() > 1 {
part_one = line_splited[1].trim();
}
if line_splited.len() == 3 || line_splited.len() > 2 {
part_two = line_splited[2].trim();
}
match tagname {
"h1"|"h2"|"h3"|"h4"|"h5"|"h6"|"p"|"time"|"a"|"abbr"|"button"|"li"|"small"|"b"|"s"|"strong"|"u"|"title" => {
if part_one == "" {
return format!("<{0}></{0}>", tagname);
} else {
if part_two == "" {
return format!("<{0}>{1}</{0}>", tagname, part_one);
} else {
return format!("<{0} {1}>{2}</{0}>", tagname, part_one, part_two);
}
}
}
"div"|"textarea"|"script"|"section"|"article"|"span"|"center"|"header"|"nav"|"main"|"form"|"table"|"th"|"tr"|"td"|"pre"|"code"|"ol"|"ul" => {
if part_one == "" {
return format!("<{0}>", tagname);
} else {
if part_two == "" {
return format!("<{0} {1}>", tagname, part_one);
} else {
return format!("<{0} {1}>{2}</{0}>", tagname, part_one, part_two);
}
}
}
"input" => {
if part_one == "" {
return format!("<{0} />", tagname);
} else {
return format!("<{0} {1} />", tagname, part_one);
}
}
"hr"|"br" => {
if part_one == "" {
return format!("<{0}>", tagname);
} else {
return format!("<{0} {1}>", tagname, part_one);
}
}
"img" => {
if part_one == "" {
return format!("<img>");
} else {
if part_two == "" {
return format!("<img src={0}>", part_one);
} else {
return format!("<img src={0} {1}>", part_one, part_two);
}
}
}
"meta" => {
if part_one == "" {
return format!("<meta>");
} else {
if part_two == "" {
return format!("<meta name={0}>", part_one);
} else {
return format!("<meta name={0} content={1}>", part_one, part_two);
}
}
}
"charset" => {
if part_one == "" {
return format!("<meta http-equiv=\"Content-Type\" content=\"text/html;charset=UTF-8\">");
} else {
return format!("<meta http-equiv=\"Content-Type\" content=\"text/html;charset={}\">", part_one);
}
}
"link" => {
if part_one == "" {
return format!("<{0}>", tagname);
} else {
if part_two == "" {
return format!("<{0} rel={1}>", tagname, part_one);
} else {
return format!("<{0} rel={1} href={2}>", tagname, part_one, part_two);
}
}
}
"end" => {
if part_one == "" {
return format!("</div>");
} else {
return format!("</{0}>", part_one);
}
}
"//" => {
if part_one == "" {
return format!("<!-- -->");
} else {
return format!("<!-- {0} -->", part_one);
}
}
_ => {
error(format!("AML Error: Cannot identify the tagname `{}` in line {}", tagname, index + 1));
}
}
}
return new_line;
} | rust | Apache-2.0 | 69342d60c6000412d6e1a202b92ac600063dde71 | 2026-01-04T20:23:30.282616Z | false |
hlsxx/tukai | https://github.com/hlsxx/tukai/blob/c7c380ec133362c2f2e04d6cb9e1e2b77fd411be/src/config.rs | src/config.rs | use ratatui::style::Style;
use rust_embed::RustEmbed;
use std::cell::{Ref, RefCell, RefMut};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::{collections::HashMap, fmt::Display, hash::Hash};
use maplit::hashmap;
use ratatui::style::Color;
pub trait ToColor {
/// Converts the `(u8, u8, u8)` tuple to a `Color::Rgb`
///
/// # Example
///
/// ```
/// use ratatui::style::Color
///
/// let rgb: (u8, u8, u8) = (128, 64, 255);
/// let color = rgb.to_color();
///
/// assert_eq!(color, Color::Rgb(128, 64, 255));
/// ```
fn to_color(self) -> Color;
}
/// Type alias for representing an RGB color as a tuple
type RgbColor = (u8, u8, u8);
impl ToColor for RgbColor {
fn to_color(self) -> Color {
Color::Rgb(self.0, self.1, self.2)
}
}
/// Represents possible color combinations and preset types used in the layout.
///
/// Variants correspond to different semantic roles for colors:
/// - `Primary`: Main accent color.
/// - `Secondary`: Secondary accent color.
/// - `Text`: Standard text color.
/// - `TextReverse`: Inverted text color for contrast.
/// - `Background`: Background color.
/// - `Error`: Color used to indicate errors.
#[allow(dead_code)]
pub enum TukaiLayoutColorTypeEnum {
Primary,
Secondary,
Text,
TextReverse,
Background,
Error,
}
/// Layout name for Tukai application
/// Used for a switchable layout colors
///
/// Switchable with a `ctrl-s` shortcut
#[derive(PartialEq, Eq, Hash, Debug, Serialize, Deserialize, Clone)]
pub enum TukaiLayoutName {
Iced,
Rust,
Anime,
Deadpool,
Wolverine,
Goblin,
}
/// Display used in the Tukai paragraph block_title
impl Display for TukaiLayoutName {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
use TukaiLayoutName::*;
let display_text = match self {
Iced => "🥶 Iced",
Rust => "🦀 Rust",
Anime => "🌸 Anime",
Deadpool => "🩸🔞 Deadpool",
Wolverine => "💪🍺 Wolverine",
Goblin => "🌳 Goblin",
};
write!(f, "{display_text}")
}
}
/// Set of the colors used in the application.
pub struct TukaiLayoutColors {
primary: RgbColor,
text: RgbColor,
text_current: RgbColor,
text_current_bg: RgbColor,
background: RgbColor,
error: RgbColor,
}
impl TukaiLayoutColors {
pub fn new(
primary: RgbColor,
text: RgbColor,
text_current: RgbColor,
text_current_bg: RgbColor,
background: RgbColor,
error: RgbColor,
) -> Self {
Self {
primary,
text,
text_current,
text_current_bg,
background,
error,
}
}
}
/// Tukai layout includes all layouts
/// also, contains `transitions`, and the current selected layout name
pub struct TukaiLayout {
// Set of the layouts
layouts: HashMap<TukaiLayoutName, TukaiLayoutColors>,
// Rules for switchable transition of the layout
transitions: HashMap<TukaiLayoutName, TukaiLayoutName>,
// Current selected layout name
active_layout_name: TukaiLayoutName,
}
impl TukaiLayout {
pub fn default() -> Self {
use TukaiLayoutName::*;
let layouts = hashmap! {
Iced => {
TukaiLayoutColors::new(
(108, 181, 230),
(232, 232, 232),
(25, 74, 107),
(200, 200, 200),
(37, 40, 46),
(214, 90, 90),
)
},
Anime => {
TukaiLayoutColors::new(
(152, 117, 201),
(222, 135, 174),
(49, 45, 51),
(222, 170, 146),
(31, 27, 30),
(227, 138, 138),
)
},
Deadpool => {
TukaiLayoutColors::new(
(139, 35, 35),
(210, 210, 210),
(23, 23, 23),
(210, 210, 210),
(33, 29, 29),
(110, 110, 110),
)
},
Wolverine => {
TukaiLayoutColors::new(
(196, 166, 51),
(200, 200, 200),
(23,23,23),
(210, 210, 210),
(10, 14, 18),
(110, 110, 110),
)
},
Rust => {
TukaiLayoutColors::new(
(150, 63, 17),
(255, 178, 137),
(255, 178, 137),
(150, 63, 17),
(24, 8, 2),
(120, 120, 120),
)
},
Goblin => {
TukaiLayoutColors::new(
(82, 140, 25),
(136, 207, 66),
(220, 220, 220),
(39, 61, 17),
(32, 36, 30),
(117, 71, 56),
)
}
};
// Define transtions for switch order
let transitions = HashMap::from([
(Iced, Anime),
(Anime, Deadpool),
(Deadpool, Wolverine),
(Wolverine, Rust),
(Rust, Goblin),
(Goblin, Iced),
]);
Self {
layouts,
transitions,
active_layout_name: TukaiLayoutName::Iced,
}
}
/// Returns the currect active layout name
pub fn get_active_layout_name(&self) -> &TukaiLayoutName {
&self.active_layout_name
}
/// Sets a new active layout name
pub fn active_layout_name(&mut self, active_layout_name: TukaiLayoutName) {
self.active_layout_name = active_layout_name;
}
/// Switches to a next layout, then returns that layout
///
/// Check `self.transitions`.
pub fn switch_to_next_layout(&mut self) -> TukaiLayoutName {
if let Some(next_layout_name) = self.transitions.get(&self.active_layout_name) {
self.active_layout_name = next_layout_name.clone();
};
self.active_layout_name.clone()
}
fn get_layout_colors(&self) -> &TukaiLayoutColors {
self.layouts.get(&self.active_layout_name).unwrap()
}
pub fn get_primary_color(&self) -> Color {
self.get_layout_colors().primary.to_color()
}
pub fn get_text_color(&self) -> Color {
self.get_layout_colors().text.to_color()
}
pub fn get_text_current_color(&self) -> Color {
self.get_layout_colors().text_current.to_color()
}
pub fn get_text_current_bg_color(&self) -> Color {
self.get_layout_colors().text_current_bg.to_color()
}
pub fn get_error_color(&self) -> Color {
self.get_layout_colors().error.to_color()
}
pub fn get_background_color(&self) -> Color {
self.get_layout_colors().background.to_color()
}
}
#[derive(RustEmbed)]
#[folder = "dictionary/"]
struct LanguageDictionary;
pub struct Language {
// Language files paths from the `words` folder
language_files: Vec<String>,
// Current used language index
current_index: usize,
// Current used language shortcut
lang_code: String,
// Current selected language words
words: Vec<String>,
}
impl Language {
// Creates default empty list of the language files
pub fn default() -> Self {
Self {
language_files: Vec::new(),
current_index: 0,
lang_code: String::from("en"),
words: Vec::new(),
}
}
pub fn init_lang_code(&mut self) {
let filename = &self.language_files[self.current_index];
let lang_code = Path::new(filename)
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("unknown")
.to_string();
self.lang_code = lang_code;
}
/// Load language files from the `words` folder
pub fn init(mut self) -> Self {
if let Ok(language_files) = self.load_language_files() {
self.language_files = language_files;
}
// If language dictionary files were founded
// Sets the words
if !self.language_files.is_empty()
&& let Ok(words) = self.load_language_words()
{
self.words = words;
}
self
}
pub fn current_index(&mut self, index: usize) {
self.current_index = index;
self.init_lang_code();
}
#[allow(unused)]
pub fn get_current_index(&self) -> &usize {
&self.current_index
}
/// Switches a current language
pub fn switch_language(&mut self) -> usize {
self.current_index += 1;
if self.current_index >= self.language_files.len() {
self.current_index = 0;
}
self.init_lang_code();
self.current_index
}
/// Returns the paths of all available language files in the `words` folder.
///
/// So i.e. available languages
pub fn load_language_files(&self) -> Result<Vec<String>, Box<dyn std::error::Error>> {
let languages = LanguageDictionary::iter()
.map(|file| file.to_string())
.collect::<Vec<String>>();
// Maybe in feature manual load custom languages
//
// let languages = entries
// .filter_map(|entry| entry.ok())
// .filter(|entry| entry.path().is_file())
// .map(|entry| entry.path())
// .collect::<Vec<PathBuf>>();
Ok(languages)
}
/// Returns current selected languages words from the language file
///
/// So i.e. language words
pub fn load_language_words(&self) -> Result<Vec<String>, Box<dyn std::error::Error>> {
let language_file_path = self
.language_files
.get(self.current_index)
.ok_or("Not found a language dictionary file")?;
let file = LanguageDictionary::get(language_file_path).unwrap();
let words = std::str::from_utf8(&file.data)?
.lines()
.flat_map(|line| {
line
.split_whitespace()
.map(String::from)
.collect::<Vec<String>>()
})
.collect::<Vec<String>>();
Ok(words)
}
pub fn get_lang_code(&self) -> &String {
&self.lang_code
}
}
#[derive(Serialize, Deserialize, Hash, PartialEq, Eq, Debug, Clone)]
/// Represents the available durations for the test
///
/// This enum defines default durations
///
/// # Variants
/// - `ThirtySec` - 30 seconds typing duration
/// - `Minute` - 60 seconds typing duration
/// - `ThreeMinutes` - 180 seconds typing duration
pub enum TypingDuration {
FifteenSec,
ThirtySec,
Minute,
ThreeMinutes,
}
impl Default for TypingDuration {
fn default() -> Self {
Self::Minute
}
}
impl TypingDuration {
pub fn as_seconds(&self) -> usize {
use TypingDuration::*;
match self {
FifteenSec => 15,
ThirtySec => 30,
Minute => 60,
ThreeMinutes => 180,
}
}
}
#[allow(unused)]
pub trait ConfigBuilder<T> {
fn new() -> Self;
fn build(self) -> T;
}
pub struct TukaiConfig {
// Path to the storage file
file_path: PathBuf,
// Choosen layout
layout: RefCell<TukaiLayout>,
// Current language
language: RefCell<Language>,
// App background is transparent
pub has_transparent_bg: bool,
// Typing duration
pub typing_duration: TypingDuration,
}
impl TukaiConfig {
pub fn default() -> Self {
Self {
file_path: PathBuf::from("tukai.bin"),
layout: RefCell::new(TukaiLayout::default()),
language: RefCell::new(Language::default().init()),
has_transparent_bg: false,
typing_duration: TypingDuration::default(),
}
}
pub fn get_layout(&self) -> Ref<'_, TukaiLayout> {
self.layout.borrow()
}
pub fn get_language(&self) -> Ref<'_, Language> {
self.language.borrow()
}
pub fn get_layout_mut(&mut self) -> RefMut<'_, TukaiLayout> {
self.layout.borrow_mut()
}
pub fn get_language_mut(&mut self) -> RefMut<'_, Language> {
self.language.borrow_mut()
}
pub fn get_file_path(&self) -> &PathBuf {
&self.file_path
}
/// Toggles the background between transparent and the layout color.
///
/// Flips the `has_transparent_bg` flag and returns the updated state.
///
/// # Returns
/// The new state of the background transparency (`true` if transparent, `false` otherwise).
pub fn toggle_transparent_bg(&mut self) -> bool {
self.has_transparent_bg = !self.has_transparent_bg;
self.has_transparent_bg
}
/// Switches the typing duration.
///
/// Options:
/// 1. Minute
/// 2. Three minutes
/// 3. Fifteen seconds
/// 4. Thirty seconds
pub fn switch_typing_duration(&mut self) -> TypingDuration {
self.typing_duration = match self.typing_duration {
TypingDuration::Minute => TypingDuration::ThreeMinutes,
TypingDuration::ThreeMinutes => TypingDuration::FifteenSec,
TypingDuration::FifteenSec => TypingDuration::ThirtySec,
TypingDuration::ThirtySec => TypingDuration::Minute,
};
self.typing_duration.clone()
}
/// Returns the background color of the selected layout.
///
/// If `has_transparent_bg` is `true`, no background color is applied.
pub fn get_bg_color(&self) -> Style {
let style = Style::default();
if self.has_transparent_bg {
style
} else {
style.bg(self.get_layout().get_background_color())
}
}
}
pub struct TukaiConfigBuilder {
// Path to the `language file`
file_path: Option<PathBuf>,
// Selected layout
layout: Option<RefCell<TukaiLayout>>,
// Selected language
language: Option<RefCell<Language>>,
// Has application background transparent
has_transparent_bg: bool,
// Typing duration per run
typing_duration: Option<TypingDuration>,
}
impl TukaiConfigBuilder {
pub fn new() -> Self {
Self {
file_path: None,
layout: None,
language: None,
has_transparent_bg: true,
typing_duration: None,
}
}
#[allow(unused)]
pub fn file_path<P: AsRef<Path>>(mut self, file_path: P) -> Self {
self.file_path = Some(file_path.as_ref().to_path_buf());
self
}
#[allow(unused)]
pub fn layout(mut self, layout: TukaiLayout) -> Self {
self.layout = Some(RefCell::new(layout));
self
}
pub fn build(self) -> TukaiConfig {
let config_default = TukaiConfig::default();
TukaiConfig {
file_path: self.file_path.unwrap_or(config_default.file_path),
layout: self.layout.unwrap_or(config_default.layout),
language: self.language.unwrap_or(config_default.language),
has_transparent_bg: self.has_transparent_bg,
typing_duration: self
.typing_duration
.unwrap_or(config_default.typing_duration),
}
}
}
| rust | MIT | c7c380ec133362c2f2e04d6cb9e1e2b77fd411be | 2026-01-04T20:23:37.632912Z | false |
hlsxx/tukai | https://github.com/hlsxx/tukai/blob/c7c380ec133362c2f2e04d6cb9e1e2b77fd411be/src/app.rs | src/app.rs | use crate::config::TukaiConfig;
use crate::event_handler::{EventHandler, TukaiEvent};
use crate::screens::ActiveScreenEnum;
use crate::screens::repeat::RepeatScreen;
use crate::screens::{Screen, stats::StatsScreen, typing::TypingScreen};
use crate::storage::storage_handler::StorageHandler;
use std::{cell::RefCell, rc::Rc};
use ratatui::Terminal;
use ratatui::prelude::CrosstermBackend;
use ratatui::{
Frame,
crossterm::event::{KeyCode, KeyEvent, KeyModifiers},
layout::{Constraint, Layout},
};
use anyhow::Result;
type TukaiTerminal = Terminal<CrosstermBackend<std::io::Stdout>>;
pub struct Tukai<'a> {
// App config
pub config: Rc<RefCell<TukaiConfig>>,
// Handles a crossterm keyboard events
event_handler: &'a mut EventHandler,
// Storage handler
storage_handler: StorageHandler,
// App was terminated
is_terminated: bool,
// Displayed screen (typing|stats)
screen: Box<dyn Screen>,
}
impl<'a> Tukai<'a> {
/// Attempts to create a new Tukai application.
/// Tries to initialize `StorageHandler` then load
/// an existing saved settings file.
pub fn try_new(event_handler: &'a mut EventHandler, mut config: TukaiConfig) -> Result<Self> {
let storage_handler = StorageHandler::new(config.get_file_path()).init()?;
config.typing_duration = storage_handler.get_typing_duration();
config.has_transparent_bg = storage_handler.get_has_transparent_bg();
{
let mut layout = config.get_layout_mut();
layout.active_layout_name(storage_handler.get_layout_name().clone());
}
{
let mut language = config.get_language_mut();
language.current_index(storage_handler.get_language_index());
}
let config = Rc::new(RefCell::new(config));
let typing_screen = TypingScreen::new(Rc::clone(&config));
Ok(Self {
config,
event_handler,
storage_handler,
is_terminated: false,
screen: Box::new(typing_screen),
})
}
/// Runs and renders tui components.
///
/// Handles events from `EventHandler`
/// Handles tick (seconds, it's time counter) from `EventHandler`
pub async fn run(&mut self, terminal: &mut TukaiTerminal) -> Result<()> {
while !self.is_terminated {
match self.event_handler.next().await? {
TukaiEvent::Key(key_event) => self.handle_events(key_event),
TukaiEvent::Tick => {
if self.screen.is_running() {
self.screen.increment_time_secs();
}
}
};
if self.screen.get_remaining_time() == 0 {
self.screen.stop(&mut self.storage_handler);
}
terminal.draw(|frame| self.draw(frame))?;
}
Ok(())
}
/// Renders TUI components of the current
/// selected screen.
fn draw(&mut self, frame: &mut Frame) {
let main_layout = Layout::default()
.constraints(vec![Constraint::Min(0), Constraint::Length(3)])
.split(frame.area());
self.screen.render(frame, main_layout[0]);
self.screen.render_instructions(frame, main_layout[1]);
if self.screen.is_popup_visible() {
self.screen.render_popup(frame);
}
}
/// Resets the application
fn reset(&mut self) {
self.screen.reset();
}
/// Exits the running application
///
/// Attempts to flush storage data before sets the `is_terminated`.
fn exit(&mut self) {
self.is_terminated = true;
self
.storage_handler
.flush()
.expect("Error occured while saving into the file");
}
/// Switches active `screen`.
///
/// Hides the currently active screen.
/// Sets the `active_screen` to the switched screen
fn switch_screen(&mut self, switch_to_screen: ActiveScreenEnum) {
self.screen = match switch_to_screen {
ActiveScreenEnum::Typing => Box::new(TypingScreen::new(self.config.clone())),
ActiveScreenEnum::Repeat => Box::new(RepeatScreen::new(self.config.clone())),
ActiveScreenEnum::Stats => Box::new(StatsScreen::new(self.config.clone())),
}
}
/// Handles crossterm events.
///
/// First, checks for events with the pressed control button.
/// Then, handles `screen` events (TypingScreen).
/// Finally, processes remainig keys.
fn handle_events(&mut self, key_event: KeyEvent) {
if key_event.modifiers.contains(KeyModifiers::CONTROL) {
// Handle screen specific CTRL key events
if self.screen.handle_control_events(key_event) {
return;
}
if let KeyCode::Char(c) = key_event.code {
match c {
'r' => self.reset(),
'l' => {
if let Some(next_screen) = self.screen.get_next_screen() {
self.switch_screen(next_screen);
}
}
'h' => {
if let Some(previous_screen) = self.screen.get_previous_screen() {
self.switch_screen(previous_screen);
}
}
'c' => self.exit(),
'd' => {
self
.storage_handler
.set_typing_duration(self.config.borrow_mut().switch_typing_duration());
self.reset();
}
't' => {
let new_state = self.config.borrow_mut().toggle_transparent_bg();
self.storage_handler.set_transparent_bg(new_state);
}
's' => {
let new_layout = self
.config
.borrow_mut()
.get_layout_mut()
.switch_to_next_layout();
self.storage_handler.set_layout(new_layout);
}
'p' => {
// switches language
let new_language_index = self
.config
.borrow_mut()
.get_language_mut()
.switch_language();
self.storage_handler.set_language_index(new_language_index);
self.reset();
}
_ => {}
}
}
return;
}
if self.screen.handle_events(key_event) {
return;
}
if key_event.code == KeyCode::Esc {
self.exit();
} else if key_event.code == KeyCode::Left
&& let Some(previous_screen) = self.screen.get_previous_screen()
{
self.switch_screen(previous_screen);
} else if key_event.code == KeyCode::Right
&& let Some(next_screen) = self.screen.get_next_screen()
{
self.switch_screen(next_screen);
}
}
}
| rust | MIT | c7c380ec133362c2f2e04d6cb9e1e2b77fd411be | 2026-01-04T20:23:37.632912Z | false |
hlsxx/tukai | https://github.com/hlsxx/tukai/blob/c7c380ec133362c2f2e04d6cb9e1e2b77fd411be/src/helper.rs | src/helper.rs | use std::iter::repeat_n;
use crate::config::TukaiConfig;
use rand::{Rng, seq::SliceRandom};
pub struct Generator;
impl Generator {
/// Loads a list of words from the current language from the configuration.
///
/// This method attempts to read words from the language specified
/// in the provided [`TukaiConfig`]. If the word list cannot be readed
/// (e.g., the file is missing or unreadable), it returns an empty vector.
pub fn get_words(config: &TukaiConfig) -> Vec<String> {
config
.get_language()
.load_language_words()
.unwrap_or_default()
}
/// Generates a random string composed of words from a language-specific word list.
///
/// This method reads words from a `words/{language}.txt` file based on the language
/// setting in the provided [`TukaiConfig`] and returns a randomly generated string.
///
/// # Parameters
/// - `config`: A reference to a [`TukaiConfig`] instance containing configuration options,
/// including the language to use.
///
/// # Returns
/// A `String` composed of randomly selected words.
pub fn generate_random_string(config: &TukaiConfig) -> String {
let mut rng = rand::thread_rng();
Generator::get_words(config)
.choose_multiple(&mut rng, config.typing_duration.as_seconds() * 2)
.fold(String::new(), |mut acc, c| {
acc.push_str(format!("{c} ").as_str());
acc
})
}
/// Generates a repeated word string based on the provided configuration.
///
/// The word and the number of repetitions are taken from the [`TukaiConfig`] instance.
/// This is useful for producing visual effects like emphasis or animation in text-based UIs.
///
/// # Parameters
/// - `config`: A reference to a [`TukaiConfig`] instance containing configuration options,
/// including the language to use.
///
/// # Returns
/// A `String` composed of randomly selected multiple times repeated word.
pub fn generate_repeated_word(config: &TukaiConfig) -> String {
let mut rng = rand::thread_rng();
let word = Generator::get_words(config)
.choose(&mut rng)
.cloned()
.unwrap_or(String::from("Hello"));
repeat_n(word, 50).collect::<Vec<String>>().join(" ")
}
/// Generates and returns a random motto string.
///
/// This could be used, for example, in a screen footer.
/// # Returns
/// A random motto `String` selected from a predefined list of mottos.
pub fn generate_random_motto() -> String {
let mottos = [
" Practice today, master tomorrow ",
" Fingers on keys, progress with ease ",
" Consistency breeds accuracy ",
" Type smarter, not harder ",
" Precision today, perfection tomorrow ",
];
let mut rng = rand::thread_rng();
let random_index = rng.gen_range(0..mottos.len());
String::from(mottos[random_index])
}
}
| rust | MIT | c7c380ec133362c2f2e04d6cb9e1e2b77fd411be | 2026-01-04T20:23:37.632912Z | false |
hlsxx/tukai | https://github.com/hlsxx/tukai/blob/c7c380ec133362c2f2e04d6cb9e1e2b77fd411be/src/event_handler.rs | src/event_handler.rs | use std::time::Duration;
use anyhow::{Result, anyhow};
use ratatui::crossterm::event::{Event, EventStream, KeyEvent};
#[cfg(target_os = "windows")]
use ratatui::crossterm::event::KeyEventKind;
use tokio::sync::mpsc;
use futures::{FutureExt, StreamExt};
/// Represents events generated by the Tukai application.
///
/// - `Tick`: A periodic timer event used for time remainder on the typing screen.
/// - `Key`: An event representing a keyboard input, resolution change, wrapping a [`KeyEvent`].
#[derive(Clone, Copy, Debug)]
pub enum TukaiEvent {
Tick,
Key(KeyEvent),
}
/// Handles sending and receiving `TukaiEvent`s asynchronously.
///
/// This struct wraps an unbounded channel sender and receiver pair,
/// allowing for event-driven communication within the application.
///
/// - `_tx`: The sending half of the channel for emitting `TukaiEvent`s.
/// - `rx`: The receiving half of the channel for consuming `TukaiEvent`s.
pub struct EventHandler {
_tx: mpsc::UnboundedSender<TukaiEvent>,
rx: mpsc::UnboundedReceiver<TukaiEvent>,
}
impl EventHandler {
/// Spawns a background asynchronous task that:
/// - Listens for terminal input events and forwards keyboard events as `TukaiEvent::Key`.
/// - Sends periodic `TukaiEvent::Tick` events every second.
///
/// The event loop uses Tokio’s async runtime and crossterm’s `EventStream` to handle input.
pub fn new() -> Self {
let tick_rate = Duration::from_secs(1);
let (_tx, rx) = mpsc::unbounded_channel::<TukaiEvent>();
let tx_clone = _tx.clone();
tokio::spawn(async move {
let mut reader = EventStream::new();
let mut interval = tokio::time::interval(tick_rate);
loop {
let tick_delay = interval.tick();
let crossterm_event = reader.next().fuse();
tokio::select! {
Some(Ok(Event::Key(key_event))) = crossterm_event => {
// On Windows terminal takes press and release
// To avoid symbols duplications checks a event kind
#[cfg(target_os = "windows")]
{
if key_event.kind != KeyEventKind::Press {
continue
}
}
tx_clone.send(TukaiEvent::Key(key_event)).unwrap();
},
_ = tick_delay => {
tx_clone.send(TukaiEvent::Tick).unwrap();
},
}
}
});
Self { _tx, rx }
}
/// Asynchronously received the next `TukaiEvent` from the event channel.
///
/// # Returns
/// A [`Result`] containing the next `TukaiEvent` on success,
/// or an error if the event stream has been closed.
pub async fn next(&mut self) -> Result<TukaiEvent> {
self
.rx
.recv()
.await
.ok_or_else(|| anyhow!("Some IO error occurred"))
}
}
| rust | MIT | c7c380ec133362c2f2e04d6cb9e1e2b77fd411be | 2026-01-04T20:23:37.632912Z | false |
hlsxx/tukai | https://github.com/hlsxx/tukai/blob/c7c380ec133362c2f2e04d6cb9e1e2b77fd411be/src/main.rs | src/main.rs | mod app;
mod config;
mod file_handler;
mod event_handler;
mod helper;
mod screens;
mod storage;
use anyhow::Result;
use app::Tukai;
use config::TukaiConfigBuilder;
use event_handler::EventHandler;
#[tokio::main]
async fn main() -> Result<()> {
let mut terminal = ratatui::init();
let mut event_handler = EventHandler::new();
let app_config = TukaiConfigBuilder::new().build();
terminal.clear()?;
let app_result = Tukai::try_new(&mut event_handler, app_config)?
.run(&mut terminal)
.await;
ratatui::restore();
app_result
}
| rust | MIT | c7c380ec133362c2f2e04d6cb9e1e2b77fd411be | 2026-01-04T20:23:37.632912Z | false |
hlsxx/tukai | https://github.com/hlsxx/tukai/blob/c7c380ec133362c2f2e04d6cb9e1e2b77fd411be/src/file_handler.rs | src/file_handler.rs | use std::{
fs::{File, OpenOptions, create_dir_all},
io::{Read, Write},
path::Path,
};
use anyhow::{Error, Result};
pub struct FileHandler;
impl FileHandler {
/// Opens a file for reading and writing, creating it if it does not exist.
///
/// If the file at the specified path exists, it is opened with read/write access.
/// If it does not exist, a new file is created.
///
/// # Parameters
/// - `path`: A path to the file to open or create.
///
/// # Returns
/// A [`Result`] containing the opened [`File`] on success, or an error on failure.
#[allow(clippy::suspicious_open_options)]
fn open_file<P: AsRef<Path>>(path: P) -> Result<File> {
let path_buf = path.as_ref().to_path_buf();
if let Some(parent_dir) = path_buf.parent() {
create_dir_all(parent_dir)?;
}
OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(path)
.map_err(Error::from)
}
/// Writes the given bytes into a file at the specified path.
///
/// This function opens the file (creating it if it doesn’t exist),
/// writes all the provided bytes to it, and then closes the file.
///
/// # Parameters
/// - `path`: The path to the file where the bytes will be written.
/// - `bytes`: A byte slice containing the data to write.
///
/// # Returns
/// A [`Result`] which is [`Ok`] if the operation succeeds,
/// or an error if opening or writing to the file fails.
pub fn write_bytes_into_file<P: AsRef<Path>>(path: P, bytes: &[u8]) -> Result<()> {
let mut file = FileHandler::open_file(path)?;
file.write_all(bytes)?;
Ok(())
}
/// Reads all bytes from the file at the specified path into a buffer.
///
/// This function opens the file for reading, reads its entire contents
/// into a `Vec<u8>`, and returns the buffer.
///
/// # Parameters
/// - `path`: The path to the file to read from.
///
/// # Returns
/// A [`Result`] containing a vector of bytes read from the file,
/// or an error if the file could not be opened or read.
pub fn read_bytes_from_file<P: AsRef<Path>>(path: P) -> Result<Vec<u8>> {
let mut bytes_buf = Vec::new();
let mut file = FileHandler::open_file(path)?;
file.read_to_end(&mut bytes_buf)?;
Ok(bytes_buf)
}
}
| rust | MIT | c7c380ec133362c2f2e04d6cb9e1e2b77fd411be | 2026-01-04T20:23:37.632912Z | false |
hlsxx/tukai | https://github.com/hlsxx/tukai/blob/c7c380ec133362c2f2e04d6cb9e1e2b77fd411be/src/storage/stats.rs | src/storage/stats.rs | use super::stat_helper::StatHelper;
use crate::config::TypingDuration;
use ratatui::{
style::{Color, Style},
text::{Line, Span},
};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct Stat {
typing_duration: TypingDuration,
average_wpm: usize,
raw_wpm: usize,
accuracy: f64,
true_accuracy: f64,
}
impl Stat {
/// Creates a new Stat
///
/// Calculates the:
/// * WPM
/// * Raw WPM
/// * Accuracy
pub fn new(
typing_duration: TypingDuration,
chars_counter: usize,
mistakes_counter: usize,
true_mistakes_counter: usize,
) -> Self {
let typing_duration_in_seconds = typing_duration.as_seconds();
Self {
typing_duration: typing_duration.clone(),
average_wpm: StatHelper::get_calculated_wpm(
chars_counter,
mistakes_counter,
typing_duration_in_seconds,
),
raw_wpm: StatHelper::get_calculated_raw_wpm(chars_counter, typing_duration_in_seconds),
accuracy: StatHelper::get_calculated_accuracy(chars_counter, mistakes_counter),
true_accuracy: StatHelper::get_calculated_accuracy(chars_counter, true_mistakes_counter),
}
}
/// Returns the average wpm
pub fn get_average_wpm(&self) -> usize {
self.average_wpm
}
/// Returns the duration
pub fn get_time_difficulty(&self) -> Span<'static> {
match self.typing_duration {
TypingDuration::FifteenSec => {
Span::from(" (Super short)").style(Style::default().fg(Color::Cyan))
}
TypingDuration::ThirtySec => Span::from(" (Short)").style(Style::default().fg(Color::Green)),
TypingDuration::Minute => Span::from(" (Medium)").style(Style::default().fg(Color::Yellow)),
TypingDuration::ThreeMinutes => Span::from(" (Long)").style(Style::default().fg(Color::Red)),
}
}
/// Returns the duration
pub fn get_duration_pretty(&self) -> Line<'static> {
Line::from(vec![
Span::from(format!("{}s", self.typing_duration.as_seconds())),
self.get_time_difficulty(),
])
}
/// Returns the raw WPM
pub fn get_raw_wpm(&self) -> usize {
self.raw_wpm
}
/// Returns the accuracy
pub fn get_accuracy(&self) -> f64 {
self.accuracy
}
pub fn get_true_accuracy(&self) -> f64 {
self.true_accuracy
}
}
| rust | MIT | c7c380ec133362c2f2e04d6cb9e1e2b77fd411be | 2026-01-04T20:23:37.632912Z | false |
hlsxx/tukai | https://github.com/hlsxx/tukai/blob/c7c380ec133362c2f2e04d6cb9e1e2b77fd411be/src/storage/mod.rs | src/storage/mod.rs | pub mod stat_helper;
pub mod stats;
pub mod storage_handler;
| rust | MIT | c7c380ec133362c2f2e04d6cb9e1e2b77fd411be | 2026-01-04T20:23:37.632912Z | false |
hlsxx/tukai | https://github.com/hlsxx/tukai/blob/c7c380ec133362c2f2e04d6cb9e1e2b77fd411be/src/storage/stat_helper.rs | src/storage/stat_helper.rs | pub struct StatHelper;
impl StatHelper {
/// Calculates raw WPM
pub fn get_calculated_raw_wpm(chars_counter: usize, time_limit: usize) -> usize {
((chars_counter as f64 / 5.0) * 60.0 / time_limit as f64) as usize
}
/// Calculates WPM
pub fn get_calculated_wpm(
chars_counter: usize,
mistakes_counter: usize,
time_limit: usize,
) -> usize {
(((chars_counter as f64 - mistakes_counter as f64) / 5.0) * 60.0 / time_limit as f64).round()
as usize
}
/// Calculates accuracy
pub fn get_calculated_accuracy(chars_counter: usize, mistakes_counter: usize) -> f64 {
let accuracy =
((chars_counter as f64 - mistakes_counter as f64) / chars_counter as f64) * 100.0;
(accuracy * 100.0).round() / 100.0
}
}
| rust | MIT | c7c380ec133362c2f2e04d6cb9e1e2b77fd411be | 2026-01-04T20:23:37.632912Z | false |
hlsxx/tukai | https://github.com/hlsxx/tukai/blob/c7c380ec133362c2f2e04d6cb9e1e2b77fd411be/src/storage/storage_handler.rs | src/storage/storage_handler.rs | use std::{
fmt::{Debug, Display},
path::{Path, PathBuf},
};
use anyhow::Result;
use crate::config::{TukaiLayoutName, TypingDuration};
use crate::file_handler::FileHandler;
use super::stats::Stat;
#[derive(Debug)]
pub struct StorageHandlerError {
message: String,
}
impl Display for StorageHandlerError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "StorageHandlerError: {}", self.message)
}
}
impl std::error::Error for StorageHandlerError {}
#[allow(unused)]
impl StorageHandlerError {
fn new(message: String) -> Self {
Self { message }
}
}
/// Storage data type
///
/// Represents types saved on a device's secondary memory.
pub type StorageData = (Vec<Stat>, TypingDuration, TukaiLayoutName, bool, usize);
/// Default data for storage
///
/// Represents the initial or fallback data used in storage.
static DEFAULT_STORAGE_DATA: StorageData = (
Vec::<Stat>::new(),
TypingDuration::Minute,
TukaiLayoutName::Iced,
false,
0,
);
/// Represents a storage file with a specified file path
///
/// Handles both read and write operations.
pub struct StorageHandler {
// Path to the `storage` file
// Defaults to the OS's local directory (refer to the `dirs` library)
file_path: PathBuf,
// Data stored in the `storage` binary file
data: Option<StorageData>,
}
/// Total statistics overview
///
/// Includes the average WPM (words per minute) and average accuracy.
pub struct StatOverview {
pub total_stats_count: usize,
pub total_average_wpm: usize,
pub total_average_accuracy: f64,
}
impl StorageHandler {
/// Creates a new `storage` file
///
/// Uses a local directory path or `/tmp` as the default location.
pub fn new<P: AsRef<Path>>(file_path: P) -> Self {
let local_dir_path = dirs::data_local_dir().unwrap_or(PathBuf::from("/tmp"));
let full_path = local_dir_path.join("tukai").join(file_path);
Self {
file_path: full_path,
data: None,
}
}
#[cfg(test)]
pub fn delete_file(&self) -> Result<()> {
std::fs::remove_file(&self.file_path)?;
Ok(())
}
/// Inits empty data and write into the `storage file`
fn init_empty_data(&mut self) -> Result<()> {
let data = self
.data
.get_or_insert_with(|| DEFAULT_STORAGE_DATA.clone());
let data_bytes = bincode::serialize(&data).unwrap();
FileHandler::write_bytes_into_file(&self.file_path, &data_bytes)?;
Ok(())
}
/// Inits the storage
///
/// Try to read all bytes from the storage file
/// Then set into the data
pub fn init(mut self) -> Result<Self> {
if !self.file_path.exists() {
self.init_empty_data()?;
return Ok(self);
}
let data_bytes = FileHandler::read_bytes_from_file(&self.file_path)?;
match bincode::deserialize(&data_bytes) {
Ok(data) => self.data = data,
Err(_) => self.init_empty_data()?,
};
Ok(self)
}
/// Returns data from the storage
///
/// If data is None, returns the storage's default values.
pub fn get_data(&self) -> &StorageData {
if let Some(storage_data) = &self.data {
storage_data
} else {
&DEFAULT_STORAGE_DATA
}
}
/// Returns data from the storage as mutable
pub fn get_data_mut(&mut self) -> Option<&mut StorageData> {
self.data.as_mut()
}
/// Returns the complete statistics overview
///
/// (average WPM, average accuracy)
pub fn get_data_for_overview(&self) -> StatOverview {
let stats = &self.get_data().0;
let (sum_wpm, sum_accuracy) = stats.iter().fold((0, 0.0), |(wpm, acc), stat| {
(wpm + stat.get_average_wpm(), acc + stat.get_accuracy())
});
let accuracy = (sum_accuracy / stats.len() as f64).round();
StatOverview {
total_stats_count: stats.len(),
total_average_wpm: sum_wpm.checked_div(stats.len()).unwrap_or(0),
total_average_accuracy: if accuracy.is_nan() { 0.0 } else { accuracy },
}
}
/// Returns data for the chart widget
///
/// Creates a dataset for the chart and calculates the best WPM.
pub fn get_data_for_chart(&self) -> (usize, Vec<(f64, f64)>) {
let stats = &self.get_data().0;
let mut best_wpm = 0_usize;
let dataset = stats
.iter()
.enumerate()
.rev()
.map(|(index, stat)| {
let stat_wpm = stat.get_average_wpm();
best_wpm = best_wpm.max(stat_wpm);
(index as f64, stat_wpm as f64)
})
.collect::<Vec<(f64, f64)>>();
(best_wpm.max(100), dataset)
}
/// Returns stats in reversed order
///
/// Newest first
pub fn get_data_stats_reversed(&self) -> Vec<Stat> {
let stats = &self.get_data().0;
stats.iter().rev().cloned().collect::<Vec<Stat>>()
}
/// Returns stats sorted by average WPM
///
/// Used to determine the `best score`.
pub fn get_data_stats_best(&self) -> Vec<Stat> {
let mut data = self.get_data().0.clone();
data.sort_by_key(|b| std::cmp::Reverse(b.get_average_wpm()));
data
}
/// Returns a TypingDuration
pub fn get_typing_duration(&self) -> TypingDuration {
self.get_data().1.clone()
}
/// Returns an active layout name
pub fn get_layout_name(&self) -> TukaiLayoutName {
self.get_data().2.clone()
}
/// Returns a current language index
pub fn get_language_index(&self) -> usize {
self.get_data().4
}
/// Returns if has a transparend background
pub fn get_has_transparent_bg(&self) -> bool {
self.get_data().3
}
/// Serialize `StorageData` into a bytes.
///
/// Flushes all serialized data to the storage file.
pub fn flush(&self) -> Result<()> {
let data_bytes = bincode::serialize(&self.data)?;
FileHandler::write_bytes_into_file(&self.file_path, &data_bytes)
}
/// Insert a new cloned Stat record to the storage file.
///
/// Then try to flush this record
pub fn insert_into_stats(&mut self, stat: &Stat) -> bool {
if let Some(storage_data) = self.get_data_mut() {
storage_data.0.push(stat.clone());
}
self.flush().is_ok()
}
/// Sets a new typing duration
pub fn set_typing_duration(&mut self, typin_duration: TypingDuration) {
if let Some(storage_data) = self.get_data_mut() {
storage_data.1 = typin_duration;
}
}
/// Sets a new active layout name
pub fn set_layout(&mut self, layout_name_changed: TukaiLayoutName) {
if let Some(storage_data) = self.get_data_mut() {
storage_data.2 = layout_name_changed;
}
}
/// Sets a new language_index
pub fn set_language_index(&mut self, language_index: usize) {
if let Some(storage_data) = self.get_data_mut() {
storage_data.4 = language_index;
}
}
/// Toggles a background transparency
pub fn set_transparent_bg(&mut self, state: bool) {
if let Some(storage_data) = self.get_data_mut() {
storage_data.3 = state;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::TypingDuration;
use uuid::Uuid;
fn get_storage_handler() -> StorageHandler {
let storage_helper = StorageHandler::new(format!("tests/{}.tukai", Uuid::new_v4()))
.init()
.expect("Failed to initialize storage file");
storage_helper
}
fn get_test_stat() -> Stat {
Stat::new(TypingDuration::Minute, 80, 5, 6)
}
//#[test]
// fn storage_local_dir_initialization() {
// let storage_handler = get_storage_handler();
// }
#[test]
// Just validate if binary file was created right
fn storage_load() {
let storage_handler = get_storage_handler();
let _storage_data = storage_handler.get_data();
storage_handler
.delete_file()
.expect("Error occured while deleting file");
}
#[test]
// Init an empty storage data
//
// Insert test Stat into the file
//
// Try to reverse read from the memory
fn storage_insert_into_data_stats() {
let mut storage_handler = get_storage_handler();
let stat = get_test_stat();
assert!(
storage_handler.insert_into_stats(&stat),
"Insert into the storage error occured"
);
let _stats = storage_handler.get_data_stats_reversed();
// assert!(
// stats.is_some(),
// "Failed to read from the storage stats (stats is None)"
// );
//
// let stats_unwraped = stats.unwrap();
//
// let stat_from_memory = &stats_unwraped[0];
//
// assert_eq!(stat_from_memory.get_average_wpm(), stat.get_average_wpm());
//
// storage_handler
// .delete_file()
// .expect("Error occured while deleting file");
}
#[test]
fn flush_data() {
let mut storage_handler = get_storage_handler();
storage_handler.insert_into_stats(&get_test_stat());
assert!(storage_handler.flush().is_ok());
storage_handler
.delete_file()
.expect("Error occured while deleting file");
}
#[test]
fn load_flushed_data() {
let mut storage_handler = get_storage_handler();
storage_handler.insert_into_stats(&get_test_stat());
println!("{:?}", storage_handler.get_data());
let data = storage_handler.get_data();
println!("{:?}", data);
storage_handler
.delete_file()
.expect("Error occured while deleting file");
}
}
| rust | MIT | c7c380ec133362c2f2e04d6cb9e1e2b77fd411be | 2026-01-04T20:23:37.632912Z | false |
hlsxx/tukai | https://github.com/hlsxx/tukai/blob/c7c380ec133362c2f2e04d6cb9e1e2b77fd411be/src/screens/stats.rs | src/screens/stats.rs | use std::{cell::RefCell, rc::Rc};
use crate::{
config::{TukaiConfig, TukaiLayoutColorTypeEnum},
screens::{Instruction, InstructionWidget, Screen, ToDark},
storage::{
stats::Stat,
storage_handler::{StatOverview, StorageHandler},
},
};
use ratatui::{
Frame,
crossterm::event::KeyEvent,
layout::{Alignment, Constraint, Direction, Layout, Rect},
style::{Style, Stylize},
symbols,
text::{Line, Span},
widgets::{
Axis, Block, BorderType, Borders, Cell, Chart, Dataset, GraphType, Padding, Paragraph, Row,
Table,
},
};
use super::ActiveScreenEnum;
pub struct StatsScreen {
config: Rc<RefCell<TukaiConfig>>,
}
impl StatsScreen {
pub fn new(config: Rc<RefCell<TukaiConfig>>) -> Self {
Self { config }
}
}
impl Screen for StatsScreen {
fn increment_time_secs(&mut self) {}
fn get_config(&self) -> &Rc<RefCell<TukaiConfig>> {
&self.config
}
fn get_screen_name(&self) -> String {
String::from("Stats")
}
fn get_remaining_time(&self) -> usize {
0
}
fn get_previous_screen(&self) -> Option<ActiveScreenEnum> {
Some(ActiveScreenEnum::Repeat)
}
fn reset(&mut self) {}
#[allow(dead_code)]
fn handle_events(&mut self, _key: KeyEvent) -> bool {
false
}
fn render_instructions(&self, frame: &mut Frame, area: Rect) {
let app_config = self.config.borrow();
let app_layout = app_config.get_layout();
let mut instruction_widget = InstructionWidget::new(&app_layout);
instruction_widget.add_instruction(Instruction::new(
"Exit",
"esc",
TukaiLayoutColorTypeEnum::Secondary,
));
instruction_widget.add_instruction(Instruction::new(
"Transparent",
"ctrl-t",
TukaiLayoutColorTypeEnum::Secondary,
));
instruction_widget.add_instruction(Instruction::new(
"Repeat word",
"ctrl-h",
TukaiLayoutColorTypeEnum::Secondary,
));
let block = Block::new().padding(Padding::new(0, 0, area.height / 2, 0));
let instructions = instruction_widget
.get_paragraph()
.block(block)
.alignment(Alignment::Center)
.style(app_config.get_bg_color());
frame.render_widget(instructions, area);
}
fn render(&self, frame: &mut Frame, area: Rect) {
let storage_handler = StorageHandler::new("tukai.bin").init().unwrap();
let chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints(vec![Constraint::Percentage(70), Constraint::Percentage(30)])
.split(area);
let left_widget = Layout::default()
.direction(Direction::Vertical)
.constraints(vec![Constraint::Percentage(50), Constraint::Percentage(50)])
.split(chunks[0]);
let right_widget = Layout::default()
.direction(Direction::Vertical)
.constraints(vec![Constraint::Length(7), Constraint::Percentage(100)])
.split(chunks[1]);
let last_runs_table_widget_data = storage_handler.get_data_stats_reversed();
let last_runs_table_widget = self.get_last_runs_table_widget(&last_runs_table_widget_data);
let chart_widget_data = storage_handler.get_data_for_chart();
let chart_widget = self.get_chart_widget(&chart_widget_data);
let best_score_widget = self.get_best_score_widget(&storage_handler);
let chart_widget_data = storage_handler.get_data_for_overview();
let stats_overview_widget = self.get_stats_overview_widget(&chart_widget_data);
frame.render_widget(last_runs_table_widget, left_widget[0]);
frame.render_widget(chart_widget, left_widget[1]);
frame.render_widget(stats_overview_widget, right_widget[0]);
frame.render_widget(best_score_widget, right_widget[1]);
}
fn render_popup(&self, _frame: &mut Frame) {}
}
impl StatsScreen {
/// Returns the right widget (Best score)
fn get_best_score_widget<'a>(&'a self, storage_handler: &StorageHandler) -> Table<'a> {
let app_config = self.config.borrow();
let app_layout = &app_config.get_layout();
let primary_color = app_layout.get_primary_color();
let text_color = app_layout.get_text_color();
let stats = storage_handler.get_data_stats_best();
let block = Block::new()
.title(" Best score ")
.title_style(Style::new().fg(primary_color))
.borders(Borders::ALL)
.border_style(Style::default().fg(primary_color))
.border_type(BorderType::Rounded);
let default_cell_style = Style::default().fg(text_color);
let rows = stats
.iter()
.map(|stat| {
Row::new(vec![
Cell::from(stat.get_average_wpm().to_string()).style(default_cell_style),
Cell::from(format!("{}%", stat.get_accuracy())).style(default_cell_style),
])
})
.collect::<Vec<Row>>();
let widths = [Constraint::Percentage(50), Constraint::Percentage(50)];
let default_header_cell_style = Style::default().fg(primary_color).bold();
Table::new(rows, widths)
.block(block)
.column_spacing(1)
.style(app_config.get_bg_color())
.header(
Row::new(vec![
Cell::from("🔥 Average WPM").style(default_header_cell_style),
Cell::from("🎯 Accuracy").style(default_header_cell_style),
])
.bottom_margin(1),
)
}
/// Gets the main table widget (Last runs)
fn get_last_runs_table_widget<'a>(&'a self, stats: &[Stat]) -> Table<'a> {
let app_config = self.config.borrow();
let app_layout = app_config.get_layout();
let primary_color = app_layout.get_primary_color();
let text_color = app_layout.get_text_color();
let block = Block::new()
.title(self.get_title())
.title_style(Style::new().fg(primary_color))
.borders(Borders::ALL)
.border_style(Style::default().fg(primary_color))
.border_type(BorderType::Rounded);
let default_cell_style = Style::default().fg(app_layout.get_text_color());
let rows = stats
.iter()
.map(|stat| {
let duration_pretty = stat.get_duration_pretty();
Row::new(vec![
Cell::from(duration_pretty),
Cell::from(stat.get_average_wpm().to_string()).style(default_cell_style),
Cell::from(format!("{}%", stat.get_accuracy())).style(default_cell_style),
Cell::from(stat.get_raw_wpm().to_string())
.style(Style::default().fg(text_color.to_dark())),
Cell::from(format!("{}%", stat.get_true_accuracy()))
.style(Style::default().fg(text_color.to_dark())),
])
})
.collect::<Vec<Row>>();
let widths = [
Constraint::Percentage(20),
Constraint::Percentage(20),
Constraint::Percentage(20),
Constraint::Percentage(20),
Constraint::Percentage(20),
];
let default_header_cell_style = Style::default().fg(primary_color).bold();
Table::new(rows, widths)
.block(block)
.column_spacing(1)
.style(app_config.get_bg_color())
.highlight_symbol("X")
.header(
Row::new(vec![
Cell::from("⏳ Duration").style(default_header_cell_style),
Cell::from("🔥 Average WPM").style(default_header_cell_style),
Cell::from("🎯 Accuracy").style(default_header_cell_style),
Cell::from("🥩 Raw WPM").style(default_header_cell_style),
Cell::from("🥶 True Accuracy").style(default_header_cell_style),
])
.bottom_margin(1),
)
}
/// Gets the left bottom widget (Chart)
fn get_chart_widget<'a>(&self, chart_widget_data: &'a (usize, Vec<(f64, f64)>)) -> Chart<'a> {
let app_config = self.config.borrow();
let app_layout = &app_config.get_layout();
let primary_color = app_layout.get_primary_color();
let text_color = app_layout.get_text_color();
let (_best_wpm, chart_data) = chart_widget_data;
// Validate best_wpm
// let upper_x_bound = if *best_wpm < 25 { 50 } else { best_wpm + 10 };
let datasets = vec![
Dataset::default()
.marker(symbols::Marker::Dot)
.graph_type(GraphType::Scatter)
.style(Style::default().fg(text_color))
.data(chart_data),
];
let y_labels = (0..=125)
.step_by(25)
.map(|y| Span::from(y.to_string()).style(Style::default().fg(text_color)))
.collect::<Vec<Span>>();
let x_axis = Axis::default()
.style(Style::default().white())
.bounds([0.0, chart_data.len() as f64]);
let y_axis = Axis::default()
.style(Style::default().fg(primary_color))
.bounds([0.0, 125_f64])
.labels(y_labels);
let chart_block = Block::new()
.title_top(" WPM progress ")
.title_style(Style::new().fg(primary_color))
.borders(Borders::ALL)
.border_style(Style::default().fg(primary_color))
.border_type(BorderType::Rounded);
Chart::new(datasets)
.block(chart_block)
.style(app_config.get_bg_color())
.x_axis(x_axis)
.y_axis(y_axis)
}
fn get_stats_overview_widget<'a>(&self, stat_overview: &'a StatOverview) -> Paragraph<'a> {
let app_config = self.config.borrow();
let app_layout = &app_config.get_layout();
let primary_color = app_layout.get_primary_color();
let text_color = app_layout.get_text_color();
let text = vec![
Line::default(),
Line::from(vec![
Span::from(" Tests count: ").style(Style::default().fg(text_color)),
Span::from(stat_overview.total_stats_count.to_string())
.style(Style::default().fg(primary_color).bold()),
]),
Line::from(vec![
Span::from(" Average WPM: ").style(Style::default().fg(text_color)),
Span::from(stat_overview.total_average_wpm.to_string())
.style(Style::default().fg(primary_color).bold()),
]),
Line::from(vec![
Span::from(" Average accuracy: ").style(Style::default().fg(text_color)),
Span::from(format!("{}%", stat_overview.total_average_accuracy,))
.style(Style::default().fg(primary_color).bold()),
]),
];
let block = Block::new()
.title(" Total score ")
.title_style(Style::new().fg(primary_color))
.borders(Borders::ALL)
.border_style(Style::default().fg(primary_color))
.border_type(BorderType::Rounded);
Paragraph::new(text)
.block(block)
.style(app_config.get_bg_color())
.alignment(Alignment::Left)
}
}
| rust | MIT | c7c380ec133362c2f2e04d6cb9e1e2b77fd411be | 2026-01-04T20:23:37.632912Z | false |
hlsxx/tukai | https://github.com/hlsxx/tukai/blob/c7c380ec133362c2f2e04d6cb9e1e2b77fd411be/src/screens/repeat.rs | src/screens/repeat.rs | use std::{cell::RefCell, collections::HashSet, rc::Rc};
use ratatui::{
Frame,
crossterm::event::{KeyCode, KeyEvent},
layout::{Alignment, Rect},
style::{Modifier, Style},
text::{Line, Span, Text},
widgets::{Block, BorderType, Borders, Padding, Paragraph, Wrap},
};
use crate::{
config::{TukaiConfig, TukaiLayout, TukaiLayoutColorTypeEnum},
helper::Generator,
screens::{Instruction, InstructionWidget, Screen, ToDark},
};
use super::ActiveScreenEnum;
/// Handler for incorrect symbols
///
/// Inserts incorrect characters into a HashSet
pub struct MistakeHandler {
mistakes_indexes: HashSet<usize>,
}
impl MistakeHandler {
/// Creates MistakeHandler with empty HashSet
fn new() -> Self {
Self {
mistakes_indexes: HashSet::new(),
}
}
/// Verifies if the character is mistaken
pub fn is_char_mistaken(&self, char_index: usize) -> bool {
self.mistakes_indexes.contains(&char_index)
}
/// Adds the typed character into the mistakes
pub fn add_to_mistakes_indexes(&mut self, char_index: usize) -> bool {
self.mistakes_indexes.insert(char_index)
}
/// Removes the typed character from mistakes
pub fn remove_from_mistakes_indexes(&mut self, char_index: usize) -> bool {
self.mistakes_indexes.remove(&char_index)
}
}
pub struct RepeatScreen {
/// Application config
config: Rc<RefCell<TukaiConfig>>,
/// Random generated text from a words list
pub generated_text: String,
/// User typed input
pub input: String,
/// Handle incorrect characters
pub mistake_handler: MistakeHandler,
/// The current cursor index withing generated_text
cursor_index: usize,
/// Block motto
motto: String,
}
impl RepeatScreen {
pub fn new(config: Rc<RefCell<TukaiConfig>>) -> Self {
let generated_text = Generator::generate_repeated_word(&config.borrow());
Self {
config,
generated_text,
input: String::new(),
mistake_handler: MistakeHandler::new(),
cursor_index: 0,
motto: Generator::generate_random_motto(),
}
}
}
impl Screen for RepeatScreen {
fn is_running(&self) -> bool {
true
}
fn increment_time_secs(&mut self) {}
fn get_config(&self) -> &Rc<RefCell<TukaiConfig>> {
&self.config
}
fn get_remaining_time(&self) -> usize {
0
}
fn get_screen_name(&self) -> String {
String::from("Repeat")
}
fn get_next_screen(&self) -> Option<ActiveScreenEnum> {
Some(ActiveScreenEnum::Stats)
}
fn get_previous_screen(&self) -> Option<ActiveScreenEnum> {
Some(ActiveScreenEnum::Typing)
}
/// Resets all necessary properties
fn reset(&mut self) {
self.mistake_handler = MistakeHandler::new();
self.cursor_index = 0;
self.input = String::new();
let app_config = self.config.borrow();
self.generated_text = Generator::generate_repeated_word(&app_config);
}
fn handle_events(&mut self, key_event: KeyEvent) -> bool {
if self.cursor_index > 0 && !self.is_running() {
return false;
}
match key_event.code {
KeyCode::Char(c) => {
self.move_cursor_forward_with(c);
true
}
KeyCode::Backspace => {
self.move_cursor_backward();
true
}
_ => false,
}
}
fn render(&self, frame: &mut Frame, area: Rect) {
let app_config = self.config.borrow();
let app_layout = app_config.get_layout();
let horizontal_padding = if (area.width / 3) < 8 {
2
} else {
area.width / 3 - 8
};
let block = Block::new()
.title(self.get_title())
.title_alignment(Alignment::Left)
.title_bottom(self.motto.as_ref())
.title_style(Style::default().fg(app_layout.get_primary_color()))
.title_alignment(Alignment::Center)
.style(app_config.get_bg_color())
.borders(Borders::ALL)
.border_type(BorderType::Rounded)
.border_style(Style::default().fg(app_layout.get_primary_color()))
.padding(Padding::new(
horizontal_padding,
horizontal_padding,
(area.height / 2) - 5,
0,
));
let p = self
.get_paragraph(&app_layout)
.block(block)
.alignment(Alignment::Left);
frame.render_widget(p, area);
}
fn render_instructions(&self, frame: &mut Frame, area: Rect) {
let app_config = self.config.borrow_mut();
let app_layout = app_config.get_layout();
let mut instruction_widget = InstructionWidget::new(&app_layout);
instruction_widget.add_instruction(Instruction::new(
"Exit",
"esc",
TukaiLayoutColorTypeEnum::Secondary,
));
instruction_widget.add_instruction(Instruction::new(
"Reset",
"ctrl-r",
TukaiLayoutColorTypeEnum::Secondary,
));
instruction_widget.add_instruction(Instruction::new(
"Layout",
"ctrl-s",
TukaiLayoutColorTypeEnum::Secondary,
));
instruction_widget.add_instruction(Instruction::new(
"Transparent",
"ctrl-t",
TukaiLayoutColorTypeEnum::Secondary,
));
instruction_widget.add_instruction(Instruction::new(
"Typing",
"ctrl-h",
TukaiLayoutColorTypeEnum::Secondary,
));
instruction_widget.add_instruction(Instruction::new(
"Stats",
"ctrl-l",
TukaiLayoutColorTypeEnum::Secondary,
));
instruction_widget.add_instruction(Instruction::new(
"Language",
"ctrl-p",
TukaiLayoutColorTypeEnum::Secondary,
));
let block = Block::new().padding(Padding::new(0, 0, area.height / 2, 0));
let instructions = instruction_widget
.get_paragraph()
.block(block)
.alignment(Alignment::Center)
.style(app_config.get_bg_color());
frame.render_widget(instructions, area);
}
/// Renders a popup screen
///
/// Used after the run is completed
fn render_popup(&self, _frame: &mut Frame) {}
}
impl RepeatScreen {
/// Validates an inserted char
///
/// If it is not valid, insert it into the set of mistakes
fn validate_input_char(&mut self, inserted_char: char) {
if let Some(generated_char) = self.generated_text.chars().nth(self.cursor_index)
&& generated_char != inserted_char
{
self
.mistake_handler
.add_to_mistakes_indexes(self.cursor_index);
}
}
/// Moves the cursor position forward
///
/// Also validates a char
fn move_cursor_forward_with(&mut self, c: char) {
self.validate_input_char(c);
self.input.push(c);
self.cursor_index += 1;
}
/// Moves the cursor position backward
///
/// Remove the incorrect symbol from the set if its exists
fn move_cursor_backward(&mut self) {
if self.input.pop().is_none() {
return;
}
self.cursor_index -= 1;
if self.mistake_handler.is_char_mistaken(self.cursor_index) {
self
.mistake_handler
.remove_from_mistakes_indexes(self.cursor_index);
}
}
// Deletes the last word form the input.
// Handles trailing spaces and updates mistakes.
#[allow(unused)]
pub fn delete_last_word(&mut self) {
if self.input.is_empty() {
return;
}
let original_input_len = self.input.len();
// Find the end of the actual contnet (trim trailing whitespace for logic)
let trimmed_end_len = self.input.trim_end().len();
if trimmed_end_len == 0 {
// Input was all spaces
for i in 0..original_input_len {
self.mistake_handler.remove_from_mistakes_indexes(i);
}
self.input.clear();
self.cursor_index = 0;
return;
}
// Find the last space before the last word in the trimmed part
let last_word_start_idx = match self.input[..trimmed_end_len].rfind(' ') {
Some(space_idx) => space_idx + 1, // Word starts after the space
none => 0, // No space found, word starts at the beginning
};
for i in last_word_start_idx..original_input_len {
self.mistake_handler.remove_from_mistakes_indexes(i);
}
self.input.truncate(last_word_start_idx);
self.cursor_index = self.input.len();
}
/// Prepares and returns a paragraph.
///
/// If popup window is showed then colors converts to dark.
pub fn get_paragraph(&self, layout: &TukaiLayout) -> Paragraph<'_> {
let mut lines = Vec::new();
let (primary_color, error_color, text_color) = {
let colors = {
(
layout.get_primary_color(),
layout.get_error_color(),
layout.get_text_color(),
)
};
if self.is_popup_visible() {
(colors.0.to_dark(), colors.1.to_dark(), colors.2.to_dark())
} else {
colors
}
};
let repeat_word_line =
Line::from("🔄 Repeat word").style(Style::default().fg(layout.get_primary_color()));
let text_line = self
.generated_text
.chars()
.enumerate()
.map(|(i, c)| {
if i == self.cursor_index {
Span::from(c.to_string()).style(
Style::default()
.fg(layout.get_text_current_color())
.bg(layout.get_text_current_bg_color()),
)
} else if i < self.cursor_index {
if self.input.chars().nth(i) == Some(c) {
Span::from(c.to_string()).style(Style::default().fg(primary_color))
} else {
Span::from(c.to_string()).style(
Style::default()
.fg(error_color)
.add_modifier(Modifier::CROSSED_OUT),
)
}
} else {
Span::from(c.to_string()).style(Style::default().fg(text_color))
}
})
.collect::<Line>();
let empty_line = Line::from(Vec::new());
lines.push(repeat_word_line);
lines.push(empty_line.clone());
lines.push(text_line);
lines.push(empty_line);
let text = Text::from(lines);
Paragraph::new(text).wrap(Wrap { trim: true })
}
}
| rust | MIT | c7c380ec133362c2f2e04d6cb9e1e2b77fd411be | 2026-01-04T20:23:37.632912Z | false |
hlsxx/tukai | https://github.com/hlsxx/tukai/blob/c7c380ec133362c2f2e04d6cb9e1e2b77fd411be/src/screens/mod.rs | src/screens/mod.rs | pub mod repeat;
pub mod stats;
pub mod typing;
use std::cell::RefCell;
use std::rc::Rc;
use ratatui::{
Frame,
crossterm::event::KeyEvent,
layout::Rect,
style::{Color, Style, Stylize},
text::{Line, Span, Text},
widgets::{Paragraph, block::Title},
};
use crate::{
config::{TukaiConfig, TukaiLayout, TukaiLayoutColorTypeEnum},
storage::storage_handler::StorageHandler,
};
#[derive(PartialEq, Hash, Eq, Debug)]
pub enum ActiveScreenEnum {
Typing,
Repeat,
Stats,
}
#[allow(unused)]
pub trait ToDark {
/// Converts the `(u8, u8, u8)` tuple to a `Color::Rgb`
///
/// # Example
///
/// ```
/// use ratatui::style::Color
///
/// let rgb: (u8, u8, u8) = (128, 64, 255);
/// let color = rgb.to_color();
///
/// assert_eq!(color, Color::Rgb(128, 64, 255));
/// ```
fn to_dark(self) -> Color;
}
impl ToDark for Color {
fn to_dark(self) -> Color {
match self {
Color::Rgb(r, g, b) => {
let darkened_r = (r as f32 * (1.0 - 0.2)) as u8;
let darkened_g = (g as f32 * (1.0 - 0.2)) as u8;
let darkened_b = (b as f32 * (1.0 - 0.2)) as u8;
Color::Rgb(darkened_r, darkened_g, darkened_b)
}
_ => self,
}
}
}
pub struct Instruction<'a> {
// Instruction title text (description)
title: &'a str,
// Instruction shortcut text
shortcut: &'a str,
// Layout color
color_type: TukaiLayoutColorTypeEnum,
}
impl<'a> Instruction<'a> {
pub fn new(title: &'a str, shortcut: &'a str, color_type: TukaiLayoutColorTypeEnum) -> Self {
Self {
title,
shortcut,
color_type,
}
}
}
pub struct InstructionWidget<'a> {
layout: &'a TukaiLayout,
instructions: Vec<Instruction<'a>>,
}
impl<'a> InstructionWidget<'a> {
pub fn new(layout: &'a TukaiLayout) -> Self {
Self {
layout,
instructions: Vec::new(),
}
}
fn get_instruction_color(&self, _color_type: &TukaiLayoutColorTypeEnum) -> Color {
self.layout.get_primary_color()
}
pub fn add_instruction(&mut self, instruction: Instruction<'a>) {
self.instructions.push(instruction);
}
/// Returns paragraph contains instructions
pub fn get_paragraph(&self) -> Paragraph<'_> {
let instructions_spans = self
.instructions
.iter()
.enumerate()
.flat_map(|(index, instruction)| {
let color = self.get_instruction_color(&instruction.color_type);
vec![
Span::from(format!(" {}", instruction.title)).style(Style::default().fg(color.to_dark())),
Span::from(format!(
" {}{}",
instruction.shortcut,
if index != self.instructions.len() - 1 {
" |"
} else {
""
}
))
.style(Style::default().fg(color).bold()),
]
})
.collect::<Vec<Span>>();
Paragraph::new(Text::from(Line::from(instructions_spans)))
}
}
pub trait Screen {
// fn new(config: Rc<RefCell<TukaiConfig>>) -> Box<Screen>;
fn increment_time_secs(&mut self);
fn get_config(&self) -> &Rc<RefCell<TukaiConfig>>;
fn get_screen_name(&self) -> String;
fn get_remaining_time(&self) -> usize;
fn get_previous_screen(&self) -> Option<ActiveScreenEnum> {
None
}
fn get_next_screen(&self) -> Option<ActiveScreenEnum> {
None
}
fn stop(&mut self, _storage_handler: &mut StorageHandler) {}
/// Returns the application title
/// including version from the `Cargo.toml`.
fn get_title<'a>(&self) -> Title<'a> {
let app_config = self.get_config().borrow();
let app_layout = app_config.get_layout();
Title::from(format!(
" tukai v{} 》{} 》{} 》{} ",
env!("CARGO_PKG_VERSION"),
app_layout.get_active_layout_name(),
app_config.get_language().get_lang_code(),
self.get_screen_name()
))
}
fn reset(&mut self);
/// Handles key events
///
/// If any key consumed by the screen returns false
fn handle_events(&mut self, key: KeyEvent) -> bool;
/// Typing is running
fn is_running(&self) -> bool {
false
}
/// Returns whether the popup is visible.
///
/// Default set to false (not used in stats screen)
fn is_popup_visible(&self) -> bool {
false
}
/// Renders screen instructions.
///
/// Visible of the bottom of screen
fn render_instructions(&self, frame: &mut Frame, area: Rect);
/// Renders screen widgets.
fn render(&self, frame: &mut Frame, area: Rect);
/// Renders a popup screen
///
/// Used after the run is completed
fn render_popup(&self, frame: &mut Frame);
/// Handles control-modified key events specific to the screen.
///
/// True if event consumed, false otherwise.
#[allow(unused_variables)]
fn handle_control_events(&mut self, key_event: KeyEvent) -> bool {
false
}
}
| rust | MIT | c7c380ec133362c2f2e04d6cb9e1e2b77fd411be | 2026-01-04T20:23:37.632912Z | false |
hlsxx/tukai | https://github.com/hlsxx/tukai/blob/c7c380ec133362c2f2e04d6cb9e1e2b77fd411be/src/screens/typing.rs | src/screens/typing.rs | use std::{cell::RefCell, collections::HashSet, rc::Rc};
use ratatui::{
Frame,
crossterm::event::{KeyCode, KeyEvent},
layout::{Alignment, Constraint, Flex, Layout, Rect},
style::{Modifier, Style, Stylize},
text::{Line, Span, Text},
widgets::{Block, BorderType, Borders, Clear, Padding, Paragraph, Wrap},
};
use crate::{
config::{TukaiConfig, TukaiLayout, TukaiLayoutColorTypeEnum},
helper::Generator,
screens::{Instruction, InstructionWidget, Screen, ToDark},
storage::{stats::Stat, storage_handler::StorageHandler},
};
use super::ActiveScreenEnum;
/// Handler for incorrect symbols
///
/// Inserts incorrect characters into a HashSet
pub struct MistakeHandler {
mistakes_indexes: HashSet<usize>,
true_mistakes_indexes: HashSet<usize>,
}
impl MistakeHandler {
/// Creates MistakeHandler with empty HashSet
fn new() -> Self {
Self {
mistakes_indexes: HashSet::new(),
true_mistakes_indexes: HashSet::new(),
}
}
/// Verifies if the character is mistaken
pub fn is_char_mistaken(&self, char_index: usize) -> bool {
self.mistakes_indexes.contains(&char_index)
}
/// Adds the typed character into the mistakes
pub fn add_to_mistakes_indexes(&mut self, char_index: usize) -> bool {
self.true_mistakes_indexes.insert(char_index);
self.mistakes_indexes.insert(char_index)
}
/// Removes the typed character from mistakes
pub fn remove_from_mistakes_indexes(&mut self, char_index: usize) -> bool {
self.mistakes_indexes.remove(&char_index)
}
/// Returns the current mistake count
pub fn get_mistakes_counter(&self) -> usize {
self.mistakes_indexes.len()
}
pub fn get_true_mistakes_counter(&self) -> usize {
self.true_mistakes_indexes.len()
}
}
pub struct TypingScreen {
/// Application config
config: Rc<RefCell<TukaiConfig>>,
/// Random generated text from a words list
pub generated_text: String,
/// User typed input
pub input: String,
/// Handle incorrect characters
pub mistake_handler: MistakeHandler,
/// User statistics after the current run is completed
pub stat: Option<Stat>,
/// Typing running
is_running: bool,
/// Popup is visible
is_popup_visible: bool,
pub time_secs: u32,
/// The current cursor index withing generated_text
cursor_index: usize,
/// Block motto
motto: String,
}
impl TypingScreen {
pub fn new(config: Rc<RefCell<TukaiConfig>>) -> Self {
let generated_text = Generator::generate_random_string(&config.borrow());
Self {
config,
generated_text,
input: String::new(),
mistake_handler: MistakeHandler::new(),
stat: None,
is_running: false,
is_popup_visible: false,
time_secs: 0,
cursor_index: 0,
motto: Generator::generate_random_motto(),
}
}
}
impl Screen for TypingScreen {
fn increment_time_secs(&mut self) {
self.time_secs += 1;
}
fn get_config(&self) -> &Rc<RefCell<TukaiConfig>> {
&self.config
}
fn get_remaining_time(&self) -> usize {
let app_config = &self.config.borrow();
app_config
.typing_duration
.as_seconds()
.saturating_sub(self.time_secs as usize)
}
fn get_next_screen(&self) -> Option<ActiveScreenEnum> {
Some(ActiveScreenEnum::Repeat)
}
/// Stops the running typing process
///
/// Makes the popup screen visible
///
/// Inserts the created stat into storage
fn stop(&mut self, storage_handler: &mut StorageHandler) {
self.is_running = false;
self.is_popup_visible = true;
if self.stat.is_none() {
let stat = Stat::new(
self.config.borrow().typing_duration.clone(),
self.input.len(),
self.mistake_handler.get_mistakes_counter(),
self.mistake_handler.get_true_mistakes_counter(),
);
storage_handler.insert_into_stats(&stat);
self.stat = Some(stat);
}
}
/// Returns whether typing has begun
fn is_running(&self) -> bool {
self.is_running
}
fn is_popup_visible(&self) -> bool {
self.is_popup_visible
}
fn get_screen_name(&self) -> String {
String::from("Typing")
}
fn handle_control_events(&mut self, key_event: KeyEvent) -> bool {
if self.is_popup_visible {
return false;
}
match key_event.code {
KeyCode::Char('w') | KeyCode::Char('h') => {
//KeyCode::Char('w') | KeyCode::Backspace => {
self.delete_last_word();
true
}
_ => false,
}
}
/// Resets all necessary properties
fn reset(&mut self) {
self.is_running = false;
self.time_secs = 0;
self.mistake_handler = MistakeHandler::new();
self.cursor_index = 0;
self.input = String::new();
self.is_popup_visible = false;
let app_config = self.config.borrow();
self.generated_text = Generator::generate_random_string(&app_config);
}
fn handle_events(&mut self, key_event: KeyEvent) -> bool {
if self.cursor_index > 0 && !self.is_running() {
return false;
}
match key_event.code {
KeyCode::Esc => {
if self.is_popup_visible() {
self.is_popup_visible = false;
true
} else {
false
}
}
KeyCode::Char(c) => {
if self.cursor_index == 0 {
self.run();
}
self.move_cursor_forward_with(c);
true
}
KeyCode::Backspace => {
self.move_cursor_backward();
true
}
_ => false,
}
}
fn render(&self, frame: &mut Frame, area: Rect) {
let app_config = self.config.borrow();
let app_layout = app_config.get_layout();
let horizontal_padding = if (area.width / 3) < 8 {
2
} else {
area.width / 3 - 8
};
let block = Block::new()
.title(self.get_title())
.title_alignment(Alignment::Left)
.title_bottom(self.motto.as_ref())
.title_style(Style::default().fg(app_layout.get_primary_color()))
.title_alignment(Alignment::Center)
.style(app_config.get_bg_color())
.borders(Borders::ALL)
.border_type(BorderType::Rounded)
.border_style(Style::default().fg(app_layout.get_primary_color()))
.padding(Padding::new(
horizontal_padding,
horizontal_padding,
(area.height / 2) - 5,
0,
));
let p = self
.get_paragraph(&app_layout)
.block(block)
.alignment(Alignment::Left);
frame.render_widget(p, area);
}
fn render_instructions(&self, frame: &mut Frame, area: Rect) {
let app_config = self.config.borrow_mut();
let app_layout = app_config.get_layout();
let mut instruction_widget = InstructionWidget::new(&app_layout);
instruction_widget.add_instruction(Instruction::new(
"Exit",
"esc",
TukaiLayoutColorTypeEnum::Secondary,
));
instruction_widget.add_instruction(Instruction::new(
"Reset",
"ctrl-r",
TukaiLayoutColorTypeEnum::Secondary,
));
instruction_widget.add_instruction(Instruction::new(
"Duration",
"ctrl-d",
TukaiLayoutColorTypeEnum::Secondary,
));
instruction_widget.add_instruction(Instruction::new(
"Layout",
"ctrl-s",
TukaiLayoutColorTypeEnum::Secondary,
));
instruction_widget.add_instruction(Instruction::new(
"Transparent",
"ctrl-t",
TukaiLayoutColorTypeEnum::Secondary,
));
instruction_widget.add_instruction(Instruction::new(
"Repeat word",
"ctrl-l",
TukaiLayoutColorTypeEnum::Secondary,
));
instruction_widget.add_instruction(Instruction::new(
"Language",
"ctrl-p",
TukaiLayoutColorTypeEnum::Secondary,
));
let block = Block::new().padding(Padding::new(0, 0, area.height / 2, 0));
let instructions = instruction_widget
.get_paragraph()
.block(block)
.alignment(Alignment::Center)
.style(app_config.get_bg_color());
frame.render_widget(instructions, area);
}
/// Renders a popup screen
///
/// Used after the run is completed
fn render_popup(&self, frame: &mut Frame) {
let app_config = self.config.borrow();
let app_layout = app_config.get_layout();
let area = frame.area();
let block = Block::bordered()
.style(app_config.get_bg_color())
.border_type(BorderType::Rounded)
.border_style(Style::new().fg(app_layout.get_primary_color()));
let text = Text::from(vec![
Line::from(vec![
Span::from("🔥 Average WPM: "),
Span::from(format!("{}", self.get_calculated_wpm())).bold(),
])
.style(Style::default().fg(app_layout.get_primary_color())),
Line::from(vec![
Span::from("🎯 Accuracy: "),
Span::from(format!("{}%", self.get_calculated_accuracy())).bold(),
])
.style(Style::default().fg(app_layout.get_primary_color())),
Line::from(vec![
Span::from("🥩 Raw WPM: "),
Span::from(format!("{}", self.get_calculated_raw_wpm())).bold(),
])
.style(Style::default().fg(app_layout.get_primary_color().to_dark())),
Line::from(vec![
Span::from("🥶 True Accuracy: "),
Span::from(format!("{}%", self.get_true_calculated_accuracy())).bold(),
])
.style(Style::default().fg(app_layout.get_primary_color().to_dark())),
Line::from(""),
Line::from(vec![
Span::from("Try again").style(Style::default().fg(app_layout.get_primary_color())),
Span::from(" ctrl-r").style(Style::default().fg(app_layout.get_primary_color()).bold()),
]),
]);
let p = Paragraph::new(text)
.block(block)
.alignment(Alignment::Center)
.centered();
let vertical = Layout::vertical([Constraint::Percentage(22)]).flex(Flex::Center);
let horizontal = Layout::horizontal([Constraint::Percentage(22)]).flex(Flex::Center);
let [area] = vertical.areas(area);
let [area] = horizontal.areas(area);
frame.render_widget(Clear, area);
frame.render_widget(p, area);
}
}
impl TypingScreen {
/// Starts the running typing process
///
/// Unsets last stat
fn run(&mut self) {
self.is_running = true;
self.stat = None;
}
/// Validates an inserted char
///
/// If it is not valid, insert it into the set of mistakes
fn validate_input_char(&mut self, inserted_char: char) {
if let Some(generated_char) = self.generated_text.chars().nth(self.cursor_index)
&& generated_char != inserted_char
{
self
.mistake_handler
.add_to_mistakes_indexes(self.cursor_index);
}
}
/// Moves the cursor position forward
///
/// Also validates a char
fn move_cursor_forward_with(&mut self, c: char) {
self.validate_input_char(c);
self.input.push(c);
self.cursor_index += 1;
}
/// Moves the cursor position backward
///
/// Remove the incorrect symbol from the set if its exists
fn move_cursor_backward(&mut self) {
if self.input.pop().is_none() {
return;
}
self.cursor_index -= 1;
if self.mistake_handler.is_char_mistaken(self.cursor_index) {
self
.mistake_handler
.remove_from_mistakes_indexes(self.cursor_index);
}
}
// Deletes the last word form the input.
// Handles trailing spaces and updates mistakes.
pub fn delete_last_word(&mut self) {
if self.input.is_empty() {
return;
}
let original_input_len = self.input.len();
// Find the end of the actual contnet (trim trailing whitespace for logic)
let trimmed_end_len = self.input.trim_end().len();
if trimmed_end_len == 0 {
// Input was all spaces
for i in 0..original_input_len {
self.mistake_handler.remove_from_mistakes_indexes(i);
}
self.input.clear();
self.cursor_index = 0;
return;
}
// Find the last space before the last word in the trimmed part
let last_word_start_idx = match self.input[..trimmed_end_len].rfind(' ') {
Some(space_idx) => space_idx + 1, // Word starts after the space
None => 0, // No space found, word starts at the beginning
};
for i in last_word_start_idx..original_input_len {
self.mistake_handler.remove_from_mistakes_indexes(i);
}
self.input.truncate(last_word_start_idx);
self.cursor_index = self.input.len();
}
/// Returns the raw WPM
pub fn get_calculated_raw_wpm(&self) -> usize {
if let Some(last_stat) = &self.stat {
last_stat.get_raw_wpm()
} else {
0
}
}
/// Returns the average WPM
pub fn get_calculated_wpm(&self) -> usize {
if let Some(last_stat) = &self.stat {
last_stat.get_average_wpm()
} else {
0
}
}
/// Returns the accuracy
pub fn get_calculated_accuracy(&self) -> f64 {
if let Some(last_stat) = &self.stat {
last_stat.get_accuracy()
} else {
0.0
}
}
/// Returns the true accuracy
pub fn get_true_calculated_accuracy(&self) -> f64 {
if let Some(last_stat) = &self.stat {
last_stat.get_true_accuracy()
} else {
0.0
}
}
/// Prepares and returns a paragraph.
///
/// If popup window is showed then colors converts to dark.
pub fn get_paragraph(&self, layout: &TukaiLayout) -> Paragraph<'_> {
let mut lines = Vec::new();
let (primary_color, error_color, text_color) = {
let colors = {
(
layout.get_primary_color(),
layout.get_error_color(),
layout.get_text_color(),
)
};
if self.is_popup_visible() {
(colors.0.to_dark(), colors.1.to_dark(), colors.2.to_dark())
} else {
colors
}
};
let remaining_time_line = Line::from(vec![
Span::from(format!("⏳{}", self.get_remaining_time(),))
.style(Style::default().fg(primary_color).bold()),
]);
let text_line = self
.generated_text
.chars()
.enumerate()
.map(|(i, c)| {
if i == self.cursor_index {
Span::from(c.to_string()).style(
Style::default()
.fg(layout.get_text_current_color())
.bg(layout.get_text_current_bg_color()),
)
} else if i < self.cursor_index {
if self.input.chars().nth(i) == Some(c) {
Span::from(c.to_string()).style(Style::default().fg(primary_color))
} else {
Span::from(c.to_string()).style(
Style::default()
.fg(error_color)
.add_modifier(Modifier::CROSSED_OUT),
)
}
} else {
Span::from(c.to_string()).style(Style::default().fg(text_color))
}
})
.collect::<Line>();
let empty_line = Line::from(Vec::new());
lines.push(remaining_time_line);
lines.push(empty_line.clone());
lines.push(text_line);
lines.push(empty_line);
let text = Text::from(lines);
Paragraph::new(text).wrap(Wrap { trim: true })
}
}
| rust | MIT | c7c380ec133362c2f2e04d6cb9e1e2b77fd411be | 2026-01-04T20:23:37.632912Z | false |
ivanceras/r2d2-sqlite | https://github.com/ivanceras/r2d2-sqlite/blob/ae6c5ffce0bfdffe199d0470a7df0ff3c676e97d/src/lib.rs | src/lib.rs | #![deny(warnings)]
//! # Sqlite support for the `r2d2` connection pool.
//!
//! Library crate: [r2d2-sqlite](https://crates.io/crates/r2d2-sqlite/)
//!
//! Integrated with: [r2d2](https://crates.io/crates/r2d2)
//! and [rusqlite](https://crates.io/crates/rusqlite)
//!
//! ## Example
//!
//! ```rust,no_run
//! extern crate r2d2;
//! extern crate r2d2_sqlite;
//! extern crate rusqlite;
//!
//! use std::thread;
//! use r2d2_sqlite::SqliteConnectionManager;
//! use rusqlite::params;
//!
//! fn main() {
//! let manager = SqliteConnectionManager::file("file.db");
//! let pool = r2d2::Pool::new(manager).unwrap();
//! pool.get()
//! .unwrap()
//! .execute("CREATE TABLE IF NOT EXISTS foo (bar INTEGER)", params![])
//! .unwrap();
//!
//! (0..10)
//! .map(|i| {
//! let pool = pool.clone();
//! thread::spawn(move || {
//! let conn = pool.get().unwrap();
//! conn.execute("INSERT INTO foo (bar) VALUES (?)", &[&i])
//! .unwrap();
//! })
//! })
//! .collect::<Vec<_>>()
//! .into_iter()
//! .map(thread::JoinHandle::join)
//! .collect::<Result<_, _>>()
//! .unwrap()
//! }
//! ```
pub use rusqlite;
use rusqlite::{Connection, Error, OpenFlags};
use std::fmt;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use uuid::Uuid;
#[derive(Debug)]
enum Source {
File(PathBuf),
Memory(String),
}
type InitFn = dyn Fn(&mut Connection) -> Result<(), rusqlite::Error> + Send + Sync + 'static;
/// An `r2d2::ManageConnection` for `rusqlite::Connection`s.
pub struct SqliteConnectionManager {
source: Source,
flags: OpenFlags,
init: Option<Box<InitFn>>,
_persist: Mutex<Option<Connection>>,
}
impl fmt::Debug for SqliteConnectionManager {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut builder = f.debug_struct("SqliteConnectionManager");
let _ = builder.field("source", &self.source);
let _ = builder.field("flags", &self.source);
let _ = builder.field("init", &self.init.as_ref().map(|_| "InitFn"));
builder.finish()
}
}
impl SqliteConnectionManager {
/// Creates a new `SqliteConnectionManager` from file.
///
/// See `rusqlite::Connection::open`
pub fn file<P: AsRef<Path>>(path: P) -> Self {
Self {
source: Source::File(path.as_ref().to_path_buf()),
flags: OpenFlags::default(),
init: None,
_persist: Mutex::new(None),
}
}
/// Creates a new `SqliteConnectionManager` from memory.
pub fn memory() -> Self {
Self {
source: Source::Memory(Uuid::new_v4().to_string()),
flags: OpenFlags::default(),
init: None,
_persist: Mutex::new(None),
}
}
/// Converts `SqliteConnectionManager` into one that sets OpenFlags upon
/// connection creation.
///
/// See `rustqlite::OpenFlags` for a list of available flags.
pub fn with_flags(self, flags: OpenFlags) -> Self {
Self { flags, ..self }
}
/// Converts `SqliteConnectionManager` into one that calls an initialization
/// function upon connection creation. Could be used to set PRAGMAs, for
/// example.
///
/// ### Example
///
/// Make a `SqliteConnectionManager` that sets the `foreign_keys` pragma to
/// true for every connection.
///
/// ```rust,no_run
/// # use r2d2_sqlite::{SqliteConnectionManager};
/// let manager = SqliteConnectionManager::file("app.db")
/// .with_init(|c| c.execute_batch("PRAGMA foreign_keys=1;"));
/// ```
pub fn with_init<F>(self, init: F) -> Self
where
F: Fn(&mut Connection) -> Result<(), rusqlite::Error> + Send + Sync + 'static,
{
let init: Option<Box<InitFn>> = Some(Box::new(init));
Self { init, ..self }
}
}
impl r2d2::ManageConnection for SqliteConnectionManager {
type Connection = Connection;
type Error = rusqlite::Error;
fn connect(&self) -> Result<Connection, Error> {
match self.source {
Source::File(ref path) => Connection::open_with_flags(path, self.flags),
Source::Memory(ref id) => {
let connection = || {
Connection::open_with_flags(
format!("file:{}?mode=memory&cache=shared", id),
self.flags,
)
};
{
let mut persist = self._persist.lock().unwrap();
if persist.is_none() {
*persist = Some(connection()?);
}
}
connection()
}
}
.map_err(Into::into)
.and_then(|mut c| match self.init {
None => Ok(c),
Some(ref init) => init(&mut c).map(|_| c),
})
}
fn is_valid(&self, conn: &mut Connection) -> Result<(), Error> {
conn.execute_batch("SELECT 1;").map_err(Into::into)
}
fn has_broken(&self, _: &mut Connection) -> bool {
false
}
}
| rust | MIT | ae6c5ffce0bfdffe199d0470a7df0ff3c676e97d | 2026-01-04T20:23:38.713984Z | false |
ivanceras/r2d2-sqlite | https://github.com/ivanceras/r2d2-sqlite/blob/ae6c5ffce0bfdffe199d0470a7df0ff3c676e97d/tests/test.rs | tests/test.rs | extern crate r2d2;
extern crate r2d2_sqlite;
extern crate rusqlite;
extern crate tempfile;
use std::sync::mpsc;
use std::thread;
use r2d2::ManageConnection;
use tempfile::TempDir;
use r2d2_sqlite::SqliteConnectionManager;
use rusqlite::Connection;
#[test]
fn test_basic() {
let manager = SqliteConnectionManager::file("file.db");
let pool = r2d2::Pool::builder().max_size(2).build(manager).unwrap();
let (s1, r1) = mpsc::channel();
let (s2, r2) = mpsc::channel();
let pool1 = pool.clone();
let t1 = thread::spawn(move || {
let conn = pool1.get().unwrap();
s1.send(()).unwrap();
r2.recv().unwrap();
drop(conn);
});
let pool2 = pool.clone();
let t2 = thread::spawn(move || {
let conn = pool2.get().unwrap();
s2.send(()).unwrap();
r1.recv().unwrap();
drop(conn);
});
t1.join().unwrap();
t2.join().unwrap();
pool.get().unwrap();
}
#[test]
fn test_file() {
let manager = SqliteConnectionManager::file("file.db");
let pool = r2d2::Pool::builder().max_size(2).build(manager).unwrap();
let (s1, r1) = mpsc::channel();
let (s2, r2) = mpsc::channel();
let pool1 = pool.clone();
let t1 = thread::spawn(move || {
let conn = pool1.get().unwrap();
let _: &Connection = &*conn;
s1.send(()).unwrap();
r2.recv().unwrap();
});
let pool2 = pool.clone();
let t2 = thread::spawn(move || {
let conn = pool2.get().unwrap();
s2.send(()).unwrap();
r1.recv().unwrap();
drop(conn);
});
t1.join().unwrap();
t2.join().unwrap();
pool.get().unwrap();
}
#[test]
fn test_is_valid() {
let manager = SqliteConnectionManager::file("file.db");
let pool = r2d2::Pool::builder()
.max_size(1)
.test_on_check_out(true)
.build(manager)
.unwrap();
pool.get().unwrap();
}
#[test]
fn test_error_handling() {
//! We specify a directory as a database. This is bound to fail.
let dir = TempDir::new().expect("Could not create temporary directory");
let dirpath = dir.path().to_str().unwrap();
let manager = SqliteConnectionManager::file(dirpath);
assert!(manager.connect().is_err());
}
#[test]
fn test_with_flags() {
// Open db as read only and try to modify it, it should fail
let manager = SqliteConnectionManager::file("file.db")
.with_flags(rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY);
let pool = r2d2::Pool::builder().max_size(2).build(manager).unwrap();
let conn = pool.get().unwrap();
let result = conn.execute_batch("CREATE TABLE hello(world)");
assert!(result.is_err());
}
#[test]
fn test_with_init() {
fn trace_sql(sql: &str) {
println!("{}", sql)
}
// Set user_version in init, then read it back to check that it was set
let manager = SqliteConnectionManager::file("file.db").with_init(|c| {
c.trace(Some(trace_sql));
c.execute_batch("PRAGMA user_version=123")
});
let pool = r2d2::Pool::builder().max_size(2).build(manager).unwrap();
let conn = pool.get().unwrap();
let db_version = conn
.query_row(
"PRAGMA user_version",
&[] as &[&dyn rusqlite::types::ToSql],
|r| r.get::<_, i32>(0),
)
.unwrap();
assert_eq!(db_version, 123);
}
#[test]
fn test_in_memory_db_is_shared() {
let manager = SqliteConnectionManager::memory();
let pool = r2d2::Pool::builder().max_size(10).build(manager).unwrap();
pool.get()
.unwrap()
.execute("CREATE TABLE IF NOT EXISTS foo (bar INTEGER)", [])
.unwrap();
(0..10)
.map(|i: i32| {
let pool = pool.clone();
std::thread::spawn(move || {
let conn = pool.get().unwrap();
conn.execute("INSERT INTO foo (bar) VALUES (?)", [i])
.unwrap();
})
})
.collect::<Vec<_>>()
.into_iter()
.try_for_each(std::thread::JoinHandle::join)
.unwrap();
let conn = pool.get().unwrap();
let mut stmt = conn.prepare("SELECT bar from foo").unwrap();
let mut rows: Vec<i32> = stmt
.query_map([], |row| row.get(0))
.unwrap()
.into_iter()
.flatten()
.collect();
rows.sort_unstable();
assert_eq!(rows, (0..10).collect::<Vec<_>>());
}
#[test]
fn test_different_in_memory_dbs_are_not_shared() {
let manager1 = SqliteConnectionManager::memory();
let pool1 = r2d2::Pool::new(manager1).unwrap();
let manager2 = SqliteConnectionManager::memory();
let pool2 = r2d2::Pool::new(manager2).unwrap();
pool1
.get()
.unwrap()
.execute_batch("CREATE TABLE foo (bar INTEGER)")
.unwrap();
let result = pool2
.get()
.unwrap()
.execute_batch("CREATE TABLE foo (bar INTEGER)");
assert!(result.is_ok());
}
#[test]
fn test_in_memory_db_persists() {
let manager = SqliteConnectionManager::memory();
{
// Normally, `r2d2::Pool` won't drop connection unless timed-out or broken.
// So let's drop managed connection instead.
let conn = manager.connect().unwrap();
conn.execute_batch("CREATE TABLE foo (bar INTEGER)")
.unwrap();
}
let conn = manager.connect().unwrap();
let mut stmt = conn.prepare("SELECT * from foo").unwrap();
let result = stmt.execute([]);
assert!(result.is_ok());
}
| rust | MIT | ae6c5ffce0bfdffe199d0470a7df0ff3c676e97d | 2026-01-04T20:23:38.713984Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/settings.rs | src/settings.rs | use crate::player::{AudioBackend, SpotifyPlayerSettings};
use gio::prelude::SettingsExt;
use libadwaita::ColorScheme;
use librespot::playback::config::Bitrate;
const SETTINGS: &str = "dev.diegovsky.Riff";
#[derive(Clone, Debug, Default)]
pub struct WindowGeometry {
pub width: i32,
pub height: i32,
pub is_maximized: bool,
}
impl WindowGeometry {
pub fn new_from_gsettings() -> Self {
let settings = gio::Settings::new(SETTINGS);
Self {
width: settings.int("window-width"),
height: settings.int("window-height"),
is_maximized: settings.boolean("window-is-maximized"),
}
}
pub fn save(&self) -> Option<()> {
let settings = gio::Settings::new(SETTINGS);
settings.delay();
settings.set_int("window-width", self.width).ok()?;
settings.set_int("window-height", self.height).ok()?;
settings
.set_boolean("window-is-maximized", self.is_maximized)
.ok()?;
settings.apply();
Some(())
}
}
// Player (librespot) settings
impl SpotifyPlayerSettings {
pub fn new_from_gsettings() -> Option<Self> {
let settings = gio::Settings::new(SETTINGS);
let bitrate = match settings.enum_("player-bitrate") {
0 => Some(Bitrate::Bitrate96),
1 => Some(Bitrate::Bitrate160),
2 => Some(Bitrate::Bitrate320),
_ => None,
}?;
let backend = match settings.enum_("audio-backend") {
0 => Some(AudioBackend::PulseAudio),
1 => Some(AudioBackend::Alsa(
settings.string("alsa-device").as_str().to_string(),
)),
2 => Some(AudioBackend::GStreamer(
"audioconvert dithering=none ! audioresample ! pipewiresink".to_string(), // This should be configurable eventually
)),
_ => None,
}?;
let gapless = settings.boolean("gapless-playback");
let ap_port_val = settings.uint("ap-port");
if ap_port_val > 65535 {
panic!("Invalid access point port");
}
// Access points usually use port 80, 443 or 4070. Since gsettings
// does not allow optional values, we use 0 to indicate that any
// port is OK and we should pass None to librespot's ap-port.
let ap_port = match ap_port_val {
0 => None,
x => Some(x as u16),
};
Some(Self {
bitrate,
backend,
gapless,
ap_port,
})
}
}
#[derive(Debug, Clone)]
pub struct RiffSettings {
pub theme_preference: ColorScheme,
pub player_settings: SpotifyPlayerSettings,
pub window: WindowGeometry,
}
// Application settings
impl RiffSettings {
pub fn new_from_gsettings() -> Option<Self> {
let settings = gio::Settings::new(SETTINGS);
let theme_preference = match settings.enum_("theme-preference") {
0 => Some(ColorScheme::ForceLight),
1 => Some(ColorScheme::ForceDark),
2 => Some(ColorScheme::Default),
_ => None,
}?;
Some(Self {
theme_preference,
player_settings: SpotifyPlayerSettings::new_from_gsettings()?,
window: WindowGeometry::new_from_gsettings(),
})
}
}
impl Default for RiffSettings {
fn default() -> Self {
Self {
theme_preference: ColorScheme::PreferDark,
player_settings: Default::default(),
window: Default::default(),
}
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/main.rs | src/main.rs | #[macro_use(clone)]
extern crate glib;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate gettextrs;
use app::state::ScreenName;
use futures::channel::mpsc::UnboundedSender;
use gettextrs::*;
use gio::prelude::*;
use gio::ApplicationFlags;
use gio::SimpleAction;
use gtk::prelude::*;
mod api;
mod app;
mod config;
mod connect;
mod dbus;
mod player;
mod settings;
use crate::app::components::expose_custom_widgets;
use crate::app::dispatch::{spawn_task_handler, DispatchLoop};
use crate::app::{state::PlaybackAction, App, AppAction, BrowserAction};
fn main() {
let settings = settings::RiffSettings::new_from_gsettings().unwrap_or_default();
setup_gtk(&settings);
// Looks like there's a side effect to declaring widgets that allows them to be referenced them in ui/blueprint files
// so here goes!
expose_custom_widgets();
let gtk_app = gtk::Application::new(Some(config::APPID), ApplicationFlags::HANDLES_OPEN);
let builder = gtk::Builder::from_resource("/dev/diegovsky/Riff/window.ui");
let window: libadwaita::ApplicationWindow = builder.object("window").unwrap();
// In debug mode, the app id is different (see meson config) so we fix the resource path (and add a distinctive style)
// Having a different app id allows running both the stable and development version at the same time
if cfg!(debug_assertions) {
// window.add_css_class("devel");
gtk_app.set_resource_base_path(Some("/dev/diegovsky/Riff"));
}
let context = glib::MainContext::default();
let dispatch_loop = DispatchLoop::new();
let sender = dispatch_loop.make_dispatcher();
// Couple of actions used with shortcuts
register_actions(>k_app, sender.clone());
setup_credits(builder.object::<libadwaita::AboutDialog>("about").unwrap());
// Main app logic is hooked up here
let app = App::new(
settings,
builder,
sender.clone(),
spawn_task_handler(&context),
);
context.spawn_local(app.attach(dispatch_loop));
let sender_clone = sender.clone();
gtk_app.connect_activate(move |gtk_app| {
debug!("activate");
if let Some(existing_window) = gtk_app.active_window() {
existing_window.present();
} else {
// Only send the Start action if we've just created the window
window.set_application(Some(gtk_app));
gtk_app.add_window(&window);
sender_clone.unbounded_send(AppAction::Start).unwrap();
}
});
gtk_app.connect_open(move |gtk_app, targets, _| {
gtk_app.activate();
// There should only be one target because %u is used in desktop file
let target = &targets[0];
let uri = target.uri().to_string();
let action = AppAction::OpenURI(uri)
.unwrap_or_else(|| AppAction::ShowNotification(gettext("Failed to open link!")));
sender.unbounded_send(action).unwrap();
});
context.invoke_local(move || {
gtk_app.run();
});
std::process::exit(0);
}
fn setup_gtk(settings: &settings::RiffSettings) {
// Setup logging
env_logger::init();
// Setup translations
textdomain("riff")
.and_then(|_| bindtextdomain("riff", config::LOCALEDIR))
.and_then(|_| bind_textdomain_codeset("riff", "UTF-8"))
.expect("Could not setup localization");
// Setup Gtk, Adwaita...
gtk::init().unwrap_or_else(|_| panic!("Failed to initialize GTK"));
libadwaita::init().unwrap_or_else(|_| panic!("Failed to initialize libadwaita"));
let manager = libadwaita::StyleManager::default();
manager.set_color_scheme(settings.theme_preference);
let res = gio::Resource::load(config::PKGDATADIR.to_owned() + "/riff.gresource")
.expect("Could not load resources");
gio::resources_register(&res);
let provider = gtk::CssProvider::new();
provider.load_from_resource("/dev/diegovsky/Riff/app.css");
gtk::style_context_add_provider_for_display(
&gdk::Display::default().unwrap(),
&provider,
gtk::STYLE_PROVIDER_PRIORITY_APPLICATION,
);
}
fn setup_credits(about: libadwaita::AboutDialog) {
// Read from a couple files at compile time and update the about dialog
let authors: Vec<&str> = include_str!("../AUTHORS")
.trim_end_matches('\n')
.split('\n')
.collect();
let translators = include_str!("../TRANSLATORS").trim_end_matches('\n');
let artists: Vec<&str> = include_str!("../ARTISTS")
.trim_end_matches('\n')
.split('\n')
.collect();
about.set_version(config::VERSION);
about.set_developers(&authors);
about.set_translator_credits(translators);
about.set_artists(&artists);
}
fn register_actions(app: >k::Application, sender: UnboundedSender<AppAction>) {
let quit = SimpleAction::new("quit", None);
quit.connect_activate(clone!(
#[weak]
app,
move |_, _| {
if let Some(existing_window) = app.active_window() {
existing_window.close();
}
app.quit();
}
));
app.add_action(&quit);
app.add_action(&make_action(
"toggle_playback",
PlaybackAction::TogglePlay.into(),
sender.clone(),
));
app.add_action(&make_action(
"player_prev",
PlaybackAction::Previous.into(),
sender.clone(),
));
app.add_action(&make_action(
"player_next",
PlaybackAction::Next.into(),
sender.clone(),
));
app.add_action(&make_action(
"nav_pop",
AppAction::BrowserAction(BrowserAction::NavigationPop),
sender.clone(),
));
app.add_action(&make_action(
"search",
AppAction::BrowserAction(BrowserAction::NavigationPush(ScreenName::Search)),
sender.clone(),
));
app.add_action(&{
let action = SimpleAction::new("open_playlist", Some(glib::VariantTy::STRING));
action.set_enabled(true);
action.connect_activate(move |_, playlist_id| {
if let Some(id) = playlist_id.and_then(|s| s.str()) {
sender
.unbounded_send(AppAction::ViewPlaylist(id.to_owned()))
.unwrap();
}
});
action
});
}
fn make_action(
name: &str,
app_action: AppAction,
sender: UnboundedSender<AppAction>,
) -> SimpleAction {
let action = SimpleAction::new(name, None);
action.connect_activate(move |_, _| {
sender.unbounded_send(app_action.clone()).unwrap();
});
action
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/dbus/listener.rs | src/dbus/listener.rs | use futures::channel::mpsc::UnboundedSender;
use std::rc::Rc;
use crate::app::{
components::EventListener,
models::{RepeatMode, SongDescription},
state::PlaybackEvent,
AppEvent, AppModel,
};
use super::types::{LoopStatus, PlaybackStatus, TrackMetadata};
#[derive(Debug)]
#[allow(clippy::enum_variant_names)]
pub enum MprisStateUpdate {
SetVolume(f64),
SetCurrentTrack {
has_prev: bool,
current: Option<TrackMetadata>,
has_next: bool,
},
SetPositionMs(u128),
SetLoopStatus {
has_prev: bool,
loop_status: LoopStatus,
has_next: bool,
},
SetShuffled(bool),
SetPlaying(PlaybackStatus),
}
pub struct AppPlaybackStateListener {
app_model: Rc<AppModel>,
sender: UnboundedSender<MprisStateUpdate>,
}
impl AppPlaybackStateListener {
pub fn new(app_model: Rc<AppModel>, sender: UnboundedSender<MprisStateUpdate>) -> Self {
Self { app_model, sender }
}
fn make_track_meta(&self) -> Option<TrackMetadata> {
let SongDescription {
id,
title,
artists,
album,
duration,
art,
..
} = self.app_model.get_state().playback.current_song()?;
Some(TrackMetadata {
id: format!("/dev/diegovsky/Riff/Track/{id}"),
length: 1000 * duration as u64,
title,
album: album.name,
artist: artists.into_iter().map(|a| a.name).collect(),
art,
})
}
fn has_prev_next(&self) -> (bool, bool) {
let state = self.app_model.get_state();
(
state.playback.prev_index().is_some(),
state.playback.next_index().is_some(),
)
}
fn loop_status(&self) -> LoopStatus {
let state = self.app_model.get_state();
match state.playback.repeat_mode() {
RepeatMode::None => LoopStatus::None,
RepeatMode::Song => LoopStatus::Track,
RepeatMode::Playlist => LoopStatus::Playlist,
}
}
fn update_for(&self, event: &PlaybackEvent) -> Option<MprisStateUpdate> {
match event {
PlaybackEvent::PlaybackPaused => {
Some(MprisStateUpdate::SetPlaying(PlaybackStatus::Paused))
}
PlaybackEvent::PlaybackResumed => {
Some(MprisStateUpdate::SetPlaying(PlaybackStatus::Playing))
}
PlaybackEvent::PlaybackStopped => {
Some(MprisStateUpdate::SetPlaying(PlaybackStatus::Stopped))
}
PlaybackEvent::TrackChanged(_) => {
let current = self.make_track_meta();
let (has_prev, has_next) = self.has_prev_next();
Some(MprisStateUpdate::SetCurrentTrack {
has_prev,
has_next,
current,
})
}
PlaybackEvent::RepeatModeChanged(_) => {
let loop_status = self.loop_status();
let (has_prev, has_next) = self.has_prev_next();
Some(MprisStateUpdate::SetLoopStatus {
has_prev,
has_next,
loop_status,
})
}
PlaybackEvent::ShuffleChanged(shuffled) => {
Some(MprisStateUpdate::SetShuffled(*shuffled))
}
PlaybackEvent::TrackSeeked(pos) | PlaybackEvent::SeekSynced(pos) => {
let pos = 1000 * (*pos as u128);
Some(MprisStateUpdate::SetPositionMs(pos))
}
PlaybackEvent::VolumeSet(vol) => Some(MprisStateUpdate::SetVolume(*vol)),
_ => None,
}
}
}
impl EventListener for AppPlaybackStateListener {
fn on_event(&mut self, event: &AppEvent) {
if let AppEvent::PlaybackEvent(event) = event {
if let Some(update) = self.update_for(event) {
self.sender
.unbounded_send(update)
.expect("Could not send event to DBUS server");
}
}
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/dbus/types.rs | src/dbus/types.rs | use std::convert::{Into, TryFrom};
use std::time::Instant;
use zvariant::Type;
use zvariant::{Dict, Signature, Str, Value};
fn boxed_value<'a, V: Into<Value<'a>>>(v: V) -> Value<'a> {
Value::new(v.into())
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LoopStatus {
None,
Track,
Playlist,
}
impl Type for LoopStatus {
fn signature() -> Signature<'static> {
Str::signature()
}
}
impl From<Value<'_>> for LoopStatus {
fn from(value: Value<'_>) -> Self {
String::try_from(value)
.map(|s| match s.as_str() {
"Track" => LoopStatus::Track,
"Playlist" => LoopStatus::Playlist,
_ => LoopStatus::None,
})
.unwrap_or(LoopStatus::None)
}
}
impl From<LoopStatus> for Value<'_> {
fn from(status: LoopStatus) -> Self {
match status {
LoopStatus::None => "None".into(),
LoopStatus::Track => "Track".into(),
LoopStatus::Playlist => "Playlist".into(),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PlaybackStatus {
Playing,
Paused,
Stopped,
}
impl Type for PlaybackStatus {
fn signature() -> Signature<'static> {
Str::signature()
}
}
impl From<PlaybackStatus> for Value<'_> {
fn from(status: PlaybackStatus) -> Self {
match status {
PlaybackStatus::Playing => "Playing".into(),
PlaybackStatus::Paused => "Paused".into(),
PlaybackStatus::Stopped => "Stopped".into(),
}
}
}
struct PositionMicros {
last_known_position: u128,
last_resume_instant: Option<Instant>,
rate: f32,
}
impl PositionMicros {
fn new(rate: f32) -> Self {
Self {
last_known_position: 0,
last_resume_instant: None,
rate,
}
}
fn current(&self) -> u128 {
let current_progress = self.last_resume_instant.map(|ri| {
let elapsed = ri.elapsed().as_micros() as f32;
let real_elapsed = self.rate * elapsed;
real_elapsed.ceil() as u128
});
self.last_known_position + current_progress.unwrap_or(0)
}
fn set(&mut self, position: u128, playing: bool) {
self.last_known_position = position;
self.last_resume_instant = if playing { Some(Instant::now()) } else { None }
}
fn pause(&mut self) {
self.last_known_position = self.current();
self.last_resume_instant = None;
}
fn resume(&mut self) {
self.last_resume_instant = Some(Instant::now());
}
}
#[derive(Debug, Clone)]
pub struct TrackMetadata {
pub id: String,
pub length: u64,
pub artist: Vec<String>,
pub album: String,
pub title: String,
pub art: Option<String>,
}
impl Type for TrackMetadata {
fn signature() -> Signature<'static> {
Signature::from_str_unchecked("a{sv}")
}
}
impl From<TrackMetadata> for Value<'_> {
fn from(meta: TrackMetadata) -> Self {
let mut d = Dict::new(Str::signature(), Value::signature());
d.append("mpris:trackid".into(), boxed_value(meta.id))
.unwrap();
d.append("mpris:length".into(), boxed_value(meta.length))
.unwrap();
d.append("xesam:title".into(), boxed_value(meta.title))
.unwrap();
d.append("xesam:artist".into(), boxed_value(meta.artist.clone()))
.unwrap();
d.append("xesam:albumArtist".into(), boxed_value(meta.artist))
.unwrap();
d.append("xesam:album".into(), boxed_value(meta.album))
.unwrap();
if let Some(art) = meta.art {
d.append("mpris:artUrl".into(), boxed_value(art)).unwrap();
}
Value::Dict(d)
}
}
pub struct MprisState {
status: PlaybackStatus,
loop_status: LoopStatus,
volume: f64,
shuffled: bool,
position: PositionMicros,
metadata: Option<TrackMetadata>,
has_prev: bool,
has_next: bool,
}
impl MprisState {
pub fn new() -> Self {
Self {
status: PlaybackStatus::Stopped,
loop_status: LoopStatus::None,
shuffled: false,
position: PositionMicros::new(1.0),
metadata: None,
has_prev: false,
has_next: false,
volume: 1f64,
}
}
pub fn volume(&self) -> f64 {
self.volume
}
pub fn set_volume(&mut self, volume: f64) {
self.volume = volume;
}
pub fn status(&self) -> PlaybackStatus {
self.status
}
pub fn loop_status(&self) -> LoopStatus {
self.loop_status
}
pub fn is_shuffled(&self) -> bool {
self.shuffled
}
pub fn current_track(&self) -> Option<&TrackMetadata> {
self.metadata.as_ref()
}
pub fn has_prev(&self) -> bool {
self.has_prev
}
pub fn has_next(&self) -> bool {
self.has_next
}
pub fn set_has_prev(&mut self, has_prev: bool) {
self.has_prev = has_prev;
}
pub fn set_has_next(&mut self, has_next: bool) {
self.has_next = has_next;
}
pub fn set_current_track(&mut self, track: Option<TrackMetadata>) {
let playing = self.status == PlaybackStatus::Playing;
self.metadata = track;
self.position.set(0, playing);
}
pub fn position(&self) -> u128 {
self.position.current()
}
pub fn set_position(&mut self, position: u128) {
let playing = self.status == PlaybackStatus::Playing;
self.position.set(position, playing);
}
pub fn set_loop_status(&mut self, loop_status: LoopStatus) {
self.loop_status = loop_status;
}
pub fn set_shuffled(&mut self, shuffled: bool) {
self.shuffled = shuffled;
}
pub fn set_playing(&mut self, status: PlaybackStatus) {
self.status = status;
match status {
PlaybackStatus::Playing => {
self.position.resume();
}
PlaybackStatus::Paused => {
self.position.pause();
}
PlaybackStatus::Stopped => {
self.position.set(0, false);
}
}
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/dbus/mpris.rs | src/dbus/mpris.rs | #![allow(non_snake_case)]
#![allow(unused_variables)]
use std::collections::HashMap;
use std::convert::TryInto;
use futures::channel::mpsc::UnboundedSender;
use zbus::fdo::{Error, Result};
use zbus::{interface, Interface, SignalContext};
use zvariant::{ObjectPath, Value};
use super::types::*;
use crate::app::models::RepeatMode;
use crate::app::state::PlaybackAction;
use crate::app::AppAction;
#[derive(Clone)]
pub struct RiffMpris {
sender: UnboundedSender<AppAction>,
}
impl RiffMpris {
pub fn new(sender: UnboundedSender<AppAction>) -> Self {
Self { sender }
}
}
#[interface(interface = "org.mpris.MediaPlayer2")]
impl RiffMpris {
fn quit(&self) -> Result<()> {
Err(Error::NotSupported("Not implemented".to_string()))
}
fn raise(&self) -> Result<()> {
self.sender
.unbounded_send(AppAction::Raise)
.map_err(|_| Error::Failed("Could not send action".to_string()))
}
#[zbus(property)]
fn can_quit(&self) -> bool {
false
}
#[zbus(property)]
fn can_raise(&self) -> bool {
true
}
#[zbus(property)]
fn has_track_list(&self) -> bool {
false
}
#[zbus(property)]
fn identity(&self) -> &'static str {
"Riff"
}
#[zbus(property)]
fn supported_mime_types(&self) -> Vec<String> {
vec![]
}
#[zbus(property)]
fn supported_uri_schemes(&self) -> Vec<String> {
vec![]
}
#[zbus(property)]
fn desktop_entry(&self) -> &'static str {
"dev.diegovsky.Riff"
}
}
pub struct RiffMprisPlayer {
state: MprisState,
sender: UnboundedSender<AppAction>,
}
impl RiffMprisPlayer {
pub fn new(sender: UnboundedSender<AppAction>) -> Self {
Self {
state: MprisState::new(),
sender,
}
}
pub fn state_mut(&mut self) -> &mut MprisState {
&mut self.state
}
pub async fn notify_current_track_changed(&self, ctxt: &SignalContext<'_>) -> zbus::Result<()> {
let metadata = Value::from(self.metadata());
let can_go_next = Value::from(self.can_go_next());
let can_go_previous = Value::from(self.can_go_previous());
zbus::fdo::Properties::properties_changed(
ctxt,
Self::name(),
&HashMap::from([
("Metadata", &metadata),
("CanGoNext", &can_go_next),
("CanGoPrevious", &can_go_previous),
]),
&[],
)
.await
}
pub async fn notify_loop_status(&self, ctxt: &SignalContext<'_>) -> zbus::Result<()> {
let loop_status = Value::from(self.loop_status());
let can_go_next = Value::from(self.can_go_next());
let can_go_previous = Value::from(self.can_go_previous());
zbus::fdo::Properties::properties_changed(
ctxt,
Self::name(),
&HashMap::from([
("LoopStatus", &loop_status),
("CanGoNext", &can_go_next),
("CanGoPrevious", &can_go_previous),
]),
&[],
)
.await
}
}
#[interface(interface = "org.mpris.MediaPlayer2.Player")]
impl RiffMprisPlayer {
pub fn next(&self) -> Result<()> {
self.sender
.unbounded_send(PlaybackAction::Next.into())
.map_err(|_| Error::Failed("Could not send action".to_string()))
}
pub fn open_uri(&self, Uri: &str) -> Result<()> {
Err(Error::NotSupported("Not implemented".to_string()))
}
pub fn pause(&self) -> Result<()> {
self.sender
.unbounded_send(PlaybackAction::Pause.into())
.map_err(|_| Error::Failed("Could not send action".to_string()))
}
pub fn play(&self) -> Result<()> {
self.sender
.unbounded_send(PlaybackAction::Play.into())
.map_err(|_| Error::Failed("Could not send action".to_string()))
}
pub fn play_pause(&self) -> Result<()> {
self.sender
.unbounded_send(PlaybackAction::TogglePlay.into())
.map_err(|_| Error::Failed("Could not send action".to_string()))
}
pub fn previous(&self) -> Result<()> {
self.sender
.unbounded_send(PlaybackAction::Previous.into())
.map_err(|_| Error::Failed("Could not send action".to_string()))
}
pub fn seek(&self, Offset: i64) -> Result<()> {
if self.state.current_track().is_none() {
return Ok(());
}
let mut new_pos: i128 = (self.state.position() as i128 + i128::from(Offset)) / 1000;
// As per spec, if new position is less than 0 round to 0
if new_pos < 0 {
new_pos = 0;
}
let new_pos: u32 = (new_pos)
.try_into()
.map_err(|_| Error::Failed("Could not parse position".to_string()))?;
// As per spec, if new position is past the length of the song skip to
// the next song
if u64::from(new_pos) >= self.metadata().length / 1000 {
self.sender
.unbounded_send(PlaybackAction::Next.into())
.map_err(|_| Error::Failed("Could not send action".to_string()))
} else {
self.sender
.unbounded_send(PlaybackAction::Seek(new_pos).into())
.map_err(|_| Error::Failed("Could not send action".to_string()))
}
}
pub fn set_position(&self, TrackId: ObjectPath, Position: i64) -> Result<()> {
if self.state.current_track().is_none() {
return Ok(());
}
if TrackId.to_string() != self.metadata().id {
return Ok(());
}
let length: i64 = self
.metadata()
.length
.try_into()
.map_err(|_| Error::Failed("Could not cast length (too large)".to_string()))?;
if Position > length {
return Ok(());
}
let pos: u32 = (Position / 1000)
.try_into()
.map_err(|_| Error::Failed("Could not parse position".to_string()))?;
self.sender
.unbounded_send(PlaybackAction::Seek(pos).into())
.map_err(|_| Error::Failed("Could not send action".to_string()))
}
pub fn stop(&self) -> Result<()> {
Err(Error::NotSupported("Not implemented".to_string()))
}
#[zbus(signal)]
pub async fn seeked(ctxt: &SignalContext<'_>, Position: i64) -> zbus::Result<()>;
#[zbus(property)]
pub fn can_control(&self) -> bool {
true
}
#[zbus(property)]
pub fn can_go_next(&self) -> bool {
self.state.has_next()
}
#[zbus(property)]
pub fn can_go_previous(&self) -> bool {
self.state.has_prev()
}
#[zbus(property)]
pub fn can_pause(&self) -> bool {
true
}
#[zbus(property)]
pub fn can_play(&self) -> bool {
true
}
#[zbus(property)]
pub fn can_seek(&self) -> bool {
self.state.current_track().is_some()
}
#[zbus(property)]
pub fn maximum_rate(&self) -> f64 {
1.0f64
}
#[zbus(property)]
pub fn metadata(&self) -> TrackMetadata {
self.state
.current_track()
.cloned()
.unwrap_or_else(|| TrackMetadata {
id: String::new(),
length: 0,
title: "Not playing".to_string(),
artist: vec![],
album: String::new(),
art: None,
})
}
#[zbus(property)]
pub fn minimum_rate(&self) -> f64 {
1.0f64
}
#[zbus(property)]
pub fn playback_status(&self) -> PlaybackStatus {
self.state.status()
}
#[zbus(property)]
pub fn loop_status(&self) -> LoopStatus {
self.state.loop_status()
}
#[zbus(property)]
pub fn set_loop_status(&self, value: LoopStatus) -> zbus::Result<()> {
let mode = match value {
LoopStatus::None => RepeatMode::None,
LoopStatus::Track => RepeatMode::Song,
LoopStatus::Playlist => RepeatMode::Playlist,
};
self.sender
.unbounded_send(PlaybackAction::SetRepeatMode(mode).into())
.map_err(|_| Error::Failed("Could not send action".to_string()))?;
Ok(())
}
#[zbus(property)]
pub fn position(&self) -> i64 {
self.state.position() as i64
}
#[zbus(property)]
pub fn rate(&self) -> f64 {
1.0f64
}
#[zbus(property)]
pub fn set_rate(&self, value: f64) {}
#[zbus(property)]
pub fn shuffle(&self) -> bool {
self.state.is_shuffled()
}
#[zbus(property)]
pub fn set_shuffle(&self, value: bool) -> zbus::Result<()> {
self.sender
.unbounded_send(PlaybackAction::ToggleShuffle.into())
.map_err(|_| Error::Failed("Could not send action".to_string()))?;
Ok(())
}
#[zbus(property)]
pub fn volume(&self) -> f64 {
self.state.volume()
}
#[zbus(property)]
pub fn set_volume(&self, value: f64) -> zbus::Result<()> {
// As per spec, if new volume less than 0 round to 0
// also, we don't support volume higher than 100% at the moment.
let volume = value.clamp(0.0, 1.0);
self.sender
.unbounded_send(PlaybackAction::SetVolume(value).into())
.map_err(|_| Error::Failed("Could not send action".to_string()))?;
Ok(())
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/dbus/mod.rs | src/dbus/mod.rs | use futures::channel::mpsc::{unbounded, UnboundedReceiver, UnboundedSender};
use futures::StreamExt;
use std::rc::Rc;
use std::thread;
use zbus::Connection;
use crate::app::{AppAction, AppModel};
mod mpris;
pub use mpris::*;
mod types;
mod listener;
use listener::*;
#[tokio::main]
async fn dbus_server(
mpris: RiffMpris,
player: RiffMprisPlayer,
receiver: UnboundedReceiver<MprisStateUpdate>,
) -> zbus::Result<()> {
let connection = Connection::session().await?;
connection
.object_server()
.at("/org/mpris/MediaPlayer2", mpris)
.await?;
connection
.object_server()
.at("/org/mpris/MediaPlayer2", player)
.await?;
connection
.request_name("org.mpris.MediaPlayer2.Riff")
.await?;
receiver
.for_each(|update| async {
if let Ok(player_ref) = connection
.object_server()
.interface::<_, RiffMprisPlayer>("/org/mpris/MediaPlayer2")
.await
{
let mut player = player_ref.get_mut().await;
let ctxt = player_ref.signal_context();
let res: zbus::Result<()> = match update {
MprisStateUpdate::SetVolume(volume) => {
player.state_mut().set_volume(volume);
player.volume_changed(ctxt).await
}
MprisStateUpdate::SetCurrentTrack {
has_prev,
has_next,
current,
} => {
player.state_mut().set_has_prev(has_prev);
player.state_mut().set_has_next(has_next);
player.state_mut().set_current_track(current);
player.notify_current_track_changed(ctxt).await
}
MprisStateUpdate::SetPositionMs(position) => {
player.state_mut().set_position(position);
Ok(())
}
MprisStateUpdate::SetLoopStatus {
has_prev,
has_next,
loop_status,
} => {
player.state_mut().set_has_prev(has_prev);
player.state_mut().set_has_next(has_next);
player.state_mut().set_loop_status(loop_status);
player.notify_loop_status(ctxt).await
}
MprisStateUpdate::SetShuffled(shuffled) => {
player.state_mut().set_shuffled(shuffled);
player.shuffle_changed(ctxt).await
}
MprisStateUpdate::SetPlaying(status) => {
player.state_mut().set_playing(status);
player.playback_status_changed(ctxt).await
}
};
res.expect("Signal emission failed");
}
})
.await;
Ok(())
}
pub fn start_dbus_server(
app_model: Rc<AppModel>,
sender: UnboundedSender<AppAction>,
) -> AppPlaybackStateListener {
let mpris = RiffMpris::new(sender.clone());
let player = RiffMprisPlayer::new(sender);
let (sender, receiver) = unbounded();
thread::spawn(move || dbus_server(mpris, player, receiver));
AppPlaybackStateListener::new(app_model, sender)
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/dispatch.rs | src/app/dispatch.rs | use futures::channel::mpsc::{unbounded, UnboundedReceiver, UnboundedSender};
use futures::future::BoxFuture;
use futures::future::Future;
use futures::stream::StreamExt;
use std::pin::Pin;
use super::AppAction;
// A wrapper around an MPSC sender to send AppActions synchronously or asynchronously
// It is a trait because I guess I wanted to be able to stub it, but see how that went...
pub trait ActionDispatcher {
fn dispatch(&self, action: AppAction);
fn dispatch_many(&self, actions: Vec<AppAction>);
fn dispatch_async(&self, action: BoxFuture<'static, Option<AppAction>>);
fn dispatch_many_async(&self, actions: BoxFuture<'static, Vec<AppAction>>);
// Can't have impl Clone easily so there you go
fn box_clone(&self) -> Box<dyn ActionDispatcher>;
}
#[derive(Clone)]
pub struct ActionDispatcherImpl {
sender: UnboundedSender<AppAction>,
worker: Worker,
}
impl ActionDispatcherImpl {
pub fn new(sender: UnboundedSender<AppAction>, worker: Worker) -> Self {
Self { sender, worker }
}
}
impl ActionDispatcher for ActionDispatcherImpl {
fn dispatch(&self, action: AppAction) {
self.sender.unbounded_send(action).unwrap();
}
fn dispatch_many(&self, actions: Vec<AppAction>) {
for action in actions.into_iter() {
self.sender.unbounded_send(action).unwrap();
}
}
fn dispatch_async(&self, action: BoxFuture<'static, Option<AppAction>>) {
let clone = self.sender.clone();
self.worker.send_task(async move {
if let Some(action) = action.await {
clone.unbounded_send(action).unwrap();
}
});
}
fn dispatch_many_async(&self, actions: BoxFuture<'static, Vec<AppAction>>) {
let clone = self.sender.clone();
self.worker.send_task(async move {
for action in actions.await.into_iter() {
clone.unbounded_send(action).unwrap();
}
});
}
fn box_clone(&self) -> Box<dyn ActionDispatcher> {
Box::new(self.clone())
}
}
// Funky name for a mere wrapper around an MPSC send/recv pair
pub struct DispatchLoop {
receiver: UnboundedReceiver<AppAction>,
sender: UnboundedSender<AppAction>,
}
impl DispatchLoop {
pub fn new() -> Self {
let (sender, receiver) = unbounded::<AppAction>();
Self { receiver, sender }
}
pub fn make_dispatcher(&self) -> UnboundedSender<AppAction> {
self.sender.clone()
}
pub async fn attach(self, mut handler: impl FnMut(AppAction)) {
self.receiver
.for_each(|action| {
handler(action);
async {}
})
.await;
}
}
pub type FutureTask = Pin<Box<dyn Future<Output = ()> + Send>>;
pub type FutureLocalTask = Pin<Box<dyn Future<Output = ()>>>;
// The Worker (see below) is a glorified way to send an async task to the GLib(rs) future executor
pub fn spawn_task_handler(context: &glib::MainContext) -> Worker {
let (future_local_sender, future_local_receiver) = unbounded::<FutureLocalTask>();
context.spawn_local_with_priority(
glib::Priority::DEFAULT_IDLE,
future_local_receiver.for_each(|t| t),
);
let (future_sender, future_receiver) = unbounded::<FutureTask>();
context.spawn_with_priority(
glib::Priority::DEFAULT_IDLE,
future_receiver.for_each(|t| t),
);
Worker(future_local_sender, future_sender)
}
// Again, fancy name for an MPSC sender
// Actually two of them, in case you need to send local futures (no Send needed)
#[derive(Clone)]
pub struct Worker(
UnboundedSender<FutureLocalTask>,
UnboundedSender<FutureTask>,
);
impl Worker {
pub fn send_local_task<T: Future<Output = ()> + 'static>(&self, task: T) -> Option<()> {
self.0.unbounded_send(Box::pin(task)).ok()
}
pub fn send_task<T: Future<Output = ()> + Send + 'static>(&self, task: T) -> Option<()> {
self.1.unbounded_send(Box::pin(task)).ok()
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/mod.rs | src/app/mod.rs | use crate::settings::RiffSettings;
use crate::PlaybackAction;
use crate::{api::CachedSpotifyClient, player::TokenStore};
use futures::channel::mpsc::UnboundedSender;
use std::rc::Rc;
use std::sync::Arc;
pub mod dispatch;
pub use dispatch::{ActionDispatcher, ActionDispatcherImpl, DispatchLoop, Worker};
pub mod components;
use components::*;
pub mod models;
mod list_store;
pub use list_store::*;
pub mod state;
pub use state::{AppAction, AppEvent, AppModel, AppState, BrowserAction, BrowserEvent};
mod batch_loader;
pub use batch_loader::*;
pub mod credentials;
pub mod loader;
pub mod rng;
pub use rng::LazyRandomIndex;
// Where all the app logic happens
pub struct App {
settings: RiffSettings,
// The builder instance used to properly configure all the widgets created at startup
builder: gtk::Builder,
// All the "components" that will be notified of things happening throughout the app
components: Vec<Box<dyn EventListener>>,
// Holds the app state
model: Rc<AppModel>,
// Allows sending actions that are handled by the model above
sender: UnboundedSender<AppAction>,
worker: Worker,
}
impl App {
pub fn new(
settings: RiffSettings,
builder: gtk::Builder,
sender: UnboundedSender<AppAction>,
worker: Worker,
) -> Self {
let state = AppState::new();
let token_store = Arc::new(TokenStore::new());
let spotify_client = Arc::new(CachedSpotifyClient::new(Arc::clone(&token_store)));
let model = Rc::new(AppModel::new(state, spotify_client));
// Non widget components
let components: Vec<Box<dyn EventListener>> = vec![
App::make_player_notifier(
Rc::clone(&model),
&settings,
Box::new(ActionDispatcherImpl::new(sender.clone(), worker.clone())),
sender.clone(),
token_store,
),
App::make_dbus(Rc::clone(&model), sender.clone()),
];
Self {
settings,
builder,
components,
model,
sender,
worker,
}
}
fn add_ui_components(&mut self) {
// Most components will need some or all of these to work
// ie some way to retrieve widgets
let builder = &self.builder;
// ...some way to read the app state
let model = &self.model;
// ...some way to handle various asynchronous tasks
let worker = &self.worker;
// ...some (basic) way to send actions that will change the app state
let sender = &self.sender;
// ...ALSO some way to send actions, but more conveniently
let dispatcher = Box::new(ActionDispatcherImpl::new(sender.clone(), worker.clone()));
// For now, we hardcode 70% volume
// it would be nice to get this from gsettings *wink wink*
dispatcher.dispatch(PlaybackAction::SetVolume(0.7).into());
// All components that will be available initially
let mut components: Vec<Box<dyn EventListener>> = vec![
App::make_window(&self.settings, builder, Rc::clone(model)),
App::make_selection_toolbar(builder, Rc::clone(model), dispatcher.box_clone()),
App::make_playback(
builder,
Rc::clone(model),
dispatcher.box_clone(),
worker.clone(),
),
App::make_login(builder, dispatcher.box_clone()),
App::make_navigation(
builder,
Rc::clone(model),
dispatcher.box_clone(),
worker.clone(),
),
App::make_search_button(builder, dispatcher.box_clone()),
App::make_user_menu(builder, Rc::clone(model), dispatcher),
App::make_notification(builder),
];
self.components.append(&mut components);
}
// A component that listens to what's happening in the app, and translates it for the actual player
fn make_player_notifier(
app_model: Rc<AppModel>,
settings: &RiffSettings,
dispatcher: Box<dyn ActionDispatcher>,
sender: UnboundedSender<AppAction>,
token_store: Arc<TokenStore>,
) -> Box<impl EventListener> {
let api = app_model.get_spotify();
Box::new(PlayerNotifier::new(
app_model,
dispatcher,
// Either communications with the librespot player
crate::player::start_player_service(
settings.player_settings.clone(),
sender.clone(),
token_store,
),
// or with a Spotify Connect device
crate::connect::start_connect_server(api, sender),
))
}
// A component to handle anything DBUS related
fn make_dbus(
app_model: Rc<AppModel>,
sender: UnboundedSender<AppAction>,
) -> Box<impl EventListener> {
Box::new(crate::dbus::start_dbus_server(app_model, sender))
}
fn make_window(
settings: &RiffSettings,
builder: >k::Builder,
app_model: Rc<AppModel>,
) -> Box<impl EventListener> {
let window: libadwaita::ApplicationWindow = builder.object("window").unwrap();
Box::new(MainWindow::new(settings.window.clone(), app_model, window))
}
fn make_navigation(
builder: >k::Builder,
app_model: Rc<AppModel>,
dispatcher: Box<dyn ActionDispatcher>,
worker: Worker,
) -> Box<Navigation> {
let split_view: libadwaita::NavigationSplitView = builder.object("split_view").unwrap();
let navigation_stack: gtk::Stack = builder.object("navigation_stack").unwrap();
let home_listbox: gtk::ListBox = builder.object("home_listbox").unwrap();
let model = NavigationModel::new(Rc::clone(&app_model), dispatcher.box_clone());
// This is where components that are not created initially will be assembled
let screen_factory =
ScreenFactory::new(Rc::clone(&app_model), dispatcher.box_clone(), worker);
Box::new(Navigation::new(
model,
split_view,
navigation_stack,
home_listbox,
screen_factory,
))
}
fn make_login(builder: >k::Builder, dispatcher: Box<dyn ActionDispatcher>) -> Box<Login> {
let parent: gtk::Window = builder.object("window").unwrap();
let model = LoginModel::new(dispatcher);
Box::new(Login::new(parent, model))
}
fn make_selection_toolbar(
builder: >k::Builder,
app_model: Rc<AppModel>,
dispatcher: Box<dyn ActionDispatcher>,
) -> Box<impl EventListener> {
Box::new(SelectionToolbar::new(
SelectionToolbarModel::new(app_model, dispatcher),
builder.object("selection_toolbar").unwrap(),
))
}
fn make_playback(
builder: >k::Builder,
app_model: Rc<AppModel>,
dispatcher: Box<dyn ActionDispatcher>,
worker: Worker,
) -> Box<impl EventListener> {
let model = PlaybackModel::new(app_model, dispatcher);
Box::new(PlaybackControl::new(
model,
builder.object("playback").unwrap(),
worker,
))
}
fn make_search_button(
builder: >k::Builder,
dispatcher: Box<dyn ActionDispatcher>,
) -> Box<SearchButton> {
let search_button: gtk::Button = builder.object("search_button").unwrap();
let model = SearchBarModel(dispatcher);
Box::new(SearchButton::new(model, search_button))
}
fn make_user_menu(
builder: >k::Builder,
app_model: Rc<AppModel>,
dispatcher: Box<dyn ActionDispatcher>,
) -> Box<UserMenu> {
let parent: gtk::Window = builder.object("window").unwrap();
let settings_model = SettingsModel::new(app_model.clone(), dispatcher.box_clone());
let settings = Settings::new(parent.clone(), settings_model);
let button: gtk::MenuButton = builder.object("user").unwrap();
let about: libadwaita::AboutDialog = builder.object("about").unwrap();
let model = UserMenuModel::new(app_model, dispatcher);
let user_menu = UserMenu::new(button, settings, about, parent, model);
Box::new(user_menu)
}
fn make_notification(builder: >k::Builder) -> Box<Notification> {
let toast_overlay: libadwaita::ToastOverlay = builder.object("main").unwrap();
Box::new(Notification::new(toast_overlay))
}
// Main handler called in a loop
fn handle(&mut self, action: AppAction) {
let starting = matches!(&action, &AppAction::Start);
// Update the state based on an incoming action
// and obtain events representing what that mutation entailed...
let events = self.model.update_state(action);
// (AppAction::Start is special and is used to setup the initial components)
if !events.is_empty() && starting {
self.add_ui_components();
}
// ...and notify every component that we know.
// They'll be responsible for passing down these events, if they feel like it.
for event in events.iter() {
for component in self.components.iter_mut() {
component.on_event(event);
}
}
}
// Here is the loop
pub async fn attach(mut self, dispatch_loop: DispatchLoop) {
let rt = tokio::runtime::Runtime::new().expect("Failed to acquire tokio runtime");
let _guard = rt.enter();
let app = &mut self;
dispatch_loop
.attach(move |action| {
app.handle(action);
})
.await;
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/loader.rs | src/app/loader.rs | use crate::api::cache::*;
use gdk_pixbuf::{prelude::PixbufLoaderExt, Pixbuf, PixbufLoader};
use isahc::config::Configurable;
use isahc::{AsyncBody, AsyncReadResponseExt, HttpClient, Response};
use std::collections::hash_map::DefaultHasher;
use std::hash::Hasher;
use std::io::{Error, ErrorKind, Write};
// A wrapper to be able to implement the Write trait on a PixbufLoader
struct LocalPixbufLoader<'a>(&'a PixbufLoader);
impl Write for LocalPixbufLoader<'_> {
fn write(&mut self, buf: &[u8]) -> Result<usize, Error> {
self.0
.write(buf)
.map_err(|e| Error::new(ErrorKind::Other, format!("glib error: {e}")))?;
Ok(buf.len())
}
fn flush(&mut self) -> Result<(), Error> {
self.0
.close()
.map_err(|e| Error::new(ErrorKind::Other, format!("glib error: {e}")))?;
Ok(())
}
}
// A helper to load remote images, with simple cache management
pub struct ImageLoader {
cache: CacheManager,
}
impl ImageLoader {
pub fn new() -> Self {
Self {
cache: CacheManager::for_dir("riff/img").unwrap(),
}
}
// Downloaded images are simply named [hash of url].[file extension]
fn resource_for(url: &str, ext: &str) -> String {
let mut hasher = DefaultHasher::new();
hasher.write(url.as_bytes());
let hashed = hasher.finish().to_string();
hashed + "." + ext
}
async fn get_image(url: &str) -> Option<Response<AsyncBody>> {
let mut builder = HttpClient::builder();
if cfg!(debug_assertions) {
builder = builder.ssl_options(isahc::config::SslOption::DANGER_ACCEPT_INVALID_CERTS);
}
let client = builder.build().unwrap();
client.get_async(url).await.ok()
}
pub async fn load_remote(
&self,
url: &str,
ext: &str,
width: i32,
height: i32,
) -> Option<Pixbuf> {
let resource = Self::resource_for(url, ext);
let pixbuf_loader = PixbufLoader::new();
pixbuf_loader.set_size(width, height);
let mut loader = LocalPixbufLoader(&pixbuf_loader);
// Try to read from cache first, ignoring possible expiry
match self
.cache
.read_cache_file(&resource[..], CachePolicy::IgnoreExpiry)
.await
{
// Write content of cache file to the pixbuf loader if the cache contained something
Ok(CacheFile::Fresh(buffer)) => {
loader.write_all(&buffer[..]).ok()?;
}
// Otherwise, get image over HTTP
_ => {
if let Some(mut resp) = Self::get_image(url).await {
let mut buffer = vec![];
// Copy the image to a buffer...
resp.copy_to(&mut buffer).await.ok()?;
// ... copy the buffer to the loader...
loader.write_all(&buffer[..]).ok()?;
// ... but also save that buffer to cache
self.cache
.write_cache_file(&resource[..], &buffer[..], CacheExpiry::Never)
.await
.ok()?;
}
}
};
pixbuf_loader.close().ok()?;
pixbuf_loader.pixbuf()
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/list_store.rs | src/app/list_store.rs | use gio::prelude::*;
use glib::clone::{Downgrade, Upgrade};
use std::iter::Iterator;
use std::marker::PhantomData;
// A wrapper around a GIO ListStore
// DEPRECATED
pub struct ListStore<GType> {
store: gio::ListStore,
_marker: PhantomData<GType>,
}
pub struct WeakListStore<GType> {
store: <gio::ListStore as Downgrade>::Weak,
_marker: PhantomData<GType>,
}
impl<GType> ListStore<GType>
where
GType: IsA<glib::Object>,
{
pub fn new() -> Self {
Self {
store: gio::ListStore::new::<GType>(),
_marker: PhantomData,
}
}
pub fn inner(&self) -> &gio::ListStore {
&self.store
}
pub fn prepend(&mut self, elements: impl Iterator<Item = GType>) {
let upcast_vec: Vec<glib::Object> = elements.map(|e| e.upcast::<glib::Object>()).collect();
self.store.splice(0, 0, &upcast_vec[..]);
}
pub fn extend(&mut self, elements: impl Iterator<Item = GType>) {
let upcast_vec: Vec<glib::Object> = elements.map(|e| e.upcast::<glib::Object>()).collect();
self.store.splice(self.store.n_items(), 0, &upcast_vec[..]);
}
pub fn replace_all(&mut self, elements: impl Iterator<Item = GType>) {
let upcast_vec: Vec<glib::Object> = elements.map(|e| e.upcast::<glib::Object>()).collect();
self.store.splice(0, self.store.n_items(), &upcast_vec[..]);
}
pub fn insert(&mut self, position: u32, element: GType) {
self.store.insert(position, &element);
}
pub fn remove(&mut self, position: u32) {
self.store.remove(position);
}
pub fn get(&self, index: u32) -> GType {
self.store.item(index).unwrap().downcast::<GType>().unwrap()
}
pub fn iter(&self) -> impl Iterator<Item = GType> + '_ {
let store = &self.store;
let count = store.n_items();
(0..count).map(move |i| self.get(i))
}
pub fn len(&self) -> usize {
self.store.n_items() as usize
}
// Quick and dirty comparison between the list store and a slice of object that can be compared
// with the contents of the store using some function F.
// Not so great but eh
pub fn eq<F, O>(&self, other: &[O], comparison: F) -> bool
where
F: Fn(>ype, &O) -> bool,
{
self.len() == other.len()
&& self
.iter()
.zip(other.iter())
.all(|(left, right)| comparison(&left, right))
}
}
impl<GType> Clone for ListStore<GType> {
fn clone(&self) -> Self {
Self {
store: self.store.clone(),
_marker: PhantomData,
}
}
}
impl<GType> Downgrade for ListStore<GType> {
type Weak = WeakListStore<GType>;
fn downgrade(&self) -> Self::Weak {
Self::Weak {
store: Downgrade::downgrade(&self.store),
_marker: PhantomData,
}
}
}
impl<GType> Upgrade for WeakListStore<GType> {
type Strong = ListStore<GType>;
fn upgrade(&self) -> Option<Self::Strong> {
Some(Self::Strong {
store: self.store.upgrade()?,
_marker: PhantomData,
})
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/credentials.rs | src/app/credentials.rs | use serde::{Deserialize, Serialize};
use secret_service::{EncryptionType, Error, SecretService};
use std::{collections::HashMap, time::SystemTime};
static SPOT_ATTR: &str = "spot_credentials";
// I'm not sure this is the right way to make credentials identifiable, but hey, it works
fn make_attributes() -> HashMap<&'static str, &'static str> {
let mut attributes = HashMap::new();
attributes.insert(SPOT_ATTR, "yes");
attributes
}
// A (statically accessed) wrapper around the DBUS Secret Service
#[derive(Deserialize, Serialize, Clone, Debug)]
pub struct Credentials {
pub access_token: String,
pub refresh_token: String,
pub token_expiry_time: Option<SystemTime>,
}
impl Credentials {
pub fn token_expired(&self) -> bool {
match self.token_expiry_time {
Some(v) => SystemTime::now() > v,
None => true,
}
}
pub async fn retrieve() -> Result<Self, Error> {
let service = SecretService::connect(EncryptionType::Dh).await?;
let collection = service.get_default_collection().await?;
if collection.is_locked().await? {
collection.unlock().await?;
}
let items = collection.search_items(make_attributes()).await?;
let item = items.first().ok_or(Error::NoResult)?.get_secret().await?;
serde_json::from_slice(&item).map_err(|_| Error::Unavailable)
}
// Try to clear the credentials
pub async fn logout() -> Result<(), Error> {
let service = SecretService::connect(EncryptionType::Dh).await?;
let collection = service.get_default_collection().await?;
if !collection.is_locked().await? {
let result = collection.search_items(make_attributes()).await?;
let item = result.first().ok_or(Error::NoResult)?;
item.delete().await
} else {
warn!("Keyring is locked -- not clearing credentials");
Ok(())
}
}
pub async fn save(&self) -> Result<(), Error> {
let service = SecretService::connect(EncryptionType::Dh).await?;
let collection = service.get_default_collection().await?;
if collection.is_locked().await? {
collection.unlock().await?;
}
// We simply write our stuct as JSON and send it
info!("Saving credentials");
let encoded = serde_json::to_vec(&self).unwrap();
collection
.create_item(
"Spotify Credentials",
make_attributes(),
&encoded,
true,
"text/plain",
)
.await?;
info!("Saved credentials");
Ok(())
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/batch_loader.rs | src/app/batch_loader.rs | use gettextrs::gettext;
use std::sync::Arc;
use crate::api::{SpotifyApiClient, SpotifyApiError};
use crate::app::models::*;
use crate::app::AppAction;
// A wrapper around the Spotify API to load batches of songs from various sources (see below)
#[derive(Clone)]
pub struct BatchLoader {
api: Arc<dyn SpotifyApiClient + Send + Sync>,
}
// The sources mentionned above
#[derive(Clone, Debug)]
pub enum SongsSource {
Playlist(String),
Album(String),
SavedTracks,
}
impl PartialEq for SongsSource {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Playlist(l), Self::Playlist(r)) => l == r,
(Self::Album(l), Self::Album(r)) => l == r,
(Self::SavedTracks, Self::SavedTracks) => true,
_ => false,
}
}
}
impl Eq for SongsSource {}
impl SongsSource {
pub fn has_spotify_uri(&self) -> bool {
matches!(self, Self::Playlist(_) | Self::Album(_))
}
pub fn spotify_uri(&self) -> Option<String> {
match self {
Self::Playlist(id) => Some(format!("spotify:playlist:{}", id)),
Self::Album(id) => Some(format!("spotify:album:{}", id)),
_ => None,
}
}
}
// How to query for a batch: specify a source, and a batch to get (offset + number of elements to get)
#[derive(Debug)]
pub struct BatchQuery {
pub source: SongsSource,
pub batch: Batch,
}
impl BatchQuery {
// Given a query, compute the next batch to get (if any)
pub fn next(&self) -> Option<Self> {
let Self { source, batch } = self;
Some(Self {
source: source.clone(),
batch: batch.next()?,
})
}
}
impl BatchLoader {
pub fn new(api: Arc<dyn SpotifyApiClient + Send + Sync>) -> Self {
Self { api }
}
// Query a batch and create an action when it's been retrieved succesfully
pub async fn query<ActionCreator>(
&self,
query: BatchQuery,
create_action: ActionCreator,
) -> Option<AppAction>
where
ActionCreator: FnOnce(SongsSource, SongBatch) -> AppAction,
{
let api = Arc::clone(&self.api);
let Batch {
offset, batch_size, ..
} = query.batch;
let result = match &query.source {
SongsSource::Playlist(id) => api.get_playlist_tracks(id, offset, batch_size).await,
SongsSource::SavedTracks => api.get_saved_tracks(offset, batch_size).await,
SongsSource::Album(id) => api.get_album_tracks(id, offset, batch_size).await,
};
match result {
Ok(batch) => Some(create_action(query.source, batch)),
// No token? Why was the batch loader called? Ah, whatever
Err(SpotifyApiError::NoToken) => None,
Err(err) => {
error!("Spotify API error: {}", err);
Some(AppAction::ShowNotification(gettext(
// translators: This notification is the default message for unhandled errors. Logs refer to console output.
"An error occured. Check logs for details!",
)))
}
}
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/rng.rs | src/app/rng.rs | use rand::{rngs::SmallRng, RngCore, SeedableRng};
// A random, resizable mapping (i-th element to play => j-th track) used to handle shuffled playlists
// It's lazy: initially we don't compute what index i maps to
// It's resizable: if our playlist grows or shrinks, we have to keep the generated mappings stable
// (we don't want to reshuffle!)
#[derive(Debug)]
pub struct LazyRandomIndex {
rng: SmallRng,
indices: Vec<usize>,
// How many mapping were generated
generated: usize,
}
impl Default for LazyRandomIndex {
fn default() -> Self {
Self::from(SmallRng::from_entropy())
}
}
impl LazyRandomIndex {
fn from(rng: SmallRng) -> Self {
Self {
rng,
indices: Default::default(),
generated: 0,
}
}
// Resets the mapping, but make sure some index `first` will be mapped from 0
// This is used to "pin" the position of a track when switching in and out of shuffle mode
// See tests below for an example
pub fn reset_picking_first(&mut self, first: usize) {
self.generated = 0;
if let Some(index) = self.indices.iter().position(|i| *i == first) {
self.pick_next(index);
}
}
// Grow or shrink
pub fn resize(&mut self, size: usize) {
if size >= self.indices.len() {
self.grow(size);
} else {
self.shrink(size);
}
}
// Resize the underlying Vec, but we don't generate mappings yet
// We don't update the `generated` count: for now whatever is beyond that index is just the non-shuffled index
pub fn grow(&mut self, size: usize) {
let current_size = self.indices.len();
self.indices.extend(current_size..size);
}
pub fn shrink(&mut self, size: usize) {
self.generated = usize::min(size, self.generated);
self.indices.truncate(size);
}
// Get the index (for instance in a playlist) of the i-th next element to play
pub fn get(&self, i: usize) -> Option<usize> {
if i >= self.generated || i >= self.indices.len() {
None
} else {
Some(self.indices[i])
}
}
// Generate all mappings until the mapping for i has been generated
pub fn next_until(&mut self, i: usize) -> Option<usize> {
if i >= self.indices.len() {
return None;
}
loop {
if self.generated > i {
break Some(self.indices[i]);
}
self.next();
}
}
// Generate the next mapping
pub fn next(&mut self) -> Option<usize> {
if self.indices.len() < self.generated {
return None;
}
let last = self.generated;
// Pick a random index in the range [k, n[ where
// k is the next index to map
// n is the size of our targeted list
// The element at that index will be swapped with whatever is in pos k
// That is, we never mess with the already picked indices, we want this to be stable:
// a0, a1, ..., ak-1, ak, ..., an
// <-already mapped->
// <-not mapped->
// We just pick something between k and n and make it ak
// Example gen with size 3
// [0, 1, 2], generated = 0
// [1, 0, 2], generated = 1, we swapped 0 and 1
// [1, 0, 2], generated = 2, we swapped 1 and 1 (no-op)
// [1, 0, 2], generated = 3, no-op again (no choice, only one element left to place)
let next = (self.rng.next_u64() as usize) % (self.indices.len() - last) + last;
Some(self.pick_next(next))
}
fn pick_next(&mut self, next: usize) -> usize {
let last = self.generated;
self.indices.swap(last, next);
self.generated += 1;
self.indices[last]
}
}
#[cfg(test)]
mod tests {
use super::*;
fn rng_for_test() -> SmallRng {
SmallRng::seed_from_u64(0)
}
fn get_sequence(n: usize) -> Vec<usize> {
let mut rng = rng_for_test();
(0..n)
.into_iter()
.map(|_| rng.next_u64() as usize)
.collect()
}
#[test]
fn test_initial() {
let seq = get_sequence(10);
let first = Some(seq[0] % 10);
// It's controlled randomness for the test :)
let mut index = LazyRandomIndex::from(rng_for_test());
index.grow(10);
let next = index.next();
assert_eq!(next, first);
assert_eq!(index.get(0), first);
}
#[test]
fn test_sample_all() {
let mut index = LazyRandomIndex::from(rng_for_test());
index.grow(2);
index.grow(5);
let mut values = (0..5)
.into_iter()
.filter_map(|_| index.next())
.collect::<Vec<usize>>();
let sorted = &mut values[..];
sorted.sort();
// Check that we have all our indices mapped
assert_eq!(sorted, &[0, 1, 2, 3, 4]);
}
#[test]
fn test_after_grow() {
let mut index = LazyRandomIndex::from(rng_for_test());
index.grow(5);
index.next_until(2);
let values = &[index.get(0), index.get(1), index.get(2)];
index.grow(10);
let same_values = &[index.get(0), index.get(1), index.get(2)];
// After growing the index from 5 to 10, we want to check
// that the previously generated mappings are unaffected.
assert_eq!(values, same_values);
}
#[test]
fn test_reset() {
let mut index = LazyRandomIndex::from(rng_for_test());
// Example use
// Assume we have 5 songs in our shuffled playlist, and we generate those 5 few random mappings
index.grow(5);
index.next_until(5);
// We exit shuffle mode at some point
// Shuffle is toggled again: we want index 2 to come up first in the shuffled playlist
// because it is what's currently playing.
index.reset_picking_first(2);
assert_eq!(index.get(0), Some(2));
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/state/login_state.rs | src/app/state/login_state.rs | use gettextrs::*;
use std::borrow::Cow;
use url::Url;
use crate::app::models::PlaylistSummary;
use crate::app::state::{AppAction, AppEvent, UpdatableState};
#[derive(Clone, Debug)]
pub enum TryLoginAction {
Restore,
InitLogin,
CompleteLogin,
}
#[derive(Clone, Debug)]
pub enum LoginAction {
ShowLogin,
OpenLoginUrl(Url),
TryLogin(TryLoginAction),
SetLoginSuccess(String),
SetUserPlaylists(Vec<PlaylistSummary>),
UpdateUserPlaylist(PlaylistSummary),
PrependUserPlaylist(Vec<PlaylistSummary>),
SetLoginFailure,
RefreshToken,
TokenRefreshed,
Logout,
}
impl From<LoginAction> for AppAction {
fn from(login_action: LoginAction) -> Self {
Self::LoginAction(login_action)
}
}
#[derive(Clone, Debug)]
pub enum LoginStartedEvent {
Restore,
InitLogin,
CompleteLogin,
OpenUrl(Url),
}
#[derive(Clone, Debug)]
pub enum LoginEvent {
LoginShown,
LoginStarted(LoginStartedEvent),
LoginCompleted,
UserPlaylistsLoaded,
LoginFailed,
FreshTokenRequested,
RefreshTokenCompleted,
LogoutCompleted,
}
impl From<LoginEvent> for AppEvent {
fn from(login_event: LoginEvent) -> Self {
Self::LoginEvent(login_event)
}
}
#[derive(Default)]
pub struct LoginState {
// Username
pub user: Option<String>,
// Playlists owned by the logged in user
pub playlists: Vec<PlaylistSummary>,
}
impl UpdatableState for LoginState {
type Action = LoginAction;
type Event = AppEvent;
// The login state has a lot of actions that just translate to events
fn update_with(&mut self, action: Cow<Self::Action>) -> Vec<Self::Event> {
info!("update_with({:?})", action);
match action.into_owned() {
LoginAction::ShowLogin => vec![LoginEvent::LoginShown.into()],
LoginAction::OpenLoginUrl(url) => {
vec![LoginEvent::LoginStarted(LoginStartedEvent::OpenUrl(url)).into()]
}
LoginAction::TryLogin(TryLoginAction::Restore) => {
vec![LoginEvent::LoginStarted(LoginStartedEvent::Restore).into()]
}
LoginAction::TryLogin(TryLoginAction::CompleteLogin) => {
vec![LoginEvent::LoginStarted(LoginStartedEvent::CompleteLogin).into()]
}
LoginAction::SetLoginSuccess(username) => {
self.user = Some(username);
vec![LoginEvent::LoginCompleted.into()]
}
LoginAction::SetLoginFailure => vec![LoginEvent::LoginFailed.into()],
LoginAction::RefreshToken => vec![LoginEvent::FreshTokenRequested.into()],
LoginAction::TokenRefreshed => {
// translators: This notification is shown when, after some inactivity, the session is successfully restored. The user might have to repeat its last action.
vec![
AppEvent::NotificationShown(gettext("Connection restored")),
LoginEvent::RefreshTokenCompleted.into(),
]
}
LoginAction::Logout => {
self.user = None;
vec![LoginEvent::LogoutCompleted.into()]
}
LoginAction::SetUserPlaylists(playlists) => {
self.playlists = playlists;
vec![LoginEvent::UserPlaylistsLoaded.into()]
}
LoginAction::UpdateUserPlaylist(PlaylistSummary { id, title }) => {
if let Some(p) = self.playlists.iter_mut().find(|p| p.id == id) {
p.title = title;
}
vec![LoginEvent::UserPlaylistsLoaded.into()]
}
LoginAction::PrependUserPlaylist(mut summaries) => {
summaries.append(&mut self.playlists);
self.playlists = summaries;
vec![LoginEvent::UserPlaylistsLoaded.into()]
}
LoginAction::TryLogin(TryLoginAction::InitLogin) => {
vec![LoginEvent::LoginStarted(LoginStartedEvent::InitLogin).into()]
}
}
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/state/selection_state.rs | src/app/state/selection_state.rs | use std::borrow::Cow;
use std::collections::HashSet;
use crate::app::models::SongDescription;
use crate::app::state::{AppAction, AppEvent, UpdatableState};
#[derive(Clone, Debug)]
pub enum SelectionAction {
Select(Vec<SongDescription>),
Deselect(Vec<String>),
Clear,
}
impl From<SelectionAction> for AppAction {
fn from(selection_action: SelectionAction) -> Self {
Self::SelectionAction(selection_action)
}
}
#[derive(Clone, Debug)]
pub enum SelectionEvent {
// Mode means selection active or not
SelectionModeChanged(bool),
SelectionChanged,
}
impl From<SelectionEvent> for AppEvent {
fn from(selection_event: SelectionEvent) -> Self {
Self::SelectionEvent(selection_event)
}
}
#[derive(Debug, Clone)]
pub enum SelectionContext {
ReadOnlyQueue,
Queue,
Playlist,
EditablePlaylist(String),
SavedTracks,
Default,
}
pub struct SelectionState {
selected_songs: Vec<SongDescription>,
selected_songs_ids: HashSet<String>,
selection_active: bool,
pub context: SelectionContext,
}
impl Default for SelectionState {
fn default() -> Self {
Self {
selected_songs: Default::default(),
selected_songs_ids: Default::default(),
selection_active: false,
context: SelectionContext::Default,
}
}
}
impl SelectionState {
fn select(&mut self, song: SongDescription) -> bool {
let selected = self.selected_songs_ids.contains(&song.id);
if !selected {
self.selected_songs_ids.insert(song.id.clone());
self.selected_songs.push(song);
}
!selected
}
fn deselect(&mut self, id: &str) -> bool {
let songs: Vec<SongDescription> = std::mem::take(&mut self.selected_songs)
.into_iter()
.filter(|s| s.id != id)
.collect();
self.selected_songs = songs;
self.selected_songs_ids.remove(id)
}
pub fn set_mode(&mut self, context: Option<SelectionContext>) -> Option<bool> {
let currently_active = self.selection_active;
match (currently_active, context) {
(false, Some(context)) => {
*self = Default::default();
self.selection_active = true;
self.context = context;
Some(true)
}
(true, None) => {
*self = Default::default();
self.selection_active = false;
Some(false)
}
_ => None,
}
}
pub fn is_selection_enabled(&self) -> bool {
self.selection_active
}
pub fn is_song_selected(&self, id: &str) -> bool {
self.selected_songs_ids.contains(id)
}
pub fn count(&self) -> usize {
self.selected_songs_ids.len()
}
// Clears (!) the selection, returns associated memory
pub fn take_selection(&mut self) -> Vec<SongDescription> {
std::mem::take(self).selected_songs
}
// Just have a look at the selection without changing it
pub fn peek_selection(&self) -> impl Iterator<Item = &'_ SongDescription> {
self.selected_songs.iter()
}
}
impl UpdatableState for SelectionState {
type Action = SelectionAction;
type Event = SelectionEvent;
fn update_with(&mut self, action: Cow<Self::Action>) -> Vec<Self::Event> {
match action.into_owned() {
SelectionAction::Select(tracks) => {
let changed = tracks
.into_iter()
.fold(false, |result, track| self.select(track) || result);
if changed {
vec![SelectionEvent::SelectionChanged]
} else {
vec![]
}
}
SelectionAction::Deselect(ids) => {
let changed = ids
.iter()
.fold(false, |result, id| self.deselect(id) || result);
if changed {
vec![SelectionEvent::SelectionChanged]
} else {
vec![]
}
}
SelectionAction::Clear => {
self.take_selection();
vec![SelectionEvent::SelectionModeChanged(false)]
}
}
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/state/browser_state.rs | src/app/state/browser_state.rs | use super::{
AppAction, AppEvent, ArtistState, DetailsState, HomeState, PlaylistDetailsState, ScreenName,
SearchState, UpdatableState, UserState,
};
use crate::app::models::*;
use std::borrow::Cow;
use std::iter::Iterator;
// Actions that affect any "screen" that we push over time
#[derive(Clone, Debug)]
pub enum BrowserAction {
SetNavigationHidden(bool),
SetHomeVisiblePage(&'static str),
SetLibraryContent(Vec<AlbumDescription>),
PrependPlaylistsContent(Vec<PlaylistDescription>),
AppendLibraryContent(Vec<AlbumDescription>),
SetPlaylistsContent(Vec<PlaylistDescription>),
AppendPlaylistsContent(Vec<PlaylistDescription>),
RemoveTracksFromPlaylist(String, Vec<String>),
SetAlbumDetails(Box<AlbumFullDescription>),
AppendAlbumTracks(String, Box<SongBatch>),
SetPlaylistDetails(Box<PlaylistDescription>, Box<SongBatch>),
UpdatePlaylistName(PlaylistSummary),
AppendPlaylistTracks(String, Box<SongBatch>),
Search(String),
SetSearchResults(Box<SearchResults>),
SetArtistDetails(Box<ArtistDescription>),
AppendArtistReleases(String, Vec<AlbumDescription>),
NavigationPush(ScreenName),
NavigationPop,
NavigationPopTo(ScreenName),
SaveAlbum(Box<AlbumDescription>),
UnsaveAlbum(String),
SetUserDetails(Box<UserDescription>),
AppendUserPlaylists(String, Vec<PlaylistDescription>),
SetSavedTracks(Box<SongBatch>),
AppendSavedTracks(Box<SongBatch>),
SaveTracks(Vec<SongDescription>),
RemoveSavedTracks(Vec<String>),
}
impl From<BrowserAction> for AppAction {
fn from(browser_action: BrowserAction) -> Self {
Self::BrowserAction(browser_action)
}
}
#[derive(Eq, PartialEq, Clone, Debug)]
pub enum BrowserEvent {
NavigationHidden(bool),
HomeVisiblePageChanged(&'static str),
LibraryUpdated,
SavedPlaylistsUpdated,
AlbumDetailsLoaded(String),
AlbumTracksAppended(String),
PlaylistDetailsLoaded(String),
PlaylistTracksAppended(String),
PlaylistTracksRemoved(String),
SearchUpdated,
SearchResultsUpdated,
ArtistDetailsUpdated(String),
NavigationPushed(ScreenName),
NavigationPopped,
NavigationPoppedTo(ScreenName),
AlbumSaved(String),
AlbumUnsaved(String),
UserDetailsUpdated(String),
SavedTracksUpdated,
}
impl From<BrowserEvent> for AppEvent {
fn from(browser_event: BrowserEvent) -> Self {
Self::BrowserEvent(browser_event)
}
}
// Any screen that can be "pushed"
pub enum BrowserScreen {
Home(Box<HomeState>), // Except this one is special, it's there at the start
AlbumDetails(Box<DetailsState>),
Search(Box<SearchState>),
Artist(Box<ArtistState>),
PlaylistDetails(Box<PlaylistDetailsState>),
User(Box<UserState>),
}
impl BrowserScreen {
fn from_name(name: &ScreenName) -> Self {
match name {
ScreenName::Home => BrowserScreen::Home(Default::default()),
ScreenName::AlbumDetails(id) => {
BrowserScreen::AlbumDetails(Box::new(DetailsState::new(id.to_string())))
}
ScreenName::Search => BrowserScreen::Search(Default::default()),
ScreenName::Artist(id) => {
BrowserScreen::Artist(Box::new(ArtistState::new(id.to_string())))
}
ScreenName::PlaylistDetails(id) => {
BrowserScreen::PlaylistDetails(Box::new(PlaylistDetailsState::new(id.to_string())))
}
ScreenName::User(id) => BrowserScreen::User(Box::new(UserState::new(id.to_string()))),
}
}
// Each screen has a state that can be updated with a BrowserAction
fn state(&mut self) -> &mut dyn UpdatableState<Action = BrowserAction, Event = BrowserEvent> {
match self {
Self::Home(state) => &mut **state,
Self::AlbumDetails(state) => &mut **state,
Self::Search(state) => &mut **state,
Self::Artist(state) => &mut **state,
Self::PlaylistDetails(state) => &mut **state,
Self::User(state) => &mut **state,
}
}
}
impl NamedScreen for BrowserScreen {
type Name = ScreenName;
fn name(&self) -> &Self::Name {
match self {
Self::Home(state) => &state.name,
Self::AlbumDetails(state) => &state.name,
Self::Search(state) => &state.name,
Self::Artist(state) => &state.name,
Self::PlaylistDetails(state) => &state.name,
Self::User(state) => &state.name,
}
}
}
pub trait NamedScreen {
type Name: PartialEq;
fn name(&self) -> &Self::Name;
}
#[derive(Debug)]
enum ScreenState {
NotPresent,
Present,
Current,
}
// The navigation stack where we push screens (something with an equatable name)
struct NavStack<Screen>(Vec<Screen>);
impl<Screen> NavStack<Screen>
where
Screen: NamedScreen,
{
// Its len is guaranteed to be always 1 (see can_pop)
fn new(initial: Screen) -> Self {
Self(vec![initial])
}
fn iter_mut(&mut self) -> impl Iterator<Item = &mut Screen> {
self.0.iter_mut().rev()
}
fn iter_rev(&self) -> impl Iterator<Item = &Screen> {
self.0.iter().rev()
}
fn count(&self) -> usize {
self.0.len()
}
fn current(&self) -> &Screen {
self.0.last().unwrap()
}
fn current_mut(&mut self) -> &mut Screen {
self.0.last_mut().unwrap()
}
fn can_pop(&self) -> bool {
self.0.len() > 1
}
fn push(&mut self, screen: Screen) {
self.0.push(screen)
}
fn pop(&mut self) -> bool {
if self.can_pop() {
self.0.pop();
true
} else {
false
}
}
fn pop_to(&mut self, name: &Screen::Name) {
let split = self.0.iter().position(|s| s.name() == name).unwrap();
self.0.truncate(split + 1);
}
fn screen_visibility(&self, name: &Screen::Name) -> ScreenState {
// We iterate screens in reverse order
self.0
.iter()
.rev()
.enumerate()
.find_map(|(i, screen)| {
let is_screen = screen.name() == name;
match (i, is_screen) {
// If we find the screen at pos 0 (last), it's therefore the current screen
(0, true) => Some(ScreenState::Current),
(_, true) => Some(ScreenState::Present),
(_, _) => None,
}
})
.unwrap_or(ScreenState::NotPresent)
}
}
pub struct BrowserState {
navigation_hidden: bool,
navigation: NavStack<BrowserScreen>,
}
macro_rules! extract_state {
($e:expr, $p:pat if $guard:expr => $i:ident) => {
extract_state_full!($e, $p if $guard => $i)
};
($e:expr, $p:pat => $i:ident) => {
extract_state_full!($e, $p if true => $i)
};
}
macro_rules! extract_state_full {
($e:expr, $p:pat if $guard:expr => $i:ident) => {{
$e.navigation.iter_rev().find_map(|screen| match screen {
$p if $guard => Some(&**$i),
_ => None,
})
}};
}
impl BrowserState {
pub fn new() -> Self {
Self {
navigation_hidden: false,
navigation: NavStack::new(BrowserScreen::Home(Default::default())),
}
}
pub fn current_screen(&self) -> &ScreenName {
self.navigation.current().name()
}
pub fn can_pop(&self) -> bool {
self.navigation.can_pop() || self.navigation_hidden
}
pub fn count(&self) -> usize {
self.navigation.count()
}
pub fn home_state(&self) -> Option<&HomeState> {
extract_state!(self, BrowserScreen::Home(s) => s)
}
pub fn home_state_mut(&mut self) -> Option<&mut HomeState> {
self.navigation.iter_mut().find_map(|screen| match screen {
BrowserScreen::Home(s) => Some(&mut **s),
_ => None,
})
}
pub fn details_state(&self, id: &str) -> Option<&DetailsState> {
extract_state!(self, BrowserScreen::AlbumDetails(state) if state.id == id => state)
}
pub fn search_state(&self) -> Option<&SearchState> {
extract_state!(self, BrowserScreen::Search(s) => s)
}
pub fn artist_state(&self, id: &str) -> Option<&ArtistState> {
extract_state!(self, BrowserScreen::Artist(state) if state.id == id => state)
}
pub fn playlist_details_state(&self, id: &str) -> Option<&PlaylistDetailsState> {
extract_state!(self, BrowserScreen::PlaylistDetails(state) if state.id == id => state)
}
pub fn user_state(&self, id: &str) -> Option<&UserState> {
extract_state!(self, BrowserScreen::User(state) if state.id == id => state)
}
// If a screen we want to push is already in the stack
// we just pop all the way back to it
fn push_if_needed(&mut self, name: &ScreenName) -> Vec<BrowserEvent> {
let navigation = &mut self.navigation;
let screen_visibility = navigation.screen_visibility(name);
match screen_visibility {
ScreenState::Current => vec![],
ScreenState::Present => {
navigation.pop_to(name);
vec![BrowserEvent::NavigationPoppedTo(name.clone())]
}
ScreenState::NotPresent => {
navigation.push(BrowserScreen::from_name(name));
vec![BrowserEvent::NavigationPushed(name.clone())]
}
}
}
}
impl UpdatableState for BrowserState {
type Action = BrowserAction;
type Event = BrowserEvent;
fn update_with(&mut self, action: Cow<Self::Action>) -> Vec<Self::Event> {
let can_pop = self.navigation.can_pop();
let action_ref = action.as_ref();
match action_ref {
BrowserAction::SetNavigationHidden(navigation_hidden) => {
self.navigation_hidden = *navigation_hidden;
vec![BrowserEvent::NavigationHidden(*navigation_hidden)]
}
// The search action will be handled here first before being passed down
// to push the search screen if it's not there already
BrowserAction::Search(_) => {
let mut events = self.push_if_needed(&ScreenName::Search);
let mut update_events = self.navigation.current_mut().state().update_with(action);
events.append(&mut update_events);
events
}
BrowserAction::NavigationPush(name) => self.push_if_needed(name),
BrowserAction::NavigationPopTo(name) => {
self.navigation.pop_to(name);
vec![BrowserEvent::NavigationPoppedTo(name.clone())]
}
BrowserAction::NavigationPop if can_pop => {
self.navigation.pop();
vec![BrowserEvent::NavigationPopped]
}
BrowserAction::NavigationPop if self.navigation_hidden => {
self.navigation_hidden = false;
vec![BrowserEvent::NavigationHidden(false)]
}
// Besides navigation actions, we just forward actions to each dedicated reducer
_ => self
.navigation
.iter_mut()
.flat_map(|s| s.state().update_with(Cow::Borrowed(action_ref)))
.collect(),
}
}
}
#[cfg(test)]
pub mod tests {
use super::*;
#[test]
fn test_navigation_push() {
let mut state = BrowserState::new();
assert_eq!(*state.current_screen(), ScreenName::Home);
assert_eq!(state.count(), 1);
let new_screen = ScreenName::Artist("some_id".to_string());
state.update_with(Cow::Owned(BrowserAction::NavigationPush(
new_screen.clone(),
)));
assert_eq!(state.current_screen(), &new_screen);
assert_eq!(state.count(), 2);
assert_eq!(state.artist_state("some_id").is_some(), true);
}
#[test]
fn test_navigation_pop() {
let mut state = BrowserState::new();
let new_screen = ScreenName::Artist("some_id".to_string());
state.update_with(Cow::Owned(BrowserAction::NavigationPush(
new_screen.clone(),
)));
assert_eq!(state.current_screen(), &new_screen);
assert_eq!(state.count(), 2);
state.update_with(Cow::Owned(BrowserAction::NavigationPop));
assert_eq!(state.current_screen(), &ScreenName::Home);
assert_eq!(state.count(), 1);
let events = state.update_with(Cow::Owned(BrowserAction::NavigationPop));
assert_eq!(state.current_screen(), &ScreenName::Home);
assert_eq!(state.count(), 1);
assert_eq!(events, vec![]);
}
#[test]
fn test_navigation_push_same_screen() {
let mut state = BrowserState::new();
let new_screen = ScreenName::Artist("some_id".to_string());
state.update_with(Cow::Owned(BrowserAction::NavigationPush(
new_screen.clone(),
)));
assert_eq!(state.current_screen(), &new_screen);
assert_eq!(state.count(), 2);
let events = state.update_with(Cow::Owned(BrowserAction::NavigationPush(
new_screen.clone(),
)));
assert_eq!(state.current_screen(), &new_screen);
assert_eq!(state.count(), 2);
assert_eq!(events, vec![]);
}
#[test]
fn test_navigation_push_same_screen_will_pop() {
let mut state = BrowserState::new();
let new_screen = ScreenName::Artist("some_id".to_string());
state.update_with(Cow::Owned(BrowserAction::NavigationPush(
new_screen.clone(),
)));
state.update_with(Cow::Owned(BrowserAction::NavigationPush(
ScreenName::Search,
)));
assert_eq!(state.current_screen(), &ScreenName::Search);
assert_eq!(state.count(), 3);
let events = state.update_with(Cow::Owned(BrowserAction::NavigationPush(
new_screen.clone(),
)));
assert_eq!(state.current_screen(), &new_screen);
assert_eq!(state.count(), 2);
assert_eq!(events, vec![BrowserEvent::NavigationPoppedTo(new_screen)]);
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/state/playback_state.rs | src/app/state/playback_state.rs | use std::borrow::Cow;
use std::time::Instant;
use crate::app::models::*;
use crate::app::state::{AppAction, AppEvent, UpdatableState};
use crate::app::{BatchQuery, LazyRandomIndex, SongsSource};
#[derive(Debug)]
pub struct PlaybackState {
available_devices: Vec<ConnectDevice>,
current_device: Device,
// A mapping of indices for shuffled playback
index: LazyRandomIndex,
// The actual list like thing backing the currently playing tracks
songs: SongListModel,
list_position: Option<usize>,
seek_position: PositionMillis,
source: Option<SongsSource>,
repeat: RepeatMode,
is_playing: bool,
is_shuffled: bool,
}
// Most mutatings methods shouldn't be pub
// If they are, they probably are only used by the app state
impl PlaybackState {
pub fn songs(&self) -> &SongListModel {
&self.songs
}
pub fn is_playing(&self) -> bool {
self.is_playing && self.list_position.is_some()
}
pub fn is_shuffled(&self) -> bool {
self.is_shuffled
}
pub fn repeat_mode(&self) -> RepeatMode {
self.repeat
}
// Whatever batch of songs we would need to grab if we were to play the next track
pub fn next_query(&self) -> Option<BatchQuery> {
let next_index = self.next_index()?;
let next_index = if self.is_shuffled {
self.index.get(next_index)?
} else {
next_index
};
let batch = self.songs.needed_batch_for(next_index);
if let Some(batch) = batch {
let source = self.source.as_ref().cloned()?;
Some(BatchQuery { source, batch })
} else {
None
}
}
fn index(&self, i: usize) -> Option<SongDescription> {
let song = if self.is_shuffled {
self.songs.index(self.index.get(i)?)
} else {
self.songs.index(i)
};
Some(song?.into_description())
}
pub fn current_source(&self) -> Option<&SongsSource> {
self.source.as_ref()
}
pub fn current_song_index(&self) -> Option<usize> {
self.list_position
}
pub fn current_song_id(&self) -> Option<String> {
Some(self.index(self.list_position?)?.id)
}
pub fn current_song(&self) -> Option<SongDescription> {
self.index(self.list_position?)
}
fn next_id(&self) -> Option<String> {
self.next_index()
.and_then(|i| Some(self.songs().index(i)?.description().id.clone()))
}
fn clear(&mut self, source: Option<SongsSource>) -> SongListModelPending {
self.source = source;
self.index = Default::default();
self.list_position = None;
self.songs.clear()
}
// Replaces (!) the current playlist with the contents of a song batch
fn set_batch(&mut self, source: Option<SongsSource>, song_batch: SongBatch) -> bool {
let ok = self.clear(source).and(|s| s.add(song_batch)).commit();
self.index.resize(self.songs.len());
ok
}
fn add_batch(&mut self, song_batch: SongBatch) -> bool {
let ok = self.songs.add(song_batch).commit();
self.index.resize(self.songs.len());
ok
}
// Replaces (!) the current playlist with a bunch of songs (not batched, not expected to grow)
fn set_queue(&mut self, tracks: Vec<SongDescription>) {
self.clear(None).and(|s| s.append(tracks)).commit();
self.index.grow(self.songs.len());
}
pub fn queue(&mut self, tracks: Vec<SongDescription>) {
self.source = None;
self.songs.append(tracks).commit();
self.index.grow(self.songs.len());
}
pub fn dequeue(&mut self, ids: &[String]) {
let current_id = self.current_song_id();
self.songs.remove(ids).commit();
self.list_position = current_id.and_then(|id| self.songs.find_index(&id));
self.index.shrink(self.songs.len());
}
// Update the current playing track (identified by a position in the list) if we're swapping songs
fn swap_pos(&mut self, index: usize, other_index: usize) {
let len = self.songs.len();
self.list_position = self
.list_position
.map(|position| match position {
i if i == index => other_index,
i if i == other_index => index,
_ => position,
})
.map(|p| usize::min(p, len - 1))
}
pub fn move_down(&mut self, id: &str) -> Option<usize> {
let index = self.songs.find_index(id)?;
self.songs.move_down(index).commit();
self.swap_pos(index + 1, index);
Some(index)
}
pub fn move_up(&mut self, id: &str) -> Option<usize> {
let index = self.songs.find_index(id).filter(|&index| index > 0)?;
self.songs.move_up(index).commit();
self.swap_pos(index - 1, index);
Some(index)
}
fn play(&mut self, id: &str) -> bool {
if self.current_song_id().map(|cur| cur == id).unwrap_or(false) {
return false;
}
let found_index = self.songs.find_index(id);
if let Some(index) = found_index {
// If shufflings songs, we make sure the track we just picked is the first to come up
if self.is_shuffled {
self.index.reset_picking_first(index);
self.play_index(0);
} else {
self.play_index(index);
}
true
} else {
false
}
}
fn stop(&mut self) {
self.list_position = None;
self.is_playing = false;
self.seek_position.set(0, false);
}
fn play_index(&mut self, index: usize) -> Option<String> {
self.is_playing = true;
self.list_position.replace(index);
self.seek_position.set(0, true);
self.index.next_until(index + 1);
self.current_song_id()
}
fn play_next(&mut self) -> Option<String> {
self.next_index().and_then(|i| {
self.seek_position.set(0, true);
self.play_index(i)
})
}
pub fn next_index(&self) -> Option<usize> {
let len = self.songs.len();
self.list_position.and_then(|p| match self.repeat {
RepeatMode::Song => Some(p),
RepeatMode::Playlist if len != 0 => Some((p + 1) % len),
RepeatMode::None => Some(p + 1).filter(|&i| i < len),
_ => None,
})
}
fn play_prev(&mut self) -> Option<String> {
self.prev_index().and_then(|i| {
// Only jump to the previous track if we aren't more than 2 seconds (2,000 ms) into the current track.
// Otherwise, seek to the start of the current track.
// (This replicates the behavior of official Spotify clients.)
if self.seek_position.current() <= 2000 {
self.seek_position.set(0, true);
self.play_index(i)
} else {
self.seek_position.set(0, true);
None
}
})
}
pub fn prev_index(&self) -> Option<usize> {
let len = self.songs.len();
self.list_position.and_then(|p| match self.repeat {
RepeatMode::Song => Some(p),
RepeatMode::Playlist if len != 0 => Some((if p == 0 { len } else { p }) - 1),
RepeatMode::None => Some(p).filter(|&i| i > 0).map(|i| i - 1),
_ => None,
})
}
fn toggle_play(&mut self) -> Option<bool> {
if self.list_position.is_some() {
self.is_playing = !self.is_playing;
match self.is_playing {
false => self.seek_position.pause(),
true => self.seek_position.resume(),
};
Some(self.is_playing)
} else {
None
}
}
fn set_shuffled(&mut self, shuffled: bool) {
self.is_shuffled = shuffled;
let old = self.list_position.replace(0).unwrap_or(0);
self.index.reset_picking_first(old);
}
pub fn available_devices(&self) -> &Vec<ConnectDevice> {
&self.available_devices
}
pub fn current_device(&self) -> &Device {
&self.current_device
}
}
impl Default for PlaybackState {
fn default() -> Self {
Self {
available_devices: vec![],
current_device: Device::Local,
index: LazyRandomIndex::default(),
songs: SongListModel::new(50),
list_position: None,
seek_position: PositionMillis::new(1.0),
source: None,
repeat: RepeatMode::None,
is_playing: false,
is_shuffled: false,
}
}
}
#[derive(Clone, Debug)]
pub enum PlaybackAction {
TogglePlay,
Play,
Pause,
Stop,
SetRepeatMode(RepeatMode),
SetShuffled(bool),
ToggleRepeat,
ToggleShuffle,
Seek(u32),
// I can't remember the diff betweek Seek and SyncSeek right now. Probably the source of the action
SyncSeek(u32),
Load(String),
LoadSongs(Vec<SongDescription>),
LoadPagedSongs(SongsSource, SongBatch),
SetVolume(f64),
Next,
Previous,
Preload,
Queue(Vec<SongDescription>),
Dequeue(String),
SwitchDevice(Device),
SetAvailableDevices(Vec<ConnectDevice>),
}
impl From<PlaybackAction> for AppAction {
fn from(playback_action: PlaybackAction) -> Self {
Self::PlaybackAction(playback_action)
}
}
#[derive(Clone, Debug)]
pub enum Device {
Local,
Connect(ConnectDevice),
}
#[derive(Clone, Debug)]
pub enum PlaybackEvent {
PlaybackPaused,
PlaybackResumed,
RepeatModeChanged(RepeatMode),
TrackSeeked(u32),
SeekSynced(u32),
VolumeSet(f64),
TrackChanged(String),
SourceChanged,
Preload(String),
ShuffleChanged(bool),
PlaylistChanged,
PlaybackStopped,
SwitchedDevice(Device),
AvailableDevicesChanged,
}
impl From<PlaybackEvent> for AppEvent {
fn from(playback_event: PlaybackEvent) -> Self {
Self::PlaybackEvent(playback_event)
}
}
impl UpdatableState for PlaybackState {
type Action = PlaybackAction;
type Event = PlaybackEvent;
// Main "reducer" :)
fn update_with(&mut self, action: Cow<Self::Action>) -> Vec<Self::Event> {
match action.into_owned() {
PlaybackAction::TogglePlay => {
if let Some(playing) = self.toggle_play() {
if playing {
vec![PlaybackEvent::PlaybackResumed]
} else {
vec![PlaybackEvent::PlaybackPaused]
}
} else {
vec![]
}
}
PlaybackAction::Play => {
if !self.is_playing() && self.toggle_play() == Some(true) {
vec![PlaybackEvent::PlaybackResumed]
} else {
vec![]
}
}
PlaybackAction::Pause => {
if self.is_playing() && self.toggle_play() == Some(false) {
vec![PlaybackEvent::PlaybackPaused]
} else {
vec![]
}
}
PlaybackAction::ToggleRepeat => {
self.repeat = match self.repeat {
RepeatMode::Song => RepeatMode::None,
RepeatMode::Playlist => RepeatMode::Song,
RepeatMode::None => RepeatMode::Playlist,
};
vec![PlaybackEvent::RepeatModeChanged(self.repeat)]
}
PlaybackAction::SetRepeatMode(mode) if self.repeat != mode => {
self.repeat = mode;
vec![PlaybackEvent::RepeatModeChanged(self.repeat)]
}
PlaybackAction::SetShuffled(shuffled) if self.is_shuffled != shuffled => {
self.set_shuffled(shuffled);
vec![PlaybackEvent::ShuffleChanged(shuffled)]
}
PlaybackAction::ToggleShuffle => {
self.set_shuffled(!self.is_shuffled);
vec![PlaybackEvent::ShuffleChanged(self.is_shuffled)]
}
PlaybackAction::Next => {
if let Some(id) = self.play_next() {
vec![
PlaybackEvent::TrackChanged(id),
PlaybackEvent::PlaybackResumed,
]
} else {
self.stop();
vec![PlaybackEvent::PlaybackStopped]
}
}
PlaybackAction::Stop => {
self.stop();
vec![PlaybackEvent::PlaybackStopped]
}
PlaybackAction::Previous => {
if let Some(id) = self.play_prev() {
vec![
PlaybackEvent::TrackChanged(id),
PlaybackEvent::PlaybackResumed,
]
} else {
vec![PlaybackEvent::TrackSeeked(0)]
}
}
PlaybackAction::Load(id) => {
if self.play(&id) {
vec![
PlaybackEvent::TrackChanged(id),
PlaybackEvent::PlaybackResumed,
]
} else {
vec![]
}
}
PlaybackAction::Preload => {
if let Some(id) = self.next_id() {
vec![PlaybackEvent::Preload(id)]
} else {
vec![]
}
}
PlaybackAction::LoadPagedSongs(source, batch)
if Some(&source) == self.source.as_ref() =>
{
if self.add_batch(batch) {
vec![PlaybackEvent::PlaylistChanged]
} else {
vec![]
}
}
PlaybackAction::LoadPagedSongs(source, batch)
if Some(&source) != self.source.as_ref() =>
{
debug!("new source: {:?}", &source);
self.set_batch(Some(source), batch);
vec![PlaybackEvent::PlaylistChanged, PlaybackEvent::SourceChanged]
}
PlaybackAction::LoadSongs(tracks) => {
self.set_queue(tracks);
vec![PlaybackEvent::PlaylistChanged, PlaybackEvent::SourceChanged]
}
PlaybackAction::Queue(tracks) => {
self.queue(tracks);
vec![PlaybackEvent::PlaylistChanged]
}
PlaybackAction::Dequeue(id) => {
self.dequeue(&[id]);
vec![PlaybackEvent::PlaylistChanged]
}
PlaybackAction::Seek(pos) => {
self.seek_position.set(pos as u64 * 1000, true);
vec![PlaybackEvent::TrackSeeked(pos)]
}
PlaybackAction::SyncSeek(pos) => {
self.seek_position.set(pos as u64 * 1000, true);
vec![PlaybackEvent::SeekSynced(pos)]
}
PlaybackAction::SetVolume(volume) => {
vec![PlaybackEvent::VolumeSet(volume)]
},
PlaybackAction::SetAvailableDevices(list) => {
self.available_devices = list;
vec![PlaybackEvent::AvailableDevicesChanged]
}
PlaybackAction::SwitchDevice(new_device) => {
self.current_device = new_device.clone();
vec![PlaybackEvent::SwitchedDevice(new_device)]
}
_ => vec![],
}
}
}
// A struct to keep track of the playback position
// Caller must call pause/play at the right time
#[derive(Debug)]
struct PositionMillis {
// Last recorded position in the track (in milliseconds)
last_known_position: u64,
// Last time we resumed playback
last_resume_instant: Option<Instant>,
// Playback rate (1)
rate: f32,
}
impl PositionMillis {
fn new(rate: f32) -> Self {
Self {
last_known_position: 0,
last_resume_instant: None,
rate,
}
}
// Read the current pos by adding elapsed time since the last time we resumed playback to the last know position
fn current(&self) -> u64 {
let current_progress = self.last_resume_instant.map(|ri| {
let elapsed = ri.elapsed().as_millis() as f32;
let real_elapsed = self.rate * elapsed;
real_elapsed.ceil() as u64
});
self.last_known_position + current_progress.unwrap_or(0)
}
fn set(&mut self, position: u64, playing: bool) {
self.last_known_position = position;
self.last_resume_instant = if playing { Some(Instant::now()) } else { None }
}
fn pause(&mut self) {
self.last_known_position = self.current();
self.last_resume_instant = None;
}
fn resume(&mut self) {
self.last_resume_instant = Some(Instant::now());
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::app::models::AlbumRef;
fn song(id: &str) -> SongDescription {
SongDescription {
id: id.to_string(),
uri: "".to_string(),
title: "Title".to_string(),
artists: vec![],
album: AlbumRef {
id: "".to_string(),
name: "".to_string(),
},
duration: 1000,
art: None,
track_number: None,
}
}
impl PlaybackState {
fn current_position(&self) -> Option<usize> {
self.list_position
}
fn prev_id(&self) -> Option<String> {
self.prev_index()
.and_then(|i| Some(self.songs().index(i)?.description().id.clone()))
}
fn song_ids(&self) -> Vec<String> {
self.songs()
.collect()
.iter()
.map(|s| s.id.clone())
.collect()
}
}
#[test]
fn test_initial_state() {
let state = PlaybackState::default();
assert!(!state.is_playing());
assert!(!state.is_shuffled());
assert!(state.current_song().is_none());
assert!(state.prev_index().is_none());
assert!(state.next_index().is_none());
}
#[test]
fn test_play_one() {
let mut state = PlaybackState::default();
state.queue(vec![song("foo")]);
state.play("foo");
assert!(state.is_playing());
assert_eq!(state.current_song_id(), Some("foo".to_string()));
assert!(state.prev_index().is_none());
assert!(state.next_index().is_none());
state.toggle_play();
assert!(!state.is_playing());
}
#[test]
fn test_queue() {
let mut state = PlaybackState::default();
state.queue(vec![song("1"), song("2"), song("3")]);
assert_eq!(state.songs().len(), 3);
state.play("2");
state.queue(vec![song("4")]);
assert_eq!(state.songs().len(), 4);
}
#[test]
fn test_play_multiple() {
let mut state = PlaybackState::default();
state.queue(vec![song("1"), song("2"), song("3")]);
assert_eq!(state.songs().len(), 3);
state.play("2");
assert!(state.is_playing());
assert_eq!(state.current_position(), Some(1));
assert_eq!(state.prev_id(), Some("1".to_string()));
assert_eq!(state.current_song_id(), Some("2".to_string()));
assert_eq!(state.next_id(), Some("3".to_string()));
state.toggle_play();
assert!(!state.is_playing());
state.play_next();
assert!(state.is_playing());
assert_eq!(state.current_position(), Some(2));
assert_eq!(state.prev_id(), Some("2".to_string()));
assert_eq!(state.current_song_id(), Some("3".to_string()));
assert!(state.next_index().is_none());
state.play_next();
assert!(state.is_playing());
assert_eq!(state.current_position(), Some(2));
assert_eq!(state.current_song_id(), Some("3".to_string()));
state.play_prev();
state.play_prev();
assert!(state.is_playing());
assert_eq!(state.current_position(), Some(0));
assert!(state.prev_index().is_none());
assert_eq!(state.current_song_id(), Some("1".to_string()));
assert_eq!(state.next_id(), Some("2".to_string()));
state.play_prev();
assert!(state.is_playing());
assert_eq!(state.current_position(), Some(0));
assert_eq!(state.current_song_id(), Some("1".to_string()));
}
#[test]
fn test_shuffle() {
let mut state = PlaybackState::default();
state.queue(vec![song("1"), song("2"), song("3"), song("4")]);
assert_eq!(state.songs().len(), 4);
state.play("2");
assert_eq!(state.current_position(), Some(1));
state.set_shuffled(true);
assert!(state.is_shuffled());
assert_eq!(state.current_position(), Some(0));
state.play_next();
assert_eq!(state.current_position(), Some(1));
state.set_shuffled(false);
assert!(!state.is_shuffled());
let ids = state.song_ids();
assert_eq!(
ids,
vec![
"1".to_string(),
"2".to_string(),
"3".to_string(),
"4".to_string()
]
);
}
#[test]
fn test_shuffle_queue() {
let mut state = PlaybackState::default();
state.queue(vec![song("1"), song("2"), song("3")]);
state.set_shuffled(true);
assert!(state.is_shuffled());
state.queue(vec![song("4")]);
state.set_shuffled(false);
assert!(!state.is_shuffled());
let ids = state.song_ids();
assert_eq!(
ids,
vec![
"1".to_string(),
"2".to_string(),
"3".to_string(),
"4".to_string()
]
);
}
#[test]
fn test_move() {
let mut state = PlaybackState::default();
state.queue(vec![song("1"), song("2"), song("3")]);
state.play("2");
assert!(state.is_playing());
state.move_down("1");
assert_eq!(state.current_song_id(), Some("2".to_string()));
let ids = state.song_ids();
assert_eq!(ids, vec!["2".to_string(), "1".to_string(), "3".to_string()]);
state.move_down("2");
state.move_down("2");
assert_eq!(state.current_song_id(), Some("2".to_string()));
let ids = state.song_ids();
assert_eq!(ids, vec!["1".to_string(), "3".to_string(), "2".to_string()]);
state.move_down("2");
assert_eq!(state.current_song_id(), Some("2".to_string()));
let ids = state.song_ids();
assert_eq!(ids, vec!["1".to_string(), "3".to_string(), "2".to_string()]);
state.move_up("2");
assert_eq!(state.current_song_id(), Some("2".to_string()));
let ids = state.song_ids();
assert_eq!(ids, vec!["1".to_string(), "2".to_string(), "3".to_string()]);
}
#[test]
fn test_dequeue_last() {
let mut state = PlaybackState::default();
state.queue(vec![song("1"), song("2"), song("3")]);
state.play("3");
assert!(state.is_playing());
state.dequeue(&["3".to_string()]);
assert_eq!(state.current_song_id(), None);
}
#[test]
fn test_dequeue_a_few_songs() {
let mut state = PlaybackState::default();
state.queue(vec![
song("1"),
song("2"),
song("3"),
song("4"),
song("5"),
song("6"),
]);
state.play("5");
assert!(state.is_playing());
state.dequeue(&["1".to_string(), "2".to_string(), "3".to_string()]);
assert_eq!(state.current_song_id(), Some("5".to_string()));
}
#[test]
fn test_dequeue_all() {
let mut state = PlaybackState::default();
state.queue(vec![song("3")]);
state.play("3");
assert!(state.is_playing());
state.dequeue(&["3".to_string()]);
assert_eq!(state.current_song_id(), None);
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/state/settings_state.rs | src/app/state/settings_state.rs | use crate::{
app::state::{AppAction, AppEvent, UpdatableState},
settings::RiffSettings,
};
#[derive(Clone, Debug)]
pub enum SettingsAction {
ChangeSettings,
}
impl From<SettingsAction> for AppAction {
fn from(settings_action: SettingsAction) -> Self {
Self::SettingsAction(settings_action)
}
}
#[derive(Clone, Debug)]
pub enum SettingsEvent {
PlayerSettingsChanged,
}
impl From<SettingsEvent> for AppEvent {
fn from(settings_event: SettingsEvent) -> Self {
Self::SettingsEvent(settings_event)
}
}
#[derive(Default)]
pub struct SettingsState {
// Probably shouldn't be stored, the source of truth is GSettings anyway
pub settings: RiffSettings,
}
impl UpdatableState for SettingsState {
type Action = SettingsAction;
type Event = AppEvent;
fn update_with(&mut self, action: std::borrow::Cow<Self::Action>) -> Vec<Self::Event> {
match action.into_owned() {
SettingsAction::ChangeSettings => {
let old_settings = &self.settings;
let new_settings = RiffSettings::new_from_gsettings().unwrap_or_default();
let player_settings_changed =
new_settings.player_settings != old_settings.player_settings;
self.settings = new_settings;
if player_settings_changed {
vec![SettingsEvent::PlayerSettingsChanged.into()]
} else {
vec![]
}
}
}
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/state/app_state.rs | src/app/state/app_state.rs | use std::borrow::Cow;
use crate::app::models::{PlaylistDescription, PlaylistSummary};
use crate::app::state::{
browser_state::{BrowserAction, BrowserEvent, BrowserState},
login_state::{LoginAction, LoginEvent, LoginState},
playback_state::{PlaybackAction, PlaybackEvent, PlaybackState},
selection_state::{SelectionAction, SelectionContext, SelectionEvent, SelectionState},
settings_state::{SettingsAction, SettingsEvent, SettingsState},
ScreenName, UpdatableState,
};
// It's a big one...
// All possible actions!
// It's probably a VERY poor way to layout such a big enum, just look at the size, I'm so sorry I am not a sytems programmer
// Could use a few more Boxes maybe?
#[derive(Clone, Debug)]
pub enum AppAction {
// With sub categories :)
PlaybackAction(PlaybackAction),
BrowserAction(BrowserAction),
SelectionAction(SelectionAction),
LoginAction(LoginAction),
SettingsAction(SettingsAction),
Start,
Raise,
ShowNotification(String),
ViewNowPlaying,
// Cross-state actions
QueueSelection,
DequeueSelection,
MoveUpSelection,
MoveDownSelection,
SaveSelection,
UnsaveSelection,
EnableSelection(SelectionContext),
CancelSelection,
CreatePlaylist(PlaylistDescription),
UpdatePlaylistName(PlaylistSummary),
}
// Not actual actions, just neat wrappers
impl AppAction {
// An action to open a Spotify URI
#[allow(non_snake_case)]
pub fn OpenURI(uri: String) -> Option<Self> {
debug!("parsing {}", &uri);
let mut parts = uri.split(':');
if parts.next()? != "spotify" {
return None;
}
// Might start with /// because of https://gitlab.gnome.org/GNOME/glib/-/issues/1886/
let action = parts
.next()?
.strip_prefix("///")
.filter(|p| !p.is_empty())?;
let data = parts.next()?;
match action {
"album" => Some(Self::ViewAlbum(data.to_string())),
"artist" => Some(Self::ViewArtist(data.to_string())),
"playlist" => Some(Self::ViewPlaylist(data.to_string())),
"user" => Some(Self::ViewUser(data.to_string())),
_ => None,
}
}
#[allow(non_snake_case)]
pub fn ViewAlbum(id: String) -> Self {
BrowserAction::NavigationPush(ScreenName::AlbumDetails(id)).into()
}
#[allow(non_snake_case)]
pub fn ViewArtist(id: String) -> Self {
BrowserAction::NavigationPush(ScreenName::Artist(id)).into()
}
#[allow(non_snake_case)]
pub fn ViewPlaylist(id: String) -> Self {
BrowserAction::NavigationPush(ScreenName::PlaylistDetails(id)).into()
}
#[allow(non_snake_case)]
pub fn ViewUser(id: String) -> Self {
BrowserAction::NavigationPush(ScreenName::User(id)).into()
}
#[allow(non_snake_case)]
pub fn ViewSearch() -> Self {
BrowserAction::NavigationPush(ScreenName::Search).into()
}
}
// Actions mutate stuff, and we know what changed thanks to these events
#[derive(Clone, Debug)]
pub enum AppEvent {
// Also subcategorized
PlaybackEvent(PlaybackEvent),
BrowserEvent(BrowserEvent),
SelectionEvent(SelectionEvent),
LoginEvent(LoginEvent),
Started,
Raised,
NotificationShown(String),
PlaylistCreatedNotificationShown(String),
NowPlayingShown,
SettingsEvent(SettingsEvent),
}
// The actual state, split five-ways
pub struct AppState {
started: bool,
pub playback: PlaybackState,
pub browser: BrowserState,
pub selection: SelectionState,
pub logged_user: LoginState,
pub settings: SettingsState,
}
impl AppState {
pub fn new() -> Self {
Self {
started: false,
playback: Default::default(),
browser: BrowserState::new(),
selection: Default::default(),
logged_user: Default::default(),
settings: Default::default(),
}
}
pub fn update_state(&mut self, message: AppAction) -> Vec<AppEvent> {
match message {
AppAction::Start if !self.started => {
self.started = true;
vec![AppEvent::Started]
}
// Couple of actions that don't mutate the state (not intested in keeping track of what they change)
// they're here just to have a consistent way of doing things (always an Action)
AppAction::ShowNotification(c) => vec![AppEvent::NotificationShown(c)],
AppAction::ViewNowPlaying => vec![AppEvent::NowPlayingShown],
AppAction::Raise => vec![AppEvent::Raised],
// Cross-state actions: multiple "substates" are affected by these actions, that's why they're handled here
// Might need some clean-up
AppAction::QueueSelection => {
self.playback.queue(self.selection.take_selection());
vec![
SelectionEvent::SelectionModeChanged(false).into(),
PlaybackEvent::PlaylistChanged.into(),
]
}
AppAction::DequeueSelection => {
let tracks: Vec<String> = self
.selection
.take_selection()
.into_iter()
.map(|s| s.id)
.collect();
self.playback.dequeue(&tracks);
vec![
SelectionEvent::SelectionModeChanged(false).into(),
PlaybackEvent::PlaylistChanged.into(),
]
}
AppAction::MoveDownSelection => {
let mut selection = self.selection.peek_selection();
let playback = &mut self.playback;
selection
.next()
.and_then(|song| playback.move_down(&song.id))
.map(|_| vec![PlaybackEvent::PlaylistChanged.into()])
.unwrap_or_default()
}
AppAction::MoveUpSelection => {
let mut selection = self.selection.peek_selection();
let playback = &mut self.playback;
selection
.next()
.and_then(|song| playback.move_up(&song.id))
.map(|_| vec![PlaybackEvent::PlaylistChanged.into()])
.unwrap_or_default()
}
AppAction::SaveSelection => {
let tracks = self.selection.take_selection();
let mut events: Vec<AppEvent> = forward_action(
BrowserAction::SaveTracks(tracks),
self.browser.home_state_mut().unwrap(),
);
events.push(SelectionEvent::SelectionModeChanged(false).into());
events
}
AppAction::UnsaveSelection => {
let tracks: Vec<String> = self
.selection
.take_selection()
.into_iter()
.map(|s| s.id)
.collect();
let mut events: Vec<AppEvent> = forward_action(
BrowserAction::RemoveSavedTracks(tracks),
self.browser.home_state_mut().unwrap(),
);
events.push(SelectionEvent::SelectionModeChanged(false).into());
events
}
AppAction::EnableSelection(context) => {
if let Some(active) = self.selection.set_mode(Some(context)) {
vec![SelectionEvent::SelectionModeChanged(active).into()]
} else {
vec![]
}
}
AppAction::CancelSelection => {
if let Some(active) = self.selection.set_mode(None) {
vec![SelectionEvent::SelectionModeChanged(active).into()]
} else {
vec![]
}
}
AppAction::CreatePlaylist(playlist) => {
let id = playlist.id.clone();
let mut events = forward_action(
LoginAction::PrependUserPlaylist(vec![playlist.clone().into()]),
&mut self.logged_user,
);
let mut more_events = forward_action(
BrowserAction::PrependPlaylistsContent(vec![playlist]),
&mut self.browser,
);
events.append(&mut more_events);
events.push(AppEvent::PlaylistCreatedNotificationShown(id));
events
}
AppAction::UpdatePlaylistName(s) => {
let mut events = forward_action(
LoginAction::UpdateUserPlaylist(s.clone()),
&mut self.logged_user,
);
let mut more_events =
forward_action(BrowserAction::UpdatePlaylistName(s), &mut self.browser);
events.append(&mut more_events);
events
}
// As for all other actions, we forward them to the substates :)
AppAction::PlaybackAction(a) => forward_action(a, &mut self.playback),
AppAction::BrowserAction(a) => forward_action(a, &mut self.browser),
AppAction::SelectionAction(a) => forward_action(a, &mut self.selection),
AppAction::LoginAction(a) => forward_action(a, &mut self.logged_user),
AppAction::SettingsAction(a) => forward_action(a, &mut self.settings),
_ => vec![],
}
}
}
fn forward_action<A, E>(
action: A,
target: &mut impl UpdatableState<Action = A, Event = E>,
) -> Vec<AppEvent>
where
A: Clone,
E: Into<AppEvent>,
{
target
.update_with(Cow::Owned(action))
.into_iter()
.map(|e| e.into())
.collect()
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/state/mod.rs | src/app/state/mod.rs | mod app_model;
mod app_state;
mod browser_state;
mod login_state;
mod pagination;
mod playback_state;
mod screen_states;
mod selection_state;
mod settings_state;
pub use app_model::AppModel;
pub use app_state::*;
pub use browser_state::*;
pub use login_state::*;
pub use playback_state::*;
pub use screen_states::*;
pub use selection_state::*;
pub use settings_state::*;
pub trait UpdatableState {
type Action: Clone;
type Event;
fn update_with(&mut self, action: std::borrow::Cow<Self::Action>) -> Vec<Self::Event>;
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/state/pagination.rs | src/app/state/pagination.rs | // A structure for batched queries that I introduced before proper batch management
// Still used to load album lists for instance
// Doesn't know how many elements exist in total ahead of time
#[derive(Clone, Debug)]
pub struct Pagination<T>
where
T: Clone,
{
pub data: T,
// The next offset (of things to load) is set to None whenever we get less than we asked for
// as it probably means we've reached the end of some list
pub next_offset: Option<usize>,
pub batch_size: usize,
}
impl<T> Pagination<T>
where
T: Clone,
{
pub fn new(data: T, batch_size: usize) -> Self {
Self {
data,
next_offset: Some(0),
batch_size,
}
}
pub fn reset_count(&mut self, new_length: usize) {
self.next_offset = if new_length >= self.batch_size {
Some(self.batch_size)
} else {
None
}
}
pub fn set_loaded_count(&mut self, loaded_count: usize) {
if let Some(offset) = self.next_offset.take() {
self.next_offset = if loaded_count >= self.batch_size {
Some(offset + self.batch_size)
} else {
None
}
}
}
// If we remove elements from paginated data without refetching from the source,
// we have to adjust the next offset to load
pub fn decrement(&mut self) {
if let Some(offset) = self.next_offset.take() {
self.next_offset = Some(offset - 1);
}
}
// Same idea as decrement
pub fn increment(&mut self) {
if let Some(offset) = self.next_offset.take() {
self.next_offset = Some(offset + 1);
}
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/state/app_model.rs | src/app/state/app_model.rs | use crate::api::SpotifyApiClient;
use crate::app::{state::*, BatchLoader};
use ref_filter_map::*;
use std::cell::{Ref, RefCell};
use std::sync::Arc;
pub struct AppServices {
pub spotify_api: Arc<dyn SpotifyApiClient + Send + Sync>,
pub batch_loader: BatchLoader,
}
// Two purposes: give access to some services to users of the AppModel (shared)
// and give a read only view of the state
pub struct AppModel {
state: RefCell<AppState>,
services: AppServices,
}
impl AppModel {
pub fn new(state: AppState, spotify_api: Arc<dyn SpotifyApiClient + Send + Sync>) -> Self {
let services = AppServices {
batch_loader: BatchLoader::new(Arc::clone(&spotify_api)),
spotify_api,
};
let state = RefCell::new(state);
Self { state, services }
}
pub fn get_spotify(&self) -> Arc<dyn SpotifyApiClient + Send + Sync> {
Arc::clone(&self.services.spotify_api)
}
pub fn get_batch_loader(&self) -> BatchLoader {
self.services.batch_loader.clone()
}
// Read only access to the state!
pub fn get_state(&self) -> Ref<'_, AppState> {
self.state.borrow()
}
// Convenience...
pub fn map_state<T: 'static, F: FnOnce(&AppState) -> &T>(&self, map: F) -> Ref<'_, T> {
Ref::map(self.state.borrow(), map)
}
// Convenience...
pub fn map_state_opt<T: 'static, F: FnOnce(&AppState) -> Option<&T>>(
&self,
map: F,
) -> Option<Ref<'_, T>> {
ref_filter_map(self.state.borrow(), map)
}
pub fn update_state(&self, action: AppAction) -> Vec<AppEvent> {
// And this is the only mutable borrow of our state!
let mut state = self.state.borrow_mut();
state.update_state(action)
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/state/screen_states.rs | src/app/state/screen_states.rs | use std::borrow::Cow;
use std::cmp::PartialEq;
use super::{pagination::Pagination, BrowserAction, BrowserEvent, UpdatableState};
use crate::app::models::*;
use crate::app::ListStore;
#[derive(Clone, Debug)]
pub enum ScreenName {
Home,
AlbumDetails(String),
Search,
Artist(String),
PlaylistDetails(String),
User(String),
}
impl ScreenName {
pub fn identifier(&self) -> Cow<str> {
match self {
Self::Home => Cow::Borrowed("home"),
Self::AlbumDetails(s) => Cow::Owned(format!("album_{s}")),
Self::Search => Cow::Borrowed("search"),
Self::Artist(s) => Cow::Owned(format!("artist_{s}")),
Self::PlaylistDetails(s) => Cow::Owned(format!("playlist_{s}")),
Self::User(s) => Cow::Owned(format!("user_{s}")),
}
}
}
impl PartialEq for ScreenName {
fn eq(&self, other: &Self) -> bool {
self.identifier() == other.identifier()
}
}
impl Eq for ScreenName {}
// ALBUM details
pub struct DetailsState {
pub id: String,
pub name: ScreenName,
pub content: Option<AlbumFullDescription>,
// Read the songs from here, not content (won't get more than the initial batch of songs)
pub songs: SongListModel,
}
impl DetailsState {
pub fn new(id: String) -> Self {
Self {
id: id.clone(),
name: ScreenName::AlbumDetails(id),
content: None,
songs: SongListModel::new(50),
}
}
}
impl UpdatableState for DetailsState {
type Action = BrowserAction;
type Event = BrowserEvent;
fn update_with(&mut self, action: Cow<Self::Action>) -> Vec<Self::Event> {
match action.as_ref() {
BrowserAction::SetAlbumDetails(album) if album.description.id == self.id => {
let AlbumDescription { id, songs, .. } = album.description.clone();
self.songs.add(songs).commit();
self.content = Some(*album.clone());
vec![BrowserEvent::AlbumDetailsLoaded(id)]
}
BrowserAction::AppendAlbumTracks(id, batch) if id == &self.id => {
self.songs.add(*batch.clone()).commit();
vec![BrowserEvent::AlbumTracksAppended(id.clone())]
}
BrowserAction::SaveAlbum(album) if album.id == self.id => {
let id = album.id.clone();
if let Some(album) = self.content.as_mut() {
album.description.is_liked = true;
vec![BrowserEvent::AlbumSaved(id)]
} else {
vec![]
}
}
BrowserAction::UnsaveAlbum(id) if id == &self.id => {
if let Some(album) = self.content.as_mut() {
album.description.is_liked = false;
vec![BrowserEvent::AlbumUnsaved(id.clone())]
} else {
vec![]
}
}
_ => vec![],
}
}
}
pub struct PlaylistDetailsState {
pub id: String,
pub name: ScreenName,
pub playlist: Option<PlaylistDescription>,
// Read the songs from here, not content (won't get more than the initial batch of songs)
pub songs: SongListModel,
}
impl PlaylistDetailsState {
pub fn new(id: String) -> Self {
Self {
id: id.clone(),
name: ScreenName::PlaylistDetails(id),
playlist: None,
songs: SongListModel::new(100),
}
}
}
impl UpdatableState for PlaylistDetailsState {
type Action = BrowserAction;
type Event = BrowserEvent;
fn update_with(&mut self, action: Cow<Self::Action>) -> Vec<Self::Event> {
match action.as_ref() {
BrowserAction::SetPlaylistDetails(playlist, song_batch) if playlist.id == self.id => {
let PlaylistDescription { id, .. } = *playlist.clone();
self.songs.add(*song_batch.clone()).commit();
self.playlist = Some(*playlist.clone());
vec![BrowserEvent::PlaylistDetailsLoaded(id)]
}
BrowserAction::UpdatePlaylistName(PlaylistSummary { id, title }) if id == &self.id => {
if let Some(p) = self.playlist.as_mut() {
p.title = title.clone();
}
vec![BrowserEvent::PlaylistDetailsLoaded(self.id.clone())]
}
BrowserAction::AppendPlaylistTracks(id, song_batch) if id == &self.id => {
self.songs.add(*song_batch.clone()).commit();
vec![BrowserEvent::PlaylistTracksAppended(id.clone())]
}
BrowserAction::RemoveTracksFromPlaylist(id, uris) if id == &self.id => {
self.songs.remove(&uris[..]).commit();
vec![BrowserEvent::PlaylistTracksRemoved(self.id.clone())]
}
_ => vec![],
}
}
}
pub struct ArtistState {
pub id: String,
pub name: ScreenName,
pub artist: Option<String>,
pub next_page: Pagination<String>,
pub albums: ListStore<AlbumModel>,
pub top_tracks: SongListModel,
}
impl ArtistState {
pub fn new(id: String) -> Self {
Self {
id: id.clone(),
name: ScreenName::Artist(id.clone()),
artist: None,
next_page: Pagination::new(id, 20),
albums: ListStore::new(),
top_tracks: SongListModel::new(10),
}
}
}
impl UpdatableState for ArtistState {
type Action = BrowserAction;
type Event = BrowserEvent;
fn update_with(&mut self, action: Cow<Self::Action>) -> Vec<Self::Event> {
match action.as_ref() {
BrowserAction::SetArtistDetails(details) if details.id == self.id => {
let ArtistDescription {
id,
name,
albums,
mut top_tracks,
} = *details.clone();
self.artist = Some(name);
self.albums
.replace_all(albums.into_iter().map(|a| a.into()));
self.next_page.reset_count(self.albums.len());
top_tracks.truncate(5);
self.top_tracks.append(top_tracks).commit();
vec![BrowserEvent::ArtistDetailsUpdated(id)]
}
BrowserAction::AppendArtistReleases(id, albums) if id == &self.id => {
self.next_page.set_loaded_count(albums.len());
self.albums.extend(albums.iter().map(|a| a.into()));
vec![BrowserEvent::ArtistDetailsUpdated(self.id.clone())]
}
_ => vec![],
}
}
}
// The "home" represents screens visible initially (saved albums, saved playlists, saved tracks)
pub struct HomeState {
pub name: ScreenName,
pub visible_page: &'static str,
pub next_albums_page: Pagination<()>,
pub albums: ListStore<AlbumModel>,
pub next_playlists_page: Pagination<()>,
pub playlists: ListStore<AlbumModel>,
pub saved_tracks: SongListModel,
}
impl Default for HomeState {
fn default() -> Self {
Self {
name: ScreenName::Home,
visible_page: "library",
next_albums_page: Pagination::new((), 30),
albums: ListStore::new(),
next_playlists_page: Pagination::new((), 30),
playlists: ListStore::new(),
saved_tracks: SongListModel::new(50),
}
}
}
impl UpdatableState for HomeState {
type Action = BrowserAction;
type Event = BrowserEvent;
fn update_with(&mut self, action: Cow<Self::Action>) -> Vec<Self::Event> {
match action.as_ref() {
BrowserAction::SetHomeVisiblePage(page) => {
self.visible_page = *page;
vec![BrowserEvent::HomeVisiblePageChanged(page)]
}
BrowserAction::SetLibraryContent(content) => {
if !self.albums.eq(content, |a, b| a.uri() == b.id) {
self.albums.replace_all(content.iter().map(|a| a.into()));
self.next_albums_page.reset_count(self.albums.len());
vec![BrowserEvent::LibraryUpdated]
} else {
vec![]
}
}
BrowserAction::PrependPlaylistsContent(content) => {
self.playlists.prepend(content.iter().map(|a| a.into()));
vec![BrowserEvent::SavedPlaylistsUpdated]
}
BrowserAction::AppendLibraryContent(content) => {
self.next_albums_page.set_loaded_count(content.len());
self.albums.extend(content.iter().map(|a| a.into()));
vec![BrowserEvent::LibraryUpdated]
}
BrowserAction::SaveAlbum(album) => {
let album_id = album.id.clone();
let already_present = self.albums.iter().any(|a| a.uri() == album_id);
if already_present {
vec![]
} else {
self.albums.insert(0, (*album.clone()).into());
self.next_albums_page.increment();
vec![BrowserEvent::LibraryUpdated]
}
}
BrowserAction::UnsaveAlbum(id) => {
let position = self.albums.iter().position(|a| a.uri() == *id);
if let Some(position) = position {
self.albums.remove(position as u32);
self.next_albums_page.decrement();
vec![BrowserEvent::LibraryUpdated]
} else {
vec![]
}
}
BrowserAction::SetPlaylistsContent(content) => {
if !self.playlists.eq(content, |a, b| a.uri() == b.id) {
self.playlists.replace_all(content.iter().map(|a| a.into()));
self.next_playlists_page.reset_count(self.playlists.len());
vec![BrowserEvent::SavedPlaylistsUpdated]
} else {
vec![]
}
}
BrowserAction::AppendPlaylistsContent(content) => {
self.next_playlists_page.set_loaded_count(content.len());
self.playlists.extend(content.iter().map(|p| p.into()));
vec![BrowserEvent::SavedPlaylistsUpdated]
}
BrowserAction::UpdatePlaylistName(PlaylistSummary { id, title }) => {
if let Some(p) = self.playlists.iter().find(|p| &p.uri() == id) {
p.set_album(title.to_owned());
}
vec![BrowserEvent::SavedPlaylistsUpdated]
}
BrowserAction::AppendSavedTracks(song_batch) => {
if self.saved_tracks.add(*song_batch.clone()).commit() {
vec![BrowserEvent::SavedTracksUpdated]
} else {
vec![]
}
}
BrowserAction::SetSavedTracks(song_batch) => {
let song_batch = *song_batch.clone();
if self
.saved_tracks
.clear()
.and(|s| s.add(song_batch))
.commit()
{
vec![BrowserEvent::SavedTracksUpdated]
} else {
vec![]
}
}
BrowserAction::SaveTracks(tracks) => {
self.saved_tracks.prepend(tracks.clone()).commit();
vec![BrowserEvent::SavedTracksUpdated]
}
BrowserAction::RemoveSavedTracks(tracks) => {
self.saved_tracks.remove(&tracks[..]).commit();
vec![BrowserEvent::SavedTracksUpdated]
}
_ => vec![],
}
}
}
pub struct SearchState {
pub name: ScreenName,
pub query: String,
pub album_results: Vec<AlbumDescription>,
pub artist_results: Vec<ArtistSummary>,
}
impl Default for SearchState {
fn default() -> Self {
Self {
name: ScreenName::Search,
query: "".to_owned(),
album_results: vec![],
artist_results: vec![],
}
}
}
impl UpdatableState for SearchState {
type Action = BrowserAction;
type Event = BrowserEvent;
fn update_with(&mut self, action: Cow<Self::Action>) -> Vec<Self::Event> {
match action.as_ref() {
BrowserAction::Search(query) if query != &self.query => {
self.query = query.clone();
vec![BrowserEvent::SearchUpdated]
}
BrowserAction::SetSearchResults(results) => {
self.album_results = results.albums.clone();
self.artist_results = results.artists.clone();
vec![BrowserEvent::SearchResultsUpdated]
}
_ => vec![],
}
}
}
// Screen when we click on the name of a playlist owner
pub struct UserState {
pub id: String,
pub name: ScreenName,
pub user: Option<String>,
pub next_page: Pagination<String>,
pub playlists: ListStore<AlbumModel>,
}
impl UserState {
pub fn new(id: String) -> Self {
Self {
id: id.clone(),
name: ScreenName::User(id.clone()),
user: None,
next_page: Pagination::new(id, 30),
playlists: ListStore::new(),
}
}
}
impl UpdatableState for UserState {
type Action = BrowserAction;
type Event = BrowserEvent;
fn update_with(&mut self, action: Cow<Self::Action>) -> Vec<Self::Event> {
match action.as_ref() {
BrowserAction::SetUserDetails(user) if user.id == self.id => {
let UserDescription {
id,
name,
playlists,
} = *user.clone();
self.user = Some(name);
self.playlists
.replace_all(playlists.iter().map(|p| p.into()));
self.next_page.reset_count(self.playlists.len());
vec![BrowserEvent::UserDetailsUpdated(id)]
}
BrowserAction::AppendUserPlaylists(id, playlists) if id == &self.id => {
self.next_page.set_loaded_count(playlists.len());
self.playlists.extend(playlists.iter().map(|p| p.into()));
vec![BrowserEvent::UserDetailsUpdated(self.id.clone())]
}
_ => vec![],
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_next_page_no_next() {
let mut artist_state = ArtistState::new("id".to_owned());
artist_state.update_with(Cow::Owned(BrowserAction::SetArtistDetails(Box::new(
ArtistDescription {
id: "id".to_owned(),
name: "Foo".to_owned(),
albums: vec![],
top_tracks: vec![],
},
))));
let next = artist_state.next_page;
assert_eq!(None, next.next_offset);
}
#[test]
fn test_next_page_more() {
let fake_album = AlbumDescription {
id: "".to_owned(),
title: "".to_owned(),
artists: vec![],
release_date: Some("1970-01-01".to_owned()),
art: Some("".to_owned()),
songs: SongBatch::empty(),
is_liked: false,
};
let id = "id".to_string();
let mut artist_state = ArtistState::new(id.clone());
artist_state.update_with(Cow::Owned(BrowserAction::SetArtistDetails(Box::new(
ArtistDescription {
id: id.clone(),
name: "Foo".to_owned(),
albums: (0..20).map(|_| fake_album.clone()).collect(),
top_tracks: vec![],
},
))));
let next = &artist_state.next_page;
assert_eq!(Some(20), next.next_offset);
artist_state.update_with(Cow::Owned(BrowserAction::AppendArtistReleases(
id.clone(),
vec![],
)));
let next = &artist_state.next_page;
assert_eq!(None, next.next_offset);
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/utils.rs | src/app/components/utils.rs | use gtk::prelude::*;
use std::cell::Cell;
use std::rc::Rc;
use std::time::Duration;
#[derive(Clone)]
pub struct Clock {
interval_ms: u32,
source: Rc<Cell<Option<glib::source::SourceId>>>,
}
impl Default for Clock {
fn default() -> Self {
Self::new(1000)
}
}
impl std::fmt::Debug for Clock {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Clock")
.field("interval_ms", &self.interval_ms)
.finish()
}
}
impl Clock {
pub fn new(interval_ms: u32) -> Self {
Self {
interval_ms,
source: Rc::new(Cell::new(None)),
}
}
pub fn start<F: Fn() + 'static>(&self, tick: F) {
let new_source = Some(glib::timeout_add_local(
Duration::from_millis(self.interval_ms.into()),
move || {
tick();
glib::ControlFlow::Continue
},
));
if let Some(previous_source) = self.source.replace(new_source) {
previous_source.remove();
}
}
pub fn stop(&self) {
let new_source = None;
if let Some(previous_source) = self.source.replace(new_source) {
previous_source.remove();
}
}
}
#[derive(Clone)]
pub struct Debouncer(Rc<Cell<Option<glib::source::SourceId>>>);
impl Debouncer {
pub fn new() -> Self {
Self(Rc::new(Cell::new(None)))
}
pub fn debounce<F: Fn() + 'static>(&self, interval_ms: u32, f: F) {
let source_clone = Rc::downgrade(&self.0);
let new_source =
glib::timeout_add_local(Duration::from_millis(interval_ms.into()), move || {
f();
if let Some(cell) = source_clone.upgrade() {
cell.set(None);
}
glib::ControlFlow::Break
});
if let Some(previous_source) = self.0.replace(Some(new_source)) {
previous_source.remove();
}
}
}
pub struct Animator<EasingFn> {
progress: Rc<Cell<u16>>,
ease_fn: EasingFn,
}
pub type AnimatorDefault = Animator<fn(f64) -> f64>;
impl AnimatorDefault {
fn ease_in_out(x: f64) -> f64 {
match x {
x if x < 0.5 => 0.5 * 2f64.powf(20.0 * x - 10.0),
_ => 0.5 * (2.0 - 2f64.powf(-20.0 * x + 10.0)),
}
}
pub fn ease_in_out_animator() -> AnimatorDefault {
Animator {
progress: Rc::new(Cell::new(0)),
ease_fn: Self::ease_in_out,
}
}
}
impl<EasingFn> Animator<EasingFn>
where
EasingFn: 'static + Copy + Fn(f64) -> f64,
{
pub fn animate<F: Fn(f64) -> bool + 'static>(&self, steps: u16, f: F) {
self.progress.set(0);
let ease_fn = self.ease_fn;
let progress = Rc::downgrade(&self.progress);
glib::timeout_add_local(Duration::from_millis(16), move || {
let mut continue_ = false;
if let Some(progress) = progress.upgrade() {
let step = progress.get();
continue_ = step < steps;
if continue_ {
progress.set(step + 1);
let p = ease_fn(step as f64 / steps as f64);
continue_ = f(p);
}
}
if continue_ {
glib::ControlFlow::Continue
} else {
glib::ControlFlow::Break
}
});
}
}
pub fn ancestor<Current, Ancestor>(widget: &Current) -> Option<Ancestor>
where
Current: IsA<gtk::Widget>,
Ancestor: IsA<gtk::Widget>,
{
widget.parent().and_then(|p| {
p.clone()
.downcast::<Ancestor>()
.ok()
.or_else(|| ancestor(&p))
})
}
pub fn wrap_flowbox_item<
Model: IsA<glib::Object>,
Widget: IsA<gtk::Widget>,
F: Fn(&Model) -> Widget,
>(
item: &glib::Object,
f: F,
) -> gtk::Widget {
let item = item.downcast_ref::<Model>().unwrap();
let widget = f(item);
let child = gtk::FlowBoxChild::new();
child.set_child(Some(&widget));
child.upcast::<gtk::Widget>()
}
pub fn format_duration(duration: f64) -> String {
let seconds = (duration / 1000.0) as i32;
let hours = seconds.div_euclid(3600);
let minutes = seconds.div_euclid(60).rem_euclid(60);
let seconds = seconds.rem_euclid(60);
if hours > 0 {
format!("{hours}∶{minutes:02}∶{seconds:02}")
} else {
format!("{minutes}∶{seconds:02}")
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/mod.rs | src/app/components/mod.rs | #[macro_export]
macro_rules! resource {
($resource:expr) => {
concat!("/dev/diegovsky/Riff", $resource)
};
}
use gettextrs::*;
use std::cell::RefCell;
use std::collections::HashSet;
use std::future::Future;
use crate::api::SpotifyApiError;
use crate::app::{ActionDispatcher, AppAction, AppEvent};
mod navigation;
pub use navigation::*;
mod playback;
pub use playback::*;
mod playlist;
pub use playlist::*;
mod login;
pub use login::*;
mod settings;
pub use settings::*;
mod player_notifier;
pub use player_notifier::PlayerNotifier;
mod library;
pub use library::*;
mod details;
pub use details::*;
mod search;
pub use search::*;
mod album;
use album::*;
mod artist;
use artist::*;
mod artist_details;
pub use artist_details::*;
mod user_details;
pub use user_details::*;
mod now_playing;
pub use now_playing::*;
mod device_selector;
pub use device_selector::*;
mod saved_tracks;
pub use saved_tracks::*;
mod user_menu;
pub use user_menu::*;
mod notification;
pub use notification::*;
mod saved_playlists;
pub use saved_playlists::*;
mod playlist_details;
pub use playlist_details::*;
mod window;
pub use window::*;
mod selection;
pub use selection::*;
mod headerbar;
pub use headerbar::*;
mod scrolling_header;
pub use scrolling_header::*;
pub mod utils;
pub mod labels;
pub mod sidebar;
// without this the builder doesn't seen to know about the custom widgets
pub fn expose_custom_widgets() {
playback::expose_widgets();
selection::expose_widgets();
headerbar::expose_widgets();
device_selector::expose_widgets();
playlist_details::expose_widgets();
scrolling_header::expose_widgets();
}
impl dyn ActionDispatcher {
fn call_spotify_and_dispatch<F, C>(&self, call: C)
where
C: 'static + Send + Clone + FnOnce() -> F,
F: Send + Future<Output = Result<AppAction, SpotifyApiError>>,
{
self.call_spotify_and_dispatch_many(move || async { call().await.map(|a| vec![a]) })
}
fn call_spotify_and_dispatch_many<F, C>(&self, call: C)
where
C: 'static + Send + Clone + FnOnce() -> F,
F: Send + Future<Output = Result<Vec<AppAction>, SpotifyApiError>>,
{
self.dispatch_many_async(Box::pin(async move {
let first_call = call.clone();
let result = first_call().await;
match result {
Ok(actions) => actions,
Err(SpotifyApiError::NoToken) => vec![],
Err(SpotifyApiError::InvalidToken) => call().await.unwrap_or_else(|_| Vec::new()),
Err(err) => {
error!("Spotify API error: {}", err);
vec![AppAction::ShowNotification(gettext(
// translators: This notification is the default message for unhandled errors. Logs refer to console output.
"An error occured. Check logs for details!",
))]
}
}
}))
}
}
thread_local!(static CSS_ADDED: RefCell<HashSet<&'static str>> = RefCell::new(HashSet::new()));
pub fn display_add_css_provider(resource: &'static str) {
CSS_ADDED.with(|set| {
if set.borrow().contains(resource) {
return;
}
set.borrow_mut().insert(resource);
let provider = gtk::CssProvider::new();
provider.load_from_resource(resource);
gtk::style_context_add_provider_for_display(
&gdk::Display::default().unwrap(),
&provider,
gtk::STYLE_PROVIDER_PRIORITY_APPLICATION,
);
});
}
pub trait EventListener {
fn on_event(&mut self, _: &AppEvent) {}
}
pub trait Component {
fn get_root_widget(&self) -> >k::Widget;
fn get_children(&mut self) -> Option<&mut Vec<Box<dyn EventListener>>> {
None
}
fn broadcast_event(&mut self, event: &AppEvent) {
if let Some(children) = self.get_children() {
for child in children.iter_mut() {
child.on_event(event);
}
}
}
}
pub trait ListenerComponent: Component + EventListener {}
impl<T> ListenerComponent for T where T: Component + EventListener {}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/player_notifier.rs | src/app/components/player_notifier.rs | use std::ops::Deref;
use std::rc::Rc;
use futures::channel::mpsc::UnboundedSender;
use librespot::core::spotify_id::SpotifyId;
use librespot::core::SpotifyUri;
use crate::app::components::EventListener;
use crate::app::state::{
Device, LoginAction, LoginEvent, LoginStartedEvent, PlaybackEvent, SettingsEvent,
};
use crate::app::{ActionDispatcher, AppAction, AppEvent, AppModel, SongsSource};
use crate::connect::ConnectCommand;
use crate::player::Command;
enum CurrentlyPlaying {
WithSource {
source: SongsSource,
offset: usize,
song: String,
},
Songs {
songs: Vec<String>,
offset: usize,
},
}
impl CurrentlyPlaying {
fn song_id(&self) -> &String {
match self {
Self::WithSource { song, .. } => song,
Self::Songs { songs, offset } => &songs[*offset],
}
}
}
pub struct PlayerNotifier {
app_model: Rc<AppModel>,
dispatcher: Box<dyn ActionDispatcher>,
command_sender: UnboundedSender<Command>,
connect_command_sender: UnboundedSender<ConnectCommand>,
}
impl PlayerNotifier {
pub fn new(
app_model: Rc<AppModel>,
dispatcher: Box<dyn ActionDispatcher>,
command_sender: UnboundedSender<Command>,
connect_command_sender: UnboundedSender<ConnectCommand>,
) -> Self {
Self {
app_model,
dispatcher,
command_sender,
connect_command_sender,
}
}
fn is_playing(&self) -> bool {
self.app_model.get_state().playback.is_playing()
}
fn currently_playing(&self) -> Option<CurrentlyPlaying> {
let state = self.app_model.get_state();
let song = state.playback.current_song_id()?;
let offset = state.playback.current_song_index()?;
let source = state.playback.current_source().cloned();
let result = match source {
Some(source) if source.has_spotify_uri() => CurrentlyPlaying::WithSource {
source,
offset,
song,
},
_ => CurrentlyPlaying::Songs {
songs: state.playback.songs().map_collect(|s| s.id),
offset,
},
};
Some(result)
}
fn device(&self) -> impl Deref<Target = Device> + '_ {
self.app_model.map_state(|s| s.playback.current_device())
}
fn notify_login(&self, event: &LoginEvent) {
info!("notify_login: {:?}", event);
let command = match event {
LoginEvent::LoginStarted(LoginStartedEvent::Restore) => Some(Command::Restore),
LoginEvent::LoginStarted(LoginStartedEvent::InitLogin) => Some(Command::InitLogin),
LoginEvent::LoginStarted(LoginStartedEvent::CompleteLogin) => {
Some(Command::CompleteLogin)
}
LoginEvent::FreshTokenRequested => Some(Command::RefreshToken),
LoginEvent::LogoutCompleted => Some(Command::Logout),
_ => None,
};
if let Some(command) = command {
self.send_command_to_local_player(command);
}
}
fn notify_connect_player(&self, event: &PlaybackEvent) {
let event = event.clone();
let currently_playing = self.currently_playing();
let command = match event {
PlaybackEvent::TrackChanged(_) | PlaybackEvent::SourceChanged => {
match currently_playing {
Some(CurrentlyPlaying::WithSource {
source,
offset,
song,
}) => Some(ConnectCommand::PlayerLoadInContext {
source,
offset,
song,
}),
Some(CurrentlyPlaying::Songs { songs, offset }) => {
Some(ConnectCommand::PlayerLoad { songs, offset })
}
None => None,
}
}
PlaybackEvent::TrackSeeked(position) => {
Some(ConnectCommand::PlayerSeek(position as usize))
}
PlaybackEvent::PlaybackPaused => Some(ConnectCommand::PlayerPause),
PlaybackEvent::PlaybackResumed => Some(ConnectCommand::PlayerResume),
PlaybackEvent::VolumeSet(volume) => Some(ConnectCommand::PlayerSetVolume(
(volume * 100f64).trunc() as u8,
)),
PlaybackEvent::RepeatModeChanged(mode) => Some(ConnectCommand::PlayerRepeat(mode)),
PlaybackEvent::ShuffleChanged(shuffled) => {
Some(ConnectCommand::PlayerShuffle(shuffled))
}
_ => None,
};
if let Some(command) = command {
self.send_command_to_connect_player(command);
}
}
fn notify_local_player(&self, event: &PlaybackEvent) {
let command = match event {
PlaybackEvent::PlaybackPaused => Some(Command::PlayerPause),
PlaybackEvent::PlaybackResumed => Some(Command::PlayerResume),
PlaybackEvent::PlaybackStopped => Some(Command::PlayerStop),
PlaybackEvent::VolumeSet(volume) => Some(Command::PlayerSetVolume(*volume)),
PlaybackEvent::TrackChanged(id) => {
info!("track changed: {}", id);
SpotifyId::from_base62(id).ok().map(|track| {
Command::PlayerLoad {
track: SpotifyUri::Track { id: track },
resume: true,
}
})
}
PlaybackEvent::SourceChanged => {
let resume = self.is_playing();
self.currently_playing()
.and_then(|c| SpotifyId::from_base62(c.song_id()).ok())
.map(|track| {
Command::PlayerLoad { track: SpotifyUri::Track { id: track }, resume }
})
}
PlaybackEvent::TrackSeeked(position) => Some(Command::PlayerSeek(*position)),
PlaybackEvent::Preload(id) => SpotifyId::from_base62(id)
.ok()
.map(|track| {
SpotifyUri::Track { id: track }
})
.map(Command::PlayerPreload),
_ => None,
};
if let Some(command) = command {
self.send_command_to_local_player(command);
}
}
fn send_command_to_connect_player(&self, command: ConnectCommand) {
self.connect_command_sender.unbounded_send(command).unwrap();
}
fn send_command_to_local_player(&self, command: Command) {
let dispatcher = &self.dispatcher;
self.command_sender
.unbounded_send(command)
.unwrap_or_else(|_| {
dispatcher.dispatch(AppAction::LoginAction(LoginAction::SetLoginFailure));
});
}
fn switch_device(&mut self, device: &Device) {
match device {
Device::Connect(device) => {
self.send_command_to_local_player(Command::PlayerStop);
self.send_command_to_connect_player(ConnectCommand::SetDevice(device.id.clone()));
self.notify_connect_player(&PlaybackEvent::SourceChanged);
}
Device::Local => {
self.send_command_to_connect_player(ConnectCommand::PlayerStop);
self.notify_local_player(&PlaybackEvent::SourceChanged);
}
}
}
}
impl EventListener for PlayerNotifier {
fn on_event(&mut self, event: &AppEvent) {
let device = self.device().clone();
match (device, event) {
(_, AppEvent::LoginEvent(event)) => self.notify_login(event),
(_, AppEvent::PlaybackEvent(PlaybackEvent::SwitchedDevice(d))) => self.switch_device(d),
(Device::Local, AppEvent::PlaybackEvent(event)) => self.notify_local_player(event),
(Device::Local, AppEvent::SettingsEvent(SettingsEvent::PlayerSettingsChanged)) => {
self.send_command_to_local_player(Command::ReloadSettings)
}
(Device::Connect(_), AppEvent::PlaybackEvent(event)) => {
self.notify_connect_player(event)
}
_ => {}
}
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/labels.rs | src/app/components/labels.rs | use gettextrs::*;
lazy_static! {
// translators: This is part of a contextual menu attached to a single track; this entry allows viewing the album containing a specific track.
pub static ref VIEW_ALBUM: String = gettext("View album");
// translators: This is part of a contextual menu attached to a single track; the intent is to copy the link (public URL) to a specific track.
pub static ref COPY_LINK: String = gettext("Copy link");
// translators: This is part of a contextual menu attached to a single track; this entry adds a track at the end of the play queue.
pub static ref ADD_TO_QUEUE: String = gettext("Add to queue");
// translators: This is part of a contextual menu attached to a single track; this entry removes a track from the play queue.
pub static ref REMOVE_FROM_QUEUE: String = gettext("Remove from queue");
}
pub fn add_to_playlist_label(playlist: &str) -> String {
// this is just to fool xgettext, it doesn't like macros (or rust for that matter) :(
if cfg!(debug_assertions) {
// translators: This is part of a larger text that says "Add to <playlist name>". This text should be as short as possible.
gettext("Add to {}");
}
gettext!("Add to {}", playlist)
}
pub fn n_songs_selected_label(n: usize) -> String {
// this is just to fool xgettext, it doesn't like macros (or rust for that matter) :(
if cfg!(debug_assertions) {
// translators: This shows up when in selection mode. This text should be as short as possible.
ngettext("{} song selected", "{} songs selected", n as u32);
}
ngettext!("{} song selected", "{} songs selected", n as u32, n)
}
pub fn more_from_label(artist: &str) -> String {
// this is just to fool xgettext, it doesn't like macros (or rust for that matter) :(
if cfg!(debug_assertions) {
// translators: This is part of a contextual menu attached to a single track; the full text is "More from <artist>".
gettext("More from {}");
}
gettext!("More from {}", glib::markup_escape_text(artist))
}
pub fn album_by_artist_label(album: &str, artist: &str) -> String {
// this is just to fool xgettext, it doesn't like macros (or rust for that matter) :(
if cfg!(debug_assertions) {
// translators: This is part of a larger label that reads "<Album> by <Artist>"
gettext("{} by {}");
}
gettext!(
"{} by {}",
glib::markup_escape_text(album),
glib::markup_escape_text(artist)
)
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/login/login.rs | src/app/components/login/login.rs | use gtk::prelude::*;
use gtk::subclass::prelude::*;
use gtk::CompositeTemplate;
use std::rc::Rc;
use url::Url;
use crate::app::components::EventListener;
use crate::app::state::{LoginEvent, LoginStartedEvent};
use crate::app::AppEvent;
use super::LoginModel;
mod imp {
use libadwaita::subclass::prelude::AdwWindowImpl;
use super::*;
#[derive(Debug, Default, CompositeTemplate)]
#[template(resource = "/dev/diegovsky/Riff/components/login.ui")]
pub struct LoginWindow {
#[template_child]
pub login_with_spotify_button: TemplateChild<gtk::Button>,
#[template_child]
pub auth_error_container: TemplateChild<gtk::Revealer>,
}
#[glib::object_subclass]
impl ObjectSubclass for LoginWindow {
const NAME: &'static str = "LoginWindow";
type Type = super::LoginWindow;
type ParentType = libadwaita::Window;
fn class_init(klass: &mut Self::Class) {
klass.bind_template();
}
fn instance_init(obj: &glib::subclass::InitializingObject<Self>) {
obj.init_template();
}
}
impl ObjectImpl for LoginWindow {}
impl WidgetImpl for LoginWindow {}
impl AdwWindowImpl for LoginWindow {}
impl WindowImpl for LoginWindow {}
}
glib::wrapper! {
pub struct LoginWindow(ObjectSubclass<imp::LoginWindow>) @extends gtk::Widget, libadwaita::Window;
}
impl Default for LoginWindow {
fn default() -> Self {
Self::new()
}
}
impl LoginWindow {
pub fn new() -> Self {
glib::Object::new()
}
fn connect_close<F>(&self, on_close: F)
where
F: Fn() + 'static,
{
let window = self.upcast_ref::<libadwaita::Window>();
window.connect_close_request(move |_| {
on_close();
glib::Propagation::Stop
});
}
fn connect_login_oauth_spotify<F>(&self, on_login_with_spotify_button: F)
where
F: Fn() + 'static,
{
self.imp()
.login_with_spotify_button
.connect_clicked(move |_| on_login_with_spotify_button());
}
fn show_auth_error(&self, shown: bool) {
let widget = self.imp();
widget.auth_error_container.set_reveal_child(shown);
}
}
pub struct Login {
parent: gtk::Window,
login_window: LoginWindow,
model: Rc<LoginModel>,
}
impl Login {
pub fn new(parent: gtk::Window, model: LoginModel) -> Self {
let model = Rc::new(model);
let login_window = LoginWindow::new();
login_window.connect_close(clone!(
#[weak]
parent,
move || {
if let Some(app) = parent.application().as_ref() {
app.quit();
}
}
));
login_window.connect_login_oauth_spotify(clone!(
#[weak]
model,
move || {
model.login_with_spotify();
}
));
Self {
parent,
login_window,
model,
}
}
fn window(&self) -> &libadwaita::Window {
self.login_window.upcast_ref::<libadwaita::Window>()
}
fn show_self(&self) {
self.window().set_transient_for(Some(&self.parent));
self.window().set_modal(true);
self.window().set_visible(true);
}
fn hide(&self) {
self.window().set_visible(false);
}
fn reveal_error(&self) {
self.show_self();
self.login_window.show_auth_error(true);
}
fn open_login_url(&self, url: Url) {
if open::that(url.as_str()).is_err() {
warn!("Could not open login page");
}
}
}
impl EventListener for Login {
fn on_event(&mut self, event: &AppEvent) {
match event {
AppEvent::LoginEvent(LoginEvent::LoginCompleted) => {
self.hide();
}
AppEvent::LoginEvent(LoginEvent::LoginFailed) => {
self.reveal_error();
}
AppEvent::LoginEvent(LoginEvent::LoginStarted(LoginStartedEvent::OpenUrl(url))) => {
self.open_login_url(url.clone());
}
AppEvent::Started => {
self.model.try_autologin();
}
AppEvent::LoginEvent(LoginEvent::LogoutCompleted | LoginEvent::LoginShown) => {
self.show_self();
}
_ => {}
}
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/login/login_model.rs | src/app/components/login/login_model.rs | use crate::app::state::{LoginAction, TryLoginAction};
use crate::app::ActionDispatcher;
pub struct LoginModel {
dispatcher: Box<dyn ActionDispatcher>,
}
impl LoginModel {
pub fn new(dispatcher: Box<dyn ActionDispatcher>) -> Self {
Self { dispatcher }
}
pub fn try_autologin(&self) {
self.dispatcher
.dispatch(LoginAction::TryLogin(TryLoginAction::Restore).into());
}
pub fn login_with_spotify(&self) {
self.dispatcher
.dispatch(LoginAction::TryLogin(TryLoginAction::InitLogin).into())
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/login/mod.rs | src/app/components/login/mod.rs | #[allow(clippy::module_inception)]
mod login;
mod login_model;
pub use login::*;
pub use login_model::*;
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/playlist_details/playlist_details_model.rs | src/app/components/playlist_details/playlist_details_model.rs | use gettextrs::gettext;
use gio::prelude::*;
use gio::SimpleActionGroup;
use std::cell::Ref;
use std::ops::Deref;
use std::rc::Rc;
use crate::api::SpotifyApiError;
use crate::app::components::{labels, PlaylistModel};
use crate::app::models::*;
use crate::app::state::SelectionContext;
use crate::app::state::{BrowserAction, PlaybackAction, SelectionAction, SelectionState};
use crate::app::AppState;
use crate::app::{ActionDispatcher, AppAction, AppModel, BatchQuery, SongsSource};
pub struct PlaylistDetailsModel {
pub id: String,
app_model: Rc<AppModel>,
dispatcher: Box<dyn ActionDispatcher>,
}
impl PlaylistDetailsModel {
pub fn new(id: String, app_model: Rc<AppModel>, dispatcher: Box<dyn ActionDispatcher>) -> Self {
Self {
id,
app_model,
dispatcher,
}
}
pub fn state(&self) -> Ref<'_, AppState> {
self.app_model.get_state()
}
pub fn is_playlist_editable(&self) -> bool {
let state = self.app_model.get_state();
state.logged_user.playlists.iter().any(|p| p.id == self.id)
}
pub fn get_playlist_info(&self) -> Option<impl Deref<Target = PlaylistDescription> + '_> {
self.app_model.map_state_opt(|s| {
s.browser
.playlist_details_state(&self.id)?
.playlist
.as_ref()
})
}
pub fn is_playing(&self) -> bool {
self.state().playback.is_playing()
}
pub fn playlist_is_playing(&self) -> bool {
matches!(
self.app_model.get_state().playback.current_source(),
Some(SongsSource::Playlist(ref id)) if id == &self.id)
}
pub fn toggle_play_playlist(&self) {
if let Some(playlist) = self.get_playlist_info() {
if !self.playlist_is_playing() {
if self.state().playback.is_shuffled() {
self.dispatcher
.dispatch(AppAction::PlaybackAction(PlaybackAction::ToggleShuffle));
}
// The playlist has no songs and the user has still decided to click the play button,
// lets just do an early return and show an error...
if playlist.songs.songs.is_empty() {
error!("Unable to start playback because songs is empty");
self.dispatcher
.dispatch(AppAction::ShowNotification(gettext(
"An error occured. Check logs for details!",
)));
return;
}
let id_of_first_song = playlist.songs.songs[0].id.as_str();
self.play_song_at(0, id_of_first_song);
return;
}
if self.state().playback.is_playing() {
self.dispatcher
.dispatch(AppAction::PlaybackAction(PlaybackAction::Pause));
} else {
self.dispatcher
.dispatch(AppAction::PlaybackAction(PlaybackAction::Play));
}
}
}
pub fn load_playlist_info(&self) {
let api = self.app_model.get_spotify();
let id = self.id.clone();
self.dispatcher
.call_spotify_and_dispatch(move || async move {
let playlist = api.get_playlist(&id).await;
let playlist_tracks = api.get_playlist_tracks(&id, 0, 100).await?;
match playlist {
Ok(playlist) => Ok(BrowserAction::SetPlaylistDetails(
Box::new(playlist),
Box::new(playlist_tracks),
)
.into()),
Err(SpotifyApiError::BadStatus(400, _))
| Err(SpotifyApiError::BadStatus(404, _)) => {
Ok(BrowserAction::NavigationPop.into())
}
Err(e) => Err(e),
}
});
}
pub fn load_more_tracks(&self) -> Option<()> {
let last_batch = self.song_list_model().last_batch()?;
let query = BatchQuery {
source: SongsSource::Playlist(self.id.clone()),
batch: last_batch,
};
let id = self.id.clone();
let next_query = query.next()?;
debug!("next_query = {:?}", &next_query);
let loader = self.app_model.get_batch_loader();
self.dispatcher.dispatch_async(Box::pin(async move {
loader
.query(next_query, |_s, song_batch| {
BrowserAction::AppendPlaylistTracks(id, Box::new(song_batch)).into()
})
.await
}));
Some(())
}
pub fn update_playlist_details(&self, title: String) {
let api = self.app_model.get_spotify();
let id = self.id.clone();
self.dispatcher
.call_spotify_and_dispatch(move || async move {
let playlist = api.update_playlist_details(&id, title.clone()).await;
match playlist {
Ok(_) => Ok(AppAction::UpdatePlaylistName(PlaylistSummary { id, title })),
Err(e) => Err(e),
}
});
}
pub fn view_owner(&self) {
if let Some(playlist) = self.get_playlist_info() {
let owner = &playlist.owner.id;
self.dispatcher
.dispatch(AppAction::ViewUser(owner.to_owned()));
}
}
pub fn disable_selection(&self) {
self.dispatcher.dispatch(AppAction::CancelSelection);
}
pub fn go_back(&self) {
self.dispatcher
.dispatch(BrowserAction::NavigationPop.into());
}
}
impl PlaylistModel for PlaylistDetailsModel {
fn song_list_model(&self) -> SongListModel {
self.state()
.browser
.playlist_details_state(&self.id)
.expect("illegal attempt to read playlist_details_state")
.songs
.clone()
}
fn is_paused(&self) -> bool {
!self.state().playback.is_playing()
}
fn current_song_id(&self) -> Option<String> {
self.state().playback.current_song_id()
}
fn play_song_at(&self, pos: usize, id: &str) {
let source = SongsSource::Playlist(self.id.clone());
let batch = self.song_list_model().song_batch_for(pos);
if let Some(batch) = batch {
self.dispatcher
.dispatch(PlaybackAction::LoadPagedSongs(source, batch).into());
self.dispatcher
.dispatch(PlaybackAction::Load(id.to_string()).into());
}
}
fn actions_for(&self, id: &str) -> Option<gio::ActionGroup> {
let song = self.song_list_model().get(id)?;
let song = song.description();
let group = SimpleActionGroup::new();
for view_artist in song.make_artist_actions(self.dispatcher.box_clone(), None) {
group.add_action(&view_artist);
}
group.add_action(&song.make_album_action(self.dispatcher.box_clone(), None));
group.add_action(&song.make_link_action(None));
group.add_action(&song.make_queue_action(self.dispatcher.box_clone(), None));
Some(group.upcast())
}
fn menu_for(&self, id: &str) -> Option<gio::MenuModel> {
let song = self.song_list_model().get(id)?;
let song = song.description();
let menu = gio::Menu::new();
menu.append(Some(&*labels::VIEW_ALBUM), Some("song.view_album"));
for artist in song.artists.iter() {
menu.append(
Some(&labels::more_from_label(&artist.name)),
Some(&format!("song.view_artist_{}", artist.id)),
);
}
menu.append(Some(&*labels::COPY_LINK), Some("song.copy_link"));
menu.append(Some(&*labels::ADD_TO_QUEUE), Some("song.queue"));
Some(menu.upcast())
}
fn select_song(&self, id: &str) {
let song = self.song_list_model().get(id);
if let Some(song) = song {
self.dispatcher
.dispatch(SelectionAction::Select(vec![song.into_description()]).into());
}
}
fn deselect_song(&self, id: &str) {
self.dispatcher
.dispatch(SelectionAction::Deselect(vec![id.to_string()]).into());
}
fn enable_selection(&self) -> bool {
self.dispatcher
.dispatch(AppAction::EnableSelection(if self.is_playlist_editable() {
SelectionContext::EditablePlaylist(self.id.clone())
} else {
SelectionContext::Playlist
}));
true
}
fn selection(&self) -> Option<Box<dyn Deref<Target = SelectionState> + '_>> {
Some(Box::new(self.app_model.map_state(|s| &s.selection)))
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/playlist_details/playlist_details.rs | src/app/components/playlist_details/playlist_details.rs | use gtk::prelude::*;
use gtk::subclass::prelude::*;
use gtk::CompositeTemplate;
use std::rc::Rc;
use super::playlist_header::PlaylistHeaderWidget;
use super::playlist_headerbar::PlaylistHeaderBarWidget;
use super::PlaylistDetailsModel;
use crate::app::components::{
Component, EventListener, Playlist, PlaylistModel, ScrollingHeaderWidget,
};
use crate::app::dispatch::Worker;
use crate::app::loader::ImageLoader;
use crate::app::state::{PlaybackEvent, SelectionEvent};
use crate::app::{AppEvent, BrowserEvent};
use libadwaita::subclass::prelude::BinImpl;
mod imp {
use super::*;
#[derive(Debug, Default, CompositeTemplate)]
#[template(resource = "/dev/diegovsky/Riff/components/playlist_details.ui")]
pub struct PlaylistDetailsWidget {
#[template_child]
pub headerbar: TemplateChild<PlaylistHeaderBarWidget>,
#[template_child]
pub scrolling_header: TemplateChild<ScrollingHeaderWidget>,
#[template_child]
pub header_widget: TemplateChild<PlaylistHeaderWidget>,
#[template_child]
pub tracks: TemplateChild<gtk::ListView>,
}
#[glib::object_subclass]
impl ObjectSubclass for PlaylistDetailsWidget {
const NAME: &'static str = "PlaylistDetailsWidget";
type Type = super::PlaylistDetailsWidget;
type ParentType = libadwaita::Bin;
fn class_init(klass: &mut Self::Class) {
klass.bind_template();
}
fn instance_init(obj: &glib::subclass::InitializingObject<Self>) {
obj.init_template();
}
}
impl ObjectImpl for PlaylistDetailsWidget {
fn constructed(&self) {
self.parent_constructed();
self.header_widget.set_grows_automatically();
}
}
impl WidgetImpl for PlaylistDetailsWidget {}
impl BinImpl for PlaylistDetailsWidget {}
}
glib::wrapper! {
pub struct PlaylistDetailsWidget(ObjectSubclass<imp::PlaylistDetailsWidget>) @extends gtk::Widget, libadwaita::Bin;
}
impl PlaylistDetailsWidget {
fn new() -> Self {
glib::Object::new()
}
fn playlist_tracks_widget(&self) -> >k::ListView {
self.imp().tracks.as_ref()
}
fn connect_bottom_edge<F>(&self, f: F)
where
F: Fn() + 'static,
{
self.imp().scrolling_header.connect_bottom_edge(f);
}
fn set_header_visible(&self, visible: bool) {
let widget = self.imp();
widget.headerbar.set_title_visible(true);
if visible {
widget.headerbar.add_classes(&["flat"]);
} else {
widget.headerbar.remove_classes(&["flat"]);
}
}
fn connect_header(&self) {
self.set_header_visible(false);
self.imp()
.scrolling_header
.connect_header_visibility(clone!(
#[weak(rename_to = _self)]
self,
move |visible| {
_self.set_header_visible(visible);
}
));
}
fn set_loaded(&self) {
self.imp()
.scrolling_header
.add_css_class("container--loaded");
}
fn set_editing(&self, editing: bool) {
self.imp().header_widget.set_editing(editing);
self.imp().headerbar.set_editing(editing);
}
fn set_editable(&self, editing: bool) {
self.imp().headerbar.set_editable(editing);
}
fn set_info(&self, playlist: &str, owner: &str) {
self.imp().header_widget.set_info(playlist, owner);
self.imp().headerbar.set_title(Some(playlist));
}
fn set_playing(&self, is_playing: bool) {
self.imp().header_widget.set_playing(is_playing);
}
fn set_artwork(&self, art: &gdk_pixbuf::Pixbuf) {
self.imp().header_widget.set_artwork(art);
}
fn connect_owner_clicked<F>(&self, f: F)
where
F: Fn() + 'static,
{
self.imp().header_widget.connect_owner_clicked(f);
}
pub fn connect_edit<F>(&self, f: F)
where
F: Fn() + 'static,
{
self.imp().headerbar.connect_edit(f);
}
pub fn connect_cancel<F>(&self, f: F)
where
F: Fn() + 'static,
{
self.imp().headerbar.connect_cancel(clone!(
#[weak(rename_to = _self)]
self,
move || {
_self.imp().header_widget.reset_playlist_name();
f();
}
));
}
pub fn connect_play<F>(&self, f: F)
where
F: Fn() + 'static,
{
self.imp().header_widget.connect_play(f);
}
pub fn connect_done<F>(&self, f: F)
where
F: Fn(String) + 'static,
{
self.imp().headerbar.connect_ok(clone!(
#[weak(rename_to = _self)]
self,
move || {
let s = _self.imp().header_widget.get_edited_playlist_name();
f(s);
}
));
}
pub fn connect_go_back<F>(&self, f: F)
where
F: Fn() + 'static,
{
self.imp().headerbar.connect_go_back(f);
}
}
pub struct PlaylistDetails {
model: Rc<PlaylistDetailsModel>,
worker: Worker,
widget: PlaylistDetailsWidget,
children: Vec<Box<dyn EventListener>>,
}
impl PlaylistDetails {
pub fn new(model: Rc<PlaylistDetailsModel>, worker: Worker) -> Self {
if model.get_playlist_info().is_none() {
model.load_playlist_info();
}
let widget = PlaylistDetailsWidget::new();
let playlist = Box::new(Playlist::new(
widget.playlist_tracks_widget().clone(),
model.clone(),
worker.clone(),
));
widget.set_editable(model.is_playlist_editable());
widget.connect_header();
widget.connect_bottom_edge(clone!(
#[weak]
model,
move || {
model.load_more_tracks();
}
));
widget.connect_owner_clicked(clone!(
#[weak]
model,
move || model.view_owner()
));
widget.connect_edit(clone!(
#[weak]
model,
move || {
model.enable_selection();
}
));
widget.connect_cancel(clone!(
#[weak]
model,
move || model.disable_selection()
));
widget.connect_done(clone!(
#[weak]
model,
move |n| {
model.disable_selection();
model.update_playlist_details(n);
}
));
widget.connect_play(clone!(
#[weak]
model,
move || model.toggle_play_playlist()
));
widget.connect_go_back(clone!(
#[weak]
model,
move || model.go_back()
));
Self {
model,
worker,
widget,
children: vec![playlist],
}
}
fn update_details(&self) {
if let Some(info) = self.model.get_playlist_info() {
let title = &info.title[..];
let owner = &info.owner.display_name[..];
let art_url = info.art.as_ref();
self.widget.set_info(title, owner);
if let Some(art_url) = art_url.cloned() {
let widget = self.widget.downgrade();
self.worker.send_local_task(async move {
let pixbuf = ImageLoader::new()
.load_remote(&art_url[..], "jpg", 320, 320)
.await;
if let (Some(widget), Some(ref pixbuf)) = (widget.upgrade(), pixbuf) {
widget.set_artwork(pixbuf);
widget.set_loaded();
}
});
} else {
self.widget.set_loaded();
}
}
}
fn update_playing(&self, is_playing: bool) {
if !self.model.playlist_is_playing() || !self.model.is_playing() {
self.widget.set_playing(false);
return;
}
self.widget.set_playing(is_playing);
}
fn set_editing(&self, editable: bool) {
if !self.model.is_playlist_editable() {
return;
}
self.widget.set_editing(editable);
}
}
impl Component for PlaylistDetails {
fn get_root_widget(&self) -> >k::Widget {
self.widget.upcast_ref()
}
fn get_children(&mut self) -> Option<&mut Vec<Box<dyn EventListener>>> {
Some(&mut self.children)
}
}
impl EventListener for PlaylistDetails {
fn on_event(&mut self, event: &AppEvent) {
match event {
AppEvent::BrowserEvent(BrowserEvent::PlaylistDetailsLoaded(id))
if id == &self.model.id =>
{
self.update_details();
self.update_playing(true);
}
AppEvent::SelectionEvent(SelectionEvent::SelectionModeChanged(editing)) => {
self.set_editing(*editing);
}
AppEvent::PlaybackEvent(PlaybackEvent::PlaybackPaused) => {
self.update_playing(false);
}
AppEvent::PlaybackEvent(PlaybackEvent::PlaybackResumed) => {
self.update_playing(true);
}
_ => {}
}
self.broadcast_event(event);
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/playlist_details/mod.rs | src/app/components/playlist_details/mod.rs | #[allow(clippy::module_inception)]
mod playlist_details;
mod playlist_details_model;
mod playlist_header;
mod playlist_headerbar;
pub use playlist_details::*;
pub use playlist_details_model::*;
use gtk::prelude::StaticType;
pub fn expose_widgets() {
playlist_headerbar::PlaylistHeaderBarWidget::static_type();
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/playlist_details/playlist_header.rs | src/app/components/playlist_details/playlist_header.rs | use crate::app::components::display_add_css_provider;
use gettextrs::gettext;
use gtk::prelude::*;
use gtk::subclass::prelude::*;
use gtk::{glib, CompositeTemplate};
const CSS_RO_ENTRY: &str = "playlist__title-entry--ro";
mod imp {
use glib::Properties;
use std::cell::{Cell, RefCell};
use super::*;
#[derive(Debug, Default, CompositeTemplate, Properties)]
#[template(resource = "/dev/diegovsky/Riff/components/playlist_header.ui")]
#[properties(wrapper_type = super::PlaylistHeaderWidget)]
pub struct PlaylistHeaderWidget {
#[template_child]
pub playlist_label_entry: TemplateChild<gtk::Entry>,
#[template_child]
pub playlist_image_box: TemplateChild<gtk::Box>,
#[template_child]
pub playlist_art: TemplateChild<gtk::Picture>,
#[template_child]
pub playlist_info: TemplateChild<gtk::Box>,
#[template_child]
pub author_button: TemplateChild<gtk::LinkButton>,
#[template_child]
pub author_button_label: TemplateChild<gtk::Label>,
#[template_child]
pub play_button: TemplateChild<gtk::Button>,
#[property(get, set, name = "original-entry-text")]
pub original_entry_text: RefCell<String>,
#[property(get, set = Self::set_vertical, name = "vertical-layout")]
pub vertical_layout: Cell<bool>,
}
impl PlaylistHeaderWidget {
pub fn set_vertical(&self, vertical: bool) {
let self_ = self.obj();
let box_ = self_.upcast_ref::<gtk::Box>();
if vertical {
box_.set_orientation(gtk::Orientation::Vertical);
box_.set_spacing(12);
self.playlist_info.set_halign(gtk::Align::Center);
EntryExt::set_alignment(&*self.playlist_label_entry, 0.5);
self.author_button.set_halign(gtk::Align::Center);
} else {
box_.set_orientation(gtk::Orientation::Horizontal);
box_.set_spacing(0);
self.playlist_info.set_halign(gtk::Align::Start);
EntryExt::set_alignment(&*self.playlist_label_entry, 0.0);
self.author_button.set_halign(gtk::Align::Start);
}
}
}
#[glib::object_subclass]
impl ObjectSubclass for PlaylistHeaderWidget {
const NAME: &'static str = "PlaylistHeaderWidget";
type Type = super::PlaylistHeaderWidget;
type ParentType = gtk::Box;
fn class_init(klass: &mut Self::Class) {
Self::bind_template(klass);
}
fn instance_init(obj: &glib::subclass::InitializingObject<Self>) {
display_add_css_provider(resource!("/components/playlist_header.css"));
obj.init_template();
}
}
#[glib::derived_properties]
impl ObjectImpl for PlaylistHeaderWidget {}
impl WidgetImpl for PlaylistHeaderWidget {}
impl BoxImpl for PlaylistHeaderWidget {}
}
glib::wrapper! {
pub struct PlaylistHeaderWidget(ObjectSubclass<imp::PlaylistHeaderWidget>) @extends gtk::Widget, gtk::Box;
}
impl Default for PlaylistHeaderWidget {
fn default() -> Self {
Self::new()
}
}
impl PlaylistHeaderWidget {
pub fn new() -> Self {
glib::Object::new()
}
pub fn connect_owner_clicked<F>(&self, f: F)
where
F: Fn() + 'static,
{
self.imp().author_button.connect_activate_link(move |_| {
f();
glib::Propagation::Stop
});
}
pub fn connect_play<F>(&self, f: F)
where
F: Fn() + 'static,
{
self.imp().play_button.connect_clicked(move |_| f());
}
pub fn reset_playlist_name(&self) {
self.imp()
.playlist_label_entry
.set_text(&self.original_entry_text());
}
pub fn get_edited_playlist_name(&self) -> String {
self.imp().playlist_label_entry.text().to_string()
}
pub fn set_artwork(&self, pixbuf: &gdk_pixbuf::Pixbuf) {
let texture = gdk::Texture::for_pixbuf(pixbuf);
self.imp().playlist_art.set_paintable(Some(&texture));
}
pub fn set_info(&self, playlist: &str, owner: &str) {
let widget = self.imp();
self.set_original_entry_text(playlist);
widget.playlist_label_entry.set_text(playlist);
widget
.playlist_label_entry
.set_placeholder_text(Some(playlist));
widget.author_button_label.set_label(owner);
}
pub fn set_playing(&self, is_playing: bool) {
let playback_icon = if is_playing {
"media-playback-pause-symbolic"
} else {
"media-playback-start-symbolic"
};
let translated_tooltip = if is_playing {
gettext("Pause")
} else {
gettext("Play")
};
let tooltip_text = Some(translated_tooltip.as_str());
self.imp().play_button.set_icon_name(playback_icon);
self.imp().play_button.set_tooltip_text(tooltip_text);
}
pub fn set_editing(&self, editing: bool) {
let widget = self.imp();
widget.playlist_label_entry.set_can_focus(editing);
widget.playlist_label_entry.set_editable(editing);
if editing {
widget.playlist_label_entry.remove_css_class(CSS_RO_ENTRY);
} else {
widget.playlist_label_entry.add_css_class(CSS_RO_ENTRY);
}
}
pub fn entry(&self) -> >k::Entry {
self.imp().playlist_label_entry.as_ref()
}
pub fn set_grows_automatically(&self) {
let entry: >k::Entry = &self.imp().playlist_label_entry;
entry
.bind_property("text", entry, "width-chars")
.transform_to(|_, text: &str| Some(text.len() as i32))
.flags(glib::BindingFlags::DEFAULT | glib::BindingFlags::SYNC_CREATE)
.build();
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/playlist_details/playlist_headerbar.rs | src/app/components/playlist_details/playlist_headerbar.rs | use gtk::prelude::*;
use gtk::subclass::prelude::*;
use gtk::CompositeTemplate;
use libadwaita::subclass::prelude::BinImpl;
mod imp {
use super::*;
#[derive(Debug, Default, CompositeTemplate)]
#[template(resource = "/dev/diegovsky/Riff/components/playlist_headerbar.ui")]
pub struct PlaylistHeaderBarWidget {
#[template_child]
pub main_header: TemplateChild<libadwaita::HeaderBar>,
#[template_child]
pub edition_header: TemplateChild<libadwaita::HeaderBar>,
#[template_child]
pub go_back: TemplateChild<gtk::Button>,
#[template_child]
pub title: TemplateChild<libadwaita::WindowTitle>,
#[template_child]
pub edit: TemplateChild<gtk::Button>,
#[template_child]
pub ok: TemplateChild<gtk::Button>,
#[template_child]
pub cancel: TemplateChild<gtk::Button>,
#[template_child]
pub overlay: TemplateChild<gtk::Overlay>,
}
#[glib::object_subclass]
impl ObjectSubclass for PlaylistHeaderBarWidget {
const NAME: &'static str = "PlaylistHeaderBarWidget";
type Type = super::PlaylistHeaderBarWidget;
type ParentType = libadwaita::Bin;
type Interfaces = (gtk::Buildable,);
fn class_init(klass: &mut Self::Class) {
Self::bind_template(klass);
}
fn instance_init(obj: &glib::subclass::InitializingObject<Self>) {
obj.init_template();
}
}
impl ObjectImpl for PlaylistHeaderBarWidget {}
impl BuildableImpl for PlaylistHeaderBarWidget {
fn add_child(&self, builder: >k::Builder, child: &glib::Object, type_: Option<&str>) {
if Some("root") == type_ {
self.parent_add_child(builder, child, type_);
} else {
self.main_header
.set_title_widget(child.downcast_ref::<gtk::Widget>());
}
}
}
impl WidgetImpl for PlaylistHeaderBarWidget {}
impl BinImpl for PlaylistHeaderBarWidget {}
impl WindowImpl for PlaylistHeaderBarWidget {}
}
glib::wrapper! {
pub struct PlaylistHeaderBarWidget(ObjectSubclass<imp::PlaylistHeaderBarWidget>) @extends gtk::Widget, libadwaita::Bin;
}
impl Default for PlaylistHeaderBarWidget {
fn default() -> Self {
Self::new()
}
}
impl PlaylistHeaderBarWidget {
pub fn new() -> Self {
glib::Object::new()
}
pub fn connect_edit<F>(&self, f: F)
where
F: Fn() + 'static,
{
self.imp().edit.connect_clicked(move |_| f());
}
pub fn connect_ok<F>(&self, f: F)
where
F: Fn() + 'static,
{
self.imp().ok.connect_clicked(move |_| f());
}
pub fn connect_cancel<F>(&self, f: F)
where
F: Fn() + 'static,
{
self.imp().cancel.connect_clicked(move |_| f());
}
pub fn connect_go_back<F>(&self, f: F)
where
F: Fn() + 'static,
{
self.imp().go_back.connect_clicked(move |_| f());
}
pub fn set_can_go_back(&self, can_go_back: bool) {
self.imp().go_back.set_visible(can_go_back);
}
pub fn set_editable(&self, editable: bool) {
self.imp().edit.set_visible(editable);
}
pub fn set_editing(&self, editing: bool) {
if editing {
self.imp().edition_header.set_visible(true);
} else {
self.imp().edition_header.set_visible(false);
}
}
pub fn add_classes(&self, classes: &[&str]) {
for &class in classes {
self.add_css_class(class);
}
}
pub fn remove_classes(&self, classes: &[&str]) {
for &class in classes {
self.remove_css_class(class);
}
}
pub fn set_title_visible(&self, visible: bool) {
self.imp().title.set_visible(visible);
}
pub fn set_title(&self, title: Option<&str>) {
self.imp().title.set_visible(title.is_some());
if let Some(title) = title {
self.imp().title.set_title(title);
}
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/window/mod.rs | src/app/components/window/mod.rs | use gtk::prelude::*;
use std::cell::RefCell;
use std::rc::Rc;
use crate::app::components::EventListener;
use crate::app::{AppEvent, AppModel};
use crate::settings::WindowGeometry;
thread_local! {
static WINDOW_GEOMETRY: RefCell<WindowGeometry> = const { RefCell::new(WindowGeometry {
width: 0, height: 0, is_maximized: false
}) };
}
pub struct MainWindow {
initial_window_geometry: WindowGeometry,
window: libadwaita::ApplicationWindow,
}
impl MainWindow {
pub fn new(
initial_window_geometry: WindowGeometry,
app_model: Rc<AppModel>,
window: libadwaita::ApplicationWindow,
) -> Self {
window.connect_close_request(clone!(
#[weak]
app_model,
#[upgrade_or]
glib::Propagation::Proceed,
move |window| {
let state = app_model.get_state();
if state.playback.is_playing() {
window.set_visible(false);
glib::Propagation::Stop
} else {
glib::Propagation::Proceed
}
}
));
window.connect_default_height_notify(Self::save_window_geometry);
window.connect_default_width_notify(Self::save_window_geometry);
window.connect_maximized_notify(Self::save_window_geometry);
window.connect_unrealize(|_| {
debug!("saving geometry");
WINDOW_GEOMETRY.with(|g| g.borrow().save());
});
Self {
initial_window_geometry,
window,
}
}
fn start(&self) {
self.window.set_default_size(
self.initial_window_geometry.width,
self.initial_window_geometry.height,
);
if self.initial_window_geometry.is_maximized {
self.window.maximize();
}
self.window.present();
}
fn raise(&self) {
self.window.present();
}
fn save_window_geometry<W: GtkWindowExt>(window: &W) {
let (width, height) = window.default_size();
let is_maximized = window.is_maximized();
WINDOW_GEOMETRY.with(|g| {
let mut g = g.borrow_mut();
g.is_maximized = is_maximized;
if !is_maximized {
g.width = width;
g.height = height;
}
});
}
}
impl EventListener for MainWindow {
fn on_event(&mut self, event: &AppEvent) {
match event {
AppEvent::Started => self.start(),
AppEvent::Raised => self.raise(),
_ => {}
}
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/settings/settings_model.rs | src/app/components/settings/settings_model.rs | use crate::app::state::{PlaybackAction, SettingsAction};
use crate::app::{ActionDispatcher, AppModel};
use crate::settings::RiffSettings;
use std::rc::Rc;
pub struct SettingsModel {
app_model: Rc<AppModel>,
dispatcher: Box<dyn ActionDispatcher>,
}
impl SettingsModel {
pub fn new(app_model: Rc<AppModel>, dispatcher: Box<dyn ActionDispatcher>) -> Self {
Self {
app_model,
dispatcher,
}
}
pub fn stop_player(&self) {
self.dispatcher.dispatch(PlaybackAction::Stop.into());
}
pub fn set_settings(&self) {
self.dispatcher
.dispatch(SettingsAction::ChangeSettings.into());
}
pub fn settings(&self) -> RiffSettings {
let state = self.app_model.get_state();
state.settings.settings.clone()
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/settings/settings.rs | src/app/components/settings/settings.rs | use crate::app::components::EventListener;
use crate::app::AppEvent;
use crate::settings::RiffSettings;
use gtk::prelude::*;
use gtk::subclass::prelude::*;
use gtk::CompositeTemplate;
use libadwaita::prelude::*;
use super::SettingsModel;
const SETTINGS: &str = "dev.diegovsky.Riff";
mod imp {
use super::*;
use libadwaita::subclass::prelude::*;
#[derive(Debug, Default, CompositeTemplate)]
#[template(resource = "/dev/diegovsky/Riff/components/settings.ui")]
pub struct SettingsDialog {
#[template_child]
pub player_bitrate: TemplateChild<libadwaita::ComboRow>,
#[template_child]
pub alsa_device: TemplateChild<gtk::Entry>,
#[template_child]
pub alsa_device_row: TemplateChild<libadwaita::ActionRow>,
#[template_child]
pub audio_backend: TemplateChild<libadwaita::ComboRow>,
#[template_child]
pub gapless_playback: TemplateChild<libadwaita::ActionRow>,
#[template_child]
pub ap_port: TemplateChild<gtk::Entry>,
#[template_child]
pub theme: TemplateChild<libadwaita::ComboRow>,
}
#[glib::object_subclass]
impl ObjectSubclass for SettingsDialog {
const NAME: &'static str = "SettingsWindow";
type Type = super::SettingsDialog;
type ParentType = libadwaita::PreferencesDialog;
fn class_init(klass: &mut Self::Class) {
klass.bind_template();
}
fn instance_init(obj: &glib::subclass::InitializingObject<Self>) {
obj.init_template();
}
}
impl ObjectImpl for SettingsDialog {}
impl WidgetImpl for SettingsDialog {}
impl AdwDialogImpl for SettingsDialog {}
impl PreferencesDialogImpl for SettingsDialog {}
}
glib::wrapper! {
pub struct SettingsDialog(ObjectSubclass<imp::SettingsDialog>) @extends gtk::Widget, libadwaita::Dialog, libadwaita::PreferencesDialog;
}
impl Default for SettingsDialog {
fn default() -> Self {
Self::new()
}
}
impl SettingsDialog {
pub fn new() -> Self {
let dialog: Self = glib::Object::new();
dialog.bind_backend_and_device();
dialog.bind_settings();
dialog.connect_theme_select();
dialog
}
fn bind_backend_and_device(&self) {
let widget = self.imp();
let audio_backend = widget
.audio_backend
.downcast_ref::<libadwaita::ComboRow>()
.unwrap();
let alsa_device_row = widget
.alsa_device_row
.downcast_ref::<libadwaita::ActionRow>()
.unwrap();
audio_backend
.bind_property("selected", alsa_device_row, "visible")
.transform_to(|_, value: u32| Some(value == 1))
.build();
if audio_backend.selected() == 0 {
alsa_device_row.set_visible(false);
}
}
fn bind_settings(&self) {
let widget = self.imp();
let settings = gio::Settings::new(SETTINGS);
let player_bitrate = widget
.player_bitrate
.downcast_ref::<libadwaita::ComboRow>()
.unwrap();
settings
.bind("player-bitrate", player_bitrate, "selected")
.mapping(|variant, _| {
variant.str().map(|s| {
match s {
"96" => 0,
"160" => 1,
"320" => 2,
_ => unreachable!(),
}
.to_value()
})
})
.set_mapping(|value, _| {
value.get::<u32>().ok().map(|u| {
match u {
0 => "96",
1 => "160",
2 => "320",
_ => unreachable!(),
}
.to_variant()
})
})
.build();
let alsa_device = widget.alsa_device.downcast_ref::<gtk::Entry>().unwrap();
settings.bind("alsa-device", alsa_device, "text").build();
let audio_backend = widget
.audio_backend
.downcast_ref::<libadwaita::ComboRow>()
.unwrap();
settings
.bind("audio-backend", audio_backend, "selected")
.mapping(|variant, _| {
variant.str().map(|s| {
match s {
"pulseaudio" => 0,
"alsa" => 1,
"gstreamer" => 2,
_ => unreachable!(),
}
.to_value()
})
})
.set_mapping(|value, _| {
value.get::<u32>().ok().map(|u| {
match u {
0 => "pulseaudio",
1 => "alsa",
2 => "gstreamer",
_ => unreachable!(),
}
.to_variant()
})
})
.build();
let gapless_playback = widget
.gapless_playback
.downcast_ref::<libadwaita::ActionRow>()
.unwrap();
settings
.bind(
"gapless-playback",
&gapless_playback.activatable_widget().unwrap(),
"active",
)
.build();
let ap_port = widget.ap_port.downcast_ref::<gtk::Entry>().unwrap();
settings
.bind("ap-port", ap_port, "text")
.mapping(|variant, _| variant.get::<u32>().map(|s| s.to_value()))
.set_mapping(|value, _| value.get::<u32>().ok().map(|u| u.to_variant()))
.build();
let theme = widget.theme.downcast_ref::<libadwaita::ComboRow>().unwrap();
settings
.bind("theme-preference", theme, "selected")
.mapping(|variant, _| {
variant.str().map(|s| {
match s {
"light" => 0,
"dark" => 1,
"system" => 2,
_ => unreachable!(),
}
.to_value()
})
})
.set_mapping(|value, _| {
value.get::<u32>().ok().map(|u| {
match u {
0 => "light",
1 => "dark",
2 => "system",
_ => unreachable!(),
}
.to_variant()
})
})
.build();
}
fn connect_theme_select(&self) {
let widget = self.imp();
let theme = widget.theme.downcast_ref::<libadwaita::ComboRow>().unwrap();
theme.connect_selected_notify(|theme| {
debug!("Theme switched! --> value: {}", theme.selected());
let manager = libadwaita::StyleManager::default();
let pref = match theme.selected() {
0 => libadwaita::ColorScheme::ForceLight,
1 => libadwaita::ColorScheme::ForceDark,
_ => libadwaita::ColorScheme::Default,
};
manager.set_color_scheme(pref);
});
}
fn connect_close<F>(&self, on_close: F)
where
F: Fn() + 'static,
{
let dialog = self.upcast_ref::<libadwaita::Dialog>();
dialog.connect_close_attempt(move |_| {
on_close();
});
}
}
pub struct Settings {
parent: gtk::Window,
settings_dialog: SettingsDialog,
}
impl Settings {
pub fn new(parent: gtk::Window, model: SettingsModel) -> Self {
let settings_dialog = SettingsDialog::new();
settings_dialog.connect_close(move || {
let new_settings = RiffSettings::new_from_gsettings().unwrap_or_default();
if model.settings().player_settings != new_settings.player_settings {
model.stop_player();
}
model.set_settings();
});
Self {
parent,
settings_dialog,
}
}
fn dialog(&self) -> &libadwaita::Dialog {
self.settings_dialog.upcast_ref::<libadwaita::Dialog>()
}
pub fn show_self(&self) {
self.dialog().present(Some(&self.parent));
}
}
impl EventListener for Settings {
fn on_event(&mut self, _: &AppEvent) {}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/settings/mod.rs | src/app/components/settings/mod.rs | #[allow(clippy::module_inception)]
mod settings;
mod settings_model;
pub use settings::*;
pub use settings_model::*;
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/album/album.rs | src/app/components/album/album.rs | use crate::app::components::display_add_css_provider;
use crate::app::dispatch::Worker;
use crate::app::loader::ImageLoader;
use crate::app::models::AlbumModel;
use gtk::prelude::*;
use gtk::subclass::prelude::*;
use gtk::CompositeTemplate;
use libadwaita::subclass::prelude::BinImpl;
mod imp {
use super::*;
#[derive(Debug, Default, CompositeTemplate)]
#[template(file = "src/app/components/album/album.blp")]
pub struct AlbumWidget {
#[template_child]
pub album_label: TemplateChild<gtk::Label>,
#[template_child]
pub artist_label: TemplateChild<gtk::Label>,
#[template_child]
pub year_label: TemplateChild<gtk::Label>,
#[template_child]
pub cover_btn: TemplateChild<gtk::Button>,
#[template_child]
pub cover_image: TemplateChild<gtk::Picture>,
}
#[glib::object_subclass]
impl ObjectSubclass for AlbumWidget {
const NAME: &'static str = "AlbumWidget";
type Type = super::AlbumWidget;
type ParentType = libadwaita::Bin;
fn class_init(klass: &mut Self::Class) {
klass.bind_template();
}
fn instance_init(obj: &glib::subclass::InitializingObject<Self>) {
obj.init_template();
}
}
impl ObjectImpl for AlbumWidget {}
impl WidgetImpl for AlbumWidget {}
impl BinImpl for AlbumWidget {}
}
glib::wrapper! {
pub struct AlbumWidget(ObjectSubclass<imp::AlbumWidget>) @extends gtk::Widget, libadwaita::Bin;
}
impl Default for AlbumWidget {
fn default() -> Self {
Self::new()
}
}
impl AlbumWidget {
pub fn new() -> Self {
display_add_css_provider(resource!("/components/album.css"));
glib::Object::new()
}
pub fn for_model(album_model: &AlbumModel, worker: Worker) -> Self {
let _self = Self::new();
_self.bind(album_model, worker);
_self
}
fn set_loaded(&self) {
self.add_css_class("container--loaded");
}
fn set_image(&self, pixbuf: &gdk_pixbuf::Pixbuf) {
let texture = gdk::Texture::for_pixbuf(pixbuf);
self.imp().cover_image.set_paintable(Some(&texture));
}
fn bind(&self, album_model: &AlbumModel, worker: Worker) {
let widget = self.imp();
widget.cover_image.set_overflow(gtk::Overflow::Hidden);
if let Some(cover_art) = album_model.cover() {
let _self = self.downgrade();
worker.send_local_task(async move {
if let Some(_self) = _self.upgrade() {
let loader = ImageLoader::new();
let result = loader.load_remote(&cover_art, "jpg", 200, 200).await;
if let Some(image) = result.as_ref() {
_self.set_image(image);
_self.set_loaded();
}
}
});
} else {
self.set_loaded();
}
album_model
.bind_property("album", &*widget.album_label, "label")
.flags(glib::BindingFlags::DEFAULT | glib::BindingFlags::SYNC_CREATE)
.build();
album_model
.bind_property("artist", &*widget.artist_label, "label")
.flags(glib::BindingFlags::DEFAULT | glib::BindingFlags::SYNC_CREATE)
.build();
if album_model.year() > 0 {
album_model
.bind_property("year", &*widget.year_label, "label")
.flags(glib::BindingFlags::DEFAULT | glib::BindingFlags::SYNC_CREATE)
.build();
} else {
widget.year_label.set_visible(false);
}
}
pub fn connect_album_pressed<F: Fn() + 'static>(&self, f: F) {
self.imp().cover_btn.connect_clicked(move |_| {
f();
});
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/album/mod.rs | src/app/components/album/mod.rs | #[allow(clippy::module_inception)]
mod album;
pub use album::AlbumWidget;
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/notification/mod.rs | src/app/components/notification/mod.rs | use crate::app::components::EventListener;
use crate::app::AppEvent;
use gdk::prelude::ToVariant;
use gettextrs::*;
pub struct Notification {
toast_overlay: libadwaita::ToastOverlay,
}
impl Notification {
pub fn new(toast_overlay: libadwaita::ToastOverlay) -> Self {
Self { toast_overlay }
}
fn show(&self, content: &str) {
let toast = libadwaita::Toast::builder()
.title(content)
.timeout(4)
.build();
self.toast_overlay.add_toast(toast);
}
fn show_playlist_created(&self, id: &str) {
// translators: This is a notification that pop ups when a new playlist is created. It includes the name of that playlist.
let message = gettext("New playlist created.");
// translators: This is a label in the notification shown after creating a new playlist. If it is clicked, the new playlist will be opened.
let label = gettext("View");
let toast = libadwaita::Toast::builder()
.title(message)
.timeout(4)
.action_name("app.open_playlist")
.button_label(label)
.action_target(&id.to_variant())
.build();
self.toast_overlay.add_toast(toast);
}
}
impl EventListener for Notification {
fn on_event(&mut self, event: &AppEvent) {
if let AppEvent::NotificationShown(content) = event {
self.show(content)
} else if let AppEvent::PlaylistCreatedNotificationShown(id) = event {
self.show_playlist_created(id)
}
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/saved_playlists/saved_playlists_model.rs | src/app/components/saved_playlists/saved_playlists_model.rs | use std::cell::Ref;
use std::ops::Deref;
use std::rc::Rc;
use crate::app::models::*;
use crate::app::state::HomeState;
use crate::app::{ActionDispatcher, AppAction, AppModel, BrowserAction, ListStore};
pub struct SavedPlaylistsModel {
app_model: Rc<AppModel>,
dispatcher: Box<dyn ActionDispatcher>,
}
impl SavedPlaylistsModel {
pub fn new(app_model: Rc<AppModel>, dispatcher: Box<dyn ActionDispatcher>) -> Self {
Self {
app_model,
dispatcher,
}
}
fn state(&self) -> Option<Ref<'_, HomeState>> {
self.app_model.map_state_opt(|s| s.browser.home_state())
}
pub fn get_list_store(&self) -> Option<impl Deref<Target = ListStore<AlbumModel>> + '_> {
Some(Ref::map(self.state()?, |s| &s.playlists))
}
pub fn refresh_saved_playlists(&self) -> Option<()> {
let api = self.app_model.get_spotify();
let batch_size = self.state()?.next_playlists_page.batch_size;
self.dispatcher
.call_spotify_and_dispatch(move || async move {
api.get_saved_playlists(0, batch_size)
.await
.map(|playlists| BrowserAction::SetPlaylistsContent(playlists).into())
});
Some(())
}
pub fn has_playlists(&self) -> bool {
self.get_list_store()
.map(|list| list.len() > 0)
.unwrap_or(false)
}
pub fn load_more_playlists(&self) -> Option<()> {
let api = self.app_model.get_spotify();
let next_page = &self.state()?.next_playlists_page;
let batch_size = next_page.batch_size;
let offset = next_page.next_offset?;
self.dispatcher
.call_spotify_and_dispatch(move || async move {
api.get_saved_playlists(offset, batch_size)
.await
.map(|playlists| BrowserAction::AppendPlaylistsContent(playlists).into())
});
Some(())
}
pub fn open_playlist(&self, id: String) {
self.dispatcher.dispatch(AppAction::ViewPlaylist(id));
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/saved_playlists/saved_playlists.rs | src/app/components/saved_playlists/saved_playlists.rs | use gtk::prelude::*;
use gtk::subclass::prelude::*;
use gtk::CompositeTemplate;
use std::rc::Rc;
use super::SavedPlaylistsModel;
use crate::app::components::{AlbumWidget, Component, EventListener};
use crate::app::dispatch::Worker;
use crate::app::models::AlbumModel;
use crate::app::state::LoginEvent;
use crate::app::{AppEvent, BrowserEvent, ListStore};
mod imp {
use super::*;
#[derive(Debug, Default, CompositeTemplate)]
#[template(resource = "/dev/diegovsky/Riff/components/saved_playlists.ui")]
pub struct SavedPlaylistsWidget {
#[template_child]
pub scrolled_window: TemplateChild<gtk::ScrolledWindow>,
#[template_child]
pub flowbox: TemplateChild<gtk::FlowBox>,
#[template_child]
pub status_page: TemplateChild<libadwaita::StatusPage>,
}
#[glib::object_subclass]
impl ObjectSubclass for SavedPlaylistsWidget {
const NAME: &'static str = "SavedPlaylistsWidget";
type Type = super::SavedPlaylistsWidget;
type ParentType = gtk::Box;
fn class_init(klass: &mut Self::Class) {
klass.bind_template();
}
fn instance_init(obj: &glib::subclass::InitializingObject<Self>) {
obj.init_template();
}
}
impl ObjectImpl for SavedPlaylistsWidget {}
impl WidgetImpl for SavedPlaylistsWidget {}
impl BoxImpl for SavedPlaylistsWidget {}
}
glib::wrapper! {
pub struct SavedPlaylistsWidget(ObjectSubclass<imp::SavedPlaylistsWidget>) @extends gtk::Widget, gtk::Box;
}
impl Default for SavedPlaylistsWidget {
fn default() -> Self {
Self::new()
}
}
impl SavedPlaylistsWidget {
pub fn new() -> Self {
glib::Object::new()
}
fn connect_bottom_edge<F>(&self, f: F)
where
F: Fn() + 'static,
{
self.imp()
.scrolled_window
.connect_edge_reached(move |_, pos| {
if let gtk::PositionType::Bottom = pos {
f()
}
});
}
fn bind_albums<F>(&self, worker: Worker, store: &ListStore<AlbumModel>, on_album_pressed: F)
where
F: Fn(String) + Clone + 'static,
{
self.imp()
.flowbox
.bind_model(Some(store.inner()), move |item| {
let album_model = item.downcast_ref::<AlbumModel>().unwrap();
let child = gtk::FlowBoxChild::new();
let album = AlbumWidget::for_model(album_model, worker.clone());
let f = on_album_pressed.clone();
album.connect_album_pressed(clone!(
#[weak]
album_model,
move || {
f(album_model.uri());
}
));
child.set_child(Some(&album));
child.upcast::<gtk::Widget>()
});
}
pub fn get_status_page(&self) -> &libadwaita::StatusPage {
&self.imp().status_page
}
}
pub struct SavedPlaylists {
widget: SavedPlaylistsWidget,
worker: Worker,
model: Rc<SavedPlaylistsModel>,
}
impl SavedPlaylists {
pub fn new(worker: Worker, model: SavedPlaylistsModel) -> Self {
let model = Rc::new(model);
let widget = SavedPlaylistsWidget::new();
widget.connect_bottom_edge(clone!(
#[weak]
model,
move || {
model.load_more_playlists();
}
));
Self {
widget,
worker,
model,
}
}
fn bind_flowbox(&self) {
self.widget.bind_albums(
self.worker.clone(),
&self.model.get_list_store().unwrap(),
clone!(
#[weak(rename_to = model)]
self.model,
move |id| {
model.open_playlist(id);
}
),
);
}
}
impl EventListener for SavedPlaylists {
fn on_event(&mut self, event: &AppEvent) {
match event {
AppEvent::Started => {
let _ = self.model.refresh_saved_playlists();
self.bind_flowbox();
}
AppEvent::LoginEvent(LoginEvent::LoginCompleted) => {
let _ = self.model.refresh_saved_playlists();
}
AppEvent::BrowserEvent(BrowserEvent::SavedPlaylistsUpdated) => {
self.widget
.get_status_page()
.set_visible(!self.model.has_playlists());
}
_ => {}
}
}
}
impl Component for SavedPlaylists {
fn get_root_widget(&self) -> >k::Widget {
self.widget.as_ref()
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/saved_playlists/mod.rs | src/app/components/saved_playlists/mod.rs | #[allow(clippy::module_inception)]
mod saved_playlists;
mod saved_playlists_model;
pub use saved_playlists::*;
pub use saved_playlists_model::*;
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/library/library.rs | src/app/components/library/library.rs | use gtk::prelude::*;
use gtk::subclass::prelude::*;
use gtk::CompositeTemplate;
use std::rc::Rc;
use super::LibraryModel;
use crate::app::components::utils::wrap_flowbox_item;
use crate::app::components::{AlbumWidget, Component, EventListener};
use crate::app::dispatch::Worker;
use crate::app::models::AlbumModel;
use crate::app::state::LoginEvent;
use crate::app::{AppEvent, BrowserEvent, ListStore};
mod imp {
use super::*;
#[derive(Debug, Default, CompositeTemplate)]
#[template(resource = "/dev/diegovsky/Riff/components/library.ui")]
pub struct LibraryWidget {
#[template_child]
pub scrolled_window: TemplateChild<gtk::ScrolledWindow>,
#[template_child]
pub flowbox: TemplateChild<gtk::FlowBox>,
#[template_child]
pub status_page: TemplateChild<libadwaita::StatusPage>,
}
#[glib::object_subclass]
impl ObjectSubclass for LibraryWidget {
const NAME: &'static str = "LibraryWidget";
type Type = super::LibraryWidget;
type ParentType = gtk::Box;
fn class_init(klass: &mut Self::Class) {
klass.bind_template();
}
fn instance_init(obj: &glib::subclass::InitializingObject<Self>) {
obj.init_template();
}
}
impl ObjectImpl for LibraryWidget {}
impl WidgetImpl for LibraryWidget {}
impl BoxImpl for LibraryWidget {}
}
glib::wrapper! {
pub struct LibraryWidget(ObjectSubclass<imp::LibraryWidget>) @extends gtk::Widget, gtk::Box;
}
impl Default for LibraryWidget {
fn default() -> Self {
Self::new()
}
}
impl LibraryWidget {
pub fn new() -> Self {
glib::Object::new()
}
fn connect_bottom_edge<F>(&self, f: F)
where
F: Fn() + 'static,
{
self.imp()
.scrolled_window
.connect_edge_reached(move |_, pos| {
if let gtk::PositionType::Bottom = pos {
f()
}
});
}
fn bind_albums<F>(&self, worker: Worker, store: &ListStore<AlbumModel>, on_album_pressed: F)
where
F: Fn(String) + Clone + 'static,
{
self.imp()
.flowbox
.bind_model(Some(store.inner()), move |item| {
wrap_flowbox_item(item, |album_model| {
let f = on_album_pressed.clone();
let album = AlbumWidget::for_model(album_model, worker.clone());
album.connect_album_pressed(clone!(
#[weak]
album_model,
move || {
f(album_model.uri());
}
));
album
})
});
}
pub fn status_page(&self) -> &libadwaita::StatusPage {
&self.imp().status_page
}
}
pub struct Library {
widget: LibraryWidget,
worker: Worker,
model: Rc<LibraryModel>,
}
impl Library {
pub fn new(worker: Worker, model: LibraryModel) -> Self {
let model = Rc::new(model);
let widget = LibraryWidget::new();
widget.connect_bottom_edge(clone!(
#[weak]
model,
move || {
model.load_more_albums();
}
));
Self {
widget,
worker,
model,
}
}
fn bind_flowbox(&self) {
self.widget.bind_albums(
self.worker.clone(),
&self.model.get_list_store().unwrap(),
clone!(
#[weak(rename_to = model)]
self.model,
move |id| {
model.open_album(id);
}
),
);
}
}
impl EventListener for Library {
fn on_event(&mut self, event: &AppEvent) {
match event {
AppEvent::Started => {
let _ = self.model.refresh_saved_albums();
self.bind_flowbox();
}
AppEvent::LoginEvent(LoginEvent::LoginCompleted) => {
let _ = self.model.refresh_saved_albums();
}
AppEvent::BrowserEvent(BrowserEvent::LibraryUpdated) => {
self.widget
.status_page()
.set_visible(!self.model.has_albums());
}
_ => {}
}
}
}
impl Component for Library {
fn get_root_widget(&self) -> >k::Widget {
self.widget.as_ref()
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/library/library_model.rs | src/app/components/library/library_model.rs | use std::cell::Ref;
use std::ops::Deref;
use std::rc::Rc;
use crate::app::models::*;
use crate::app::state::HomeState;
use crate::app::{ActionDispatcher, AppAction, AppModel, BrowserAction, ListStore};
pub struct LibraryModel {
app_model: Rc<AppModel>,
dispatcher: Box<dyn ActionDispatcher>,
}
impl LibraryModel {
pub fn new(app_model: Rc<AppModel>, dispatcher: Box<dyn ActionDispatcher>) -> Self {
Self {
app_model,
dispatcher,
}
}
fn state(&self) -> Option<Ref<'_, HomeState>> {
self.app_model.map_state_opt(|s| s.browser.home_state())
}
pub fn get_list_store(&self) -> Option<impl Deref<Target = ListStore<AlbumModel>> + '_> {
Some(Ref::map(self.state()?, |s| &s.albums))
}
pub fn refresh_saved_albums(&self) -> Option<()> {
let api = self.app_model.get_spotify();
let batch_size = self.state()?.next_albums_page.batch_size;
self.dispatcher
.call_spotify_and_dispatch(move || async move {
api.get_saved_albums(0, batch_size)
.await
.map(|albums| BrowserAction::SetLibraryContent(albums).into())
});
Some(())
}
pub fn has_albums(&self) -> bool {
self.get_list_store()
.map(|list| list.len() > 0)
.unwrap_or(false)
}
pub fn load_more_albums(&self) -> Option<()> {
let api = self.app_model.get_spotify();
let next_page = &self.state()?.next_albums_page;
let batch_size = next_page.batch_size;
let offset = next_page.next_offset?;
self.dispatcher
.call_spotify_and_dispatch(move || async move {
api.get_saved_albums(offset, batch_size)
.await
.map(|albums| BrowserAction::AppendLibraryContent(albums).into())
});
Some(())
}
pub fn open_album(&self, album_id: String) {
self.dispatcher.dispatch(AppAction::ViewAlbum(album_id));
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/library/mod.rs | src/app/components/library/mod.rs | #[allow(clippy::module_inception)]
mod library;
mod library_model;
pub use library::*;
pub use library_model::*;
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/headerbar/widget.rs | src/app/components/headerbar/widget.rs | use gtk::prelude::*;
use gtk::subclass::prelude::*;
use gtk::CompositeTemplate;
use libadwaita::subclass::prelude::BinImpl;
use crate::app::components::labels;
mod imp {
use super::*;
#[derive(Debug, Default, CompositeTemplate)]
#[template(resource = "/dev/diegovsky/Riff/components/headerbar.ui")]
pub struct HeaderBarWidget {
#[template_child]
pub main_header: TemplateChild<libadwaita::HeaderBar>,
#[template_child]
pub selection_header: TemplateChild<libadwaita::HeaderBar>,
#[template_child]
pub go_back: TemplateChild<gtk::Button>,
#[template_child]
pub title: TemplateChild<libadwaita::WindowTitle>,
#[template_child]
pub selection_title: TemplateChild<libadwaita::WindowTitle>,
#[template_child]
pub start_selection: TemplateChild<gtk::Button>,
#[template_child]
pub select_all: TemplateChild<gtk::Button>,
#[template_child]
pub cancel: TemplateChild<gtk::Button>,
#[template_child]
pub overlay: TemplateChild<gtk::Overlay>,
}
#[glib::object_subclass]
impl ObjectSubclass for HeaderBarWidget {
const NAME: &'static str = "HeaderBarWidget";
type Type = super::HeaderBarWidget;
type ParentType = libadwaita::Bin;
type Interfaces = (gtk::Buildable,);
fn class_init(klass: &mut Self::Class) {
klass.bind_template();
}
fn instance_init(obj: &glib::subclass::InitializingObject<Self>) {
obj.init_template();
}
}
impl ObjectImpl for HeaderBarWidget {}
impl BuildableImpl for HeaderBarWidget {
fn add_child(&self, builder: >k::Builder, child: &glib::Object, type_: Option<&str>) {
if Some("root") == type_ {
self.parent_add_child(builder, child, type_);
} else {
self.main_header
.set_title_widget(child.downcast_ref::<gtk::Widget>());
}
}
}
impl WidgetImpl for HeaderBarWidget {}
impl BinImpl for HeaderBarWidget {}
impl WindowImpl for HeaderBarWidget {}
}
glib::wrapper! {
pub struct HeaderBarWidget(ObjectSubclass<imp::HeaderBarWidget>) @extends gtk::Widget, libadwaita::Bin;
}
impl Default for HeaderBarWidget {
fn default() -> Self {
Self::new()
}
}
impl HeaderBarWidget {
pub fn new() -> Self {
glib::Object::new()
}
pub fn connect_selection_start<F>(&self, f: F)
where
F: Fn() + 'static,
{
self.imp().start_selection.connect_clicked(move |_| f());
}
pub fn connect_select_all<F>(&self, f: F)
where
F: Fn() + 'static,
{
self.imp().select_all.connect_clicked(move |_| f());
}
pub fn connect_selection_cancel<F>(&self, f: F)
where
F: Fn() + 'static,
{
self.imp().cancel.connect_clicked(move |_| f());
}
pub fn connect_go_back<F>(&self, f: F)
where
F: Fn() + 'static,
{
self.imp().go_back.connect_clicked(move |_| f());
}
pub fn set_can_go_back(&self, can_go_back: bool) {
self.imp().go_back.set_visible(can_go_back);
}
pub fn set_selection_possible(&self, possible: bool) {
self.imp().start_selection.set_visible(possible);
}
pub fn set_select_all_possible(&self, possible: bool) {
self.imp().select_all.set_visible(possible);
}
pub fn set_selection_active(&self, active: bool) {
if active {
self.imp()
.selection_title
.set_title(&labels::n_songs_selected_label(0));
self.imp().selection_title.set_visible(true);
self.imp().selection_header.set_visible(true);
} else {
self.imp().selection_title.set_visible(false);
self.imp().selection_header.set_visible(false);
}
}
pub fn set_selection_count(&self, count: usize) {
self.imp()
.selection_title
.set_title(&labels::n_songs_selected_label(count));
}
pub fn add_classes(&self, classes: &[&str]) {
for &class in classes {
self.imp().main_header.add_css_class(class);
}
}
pub fn remove_classes(&self, classes: &[&str]) {
for &class in classes {
self.imp().main_header.remove_css_class(class);
}
}
pub fn set_title_visible(&self, visible: bool) {
self.imp().title.set_visible(visible);
}
pub fn set_title_and_subtitle(&self, title: &str, subtitle: &str) {
self.imp().title.set_title(title);
self.imp().title.set_subtitle(subtitle);
}
pub fn set_title(&self, title: Option<&str>) {
self.imp().title.set_visible(title.is_some());
if let Some(title) = title {
self.imp().title.set_title(title);
}
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/headerbar/mod.rs | src/app/components/headerbar/mod.rs | mod widget;
pub use widget::*;
mod component;
pub use component::*;
use glib::prelude::*;
pub fn expose_widgets() {
widget::HeaderBarWidget::static_type();
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/headerbar/component.rs | src/app/components/headerbar/component.rs | use std::rc::Rc;
use gtk::prelude::*;
use crate::app::{
components::{Component, EventListener, ListenerComponent},
state::{SelectionContext, SelectionEvent},
ActionDispatcher, AppAction, AppEvent, AppModel, BrowserAction, BrowserEvent,
};
use super::widget::HeaderBarWidget;
pub trait HeaderBarModel {
fn title(&self) -> Option<String>;
fn title_updated(&self, event: &AppEvent) -> bool;
fn go_back(&self);
fn can_go_back(&self) -> bool;
fn selection_context(&self) -> Option<SelectionContext>;
fn can_select_all(&self) -> bool;
fn start_selection(&self);
fn select_all(&self);
fn cancel_selection(&self);
fn selected_count(&self) -> usize;
}
pub struct DefaultHeaderBarModel {
title: Option<String>,
selection_context: Option<SelectionContext>,
app_model: Rc<AppModel>,
dispatcher: Box<dyn ActionDispatcher>,
}
impl DefaultHeaderBarModel {
pub fn new(
title: Option<String>,
selection_context: Option<SelectionContext>,
app_model: Rc<AppModel>,
dispatcher: Box<dyn ActionDispatcher>,
) -> Self {
Self {
title,
selection_context,
app_model,
dispatcher,
}
}
}
impl HeaderBarModel for DefaultHeaderBarModel {
fn title(&self) -> Option<String> {
self.title.clone()
}
fn title_updated(&self, _: &AppEvent) -> bool {
false
}
fn go_back(&self) {
self.dispatcher
.dispatch(BrowserAction::NavigationPop.into())
}
fn can_go_back(&self) -> bool {
self.app_model.get_state().browser.can_pop()
}
fn selection_context(&self) -> Option<SelectionContext> {
self.selection_context.clone()
}
fn can_select_all(&self) -> bool {
false
}
fn start_selection(&self) {
if let Some(context) = self.selection_context.as_ref() {
self.dispatcher
.dispatch(AppAction::EnableSelection(context.clone()))
}
}
fn select_all(&self) {}
fn cancel_selection(&self) {
self.dispatcher.dispatch(AppAction::CancelSelection)
}
fn selected_count(&self) -> usize {
self.app_model.get_state().selection.count()
}
}
pub trait SimpleHeaderBarModel {
fn title(&self) -> Option<String>;
fn title_updated(&self, event: &AppEvent) -> bool;
fn selection_context(&self) -> Option<SelectionContext>;
fn select_all(&self);
}
pub struct SimpleHeaderBarModelWrapper<M> {
wrapped_model: Rc<M>,
app_model: Rc<AppModel>,
dispatcher: Box<dyn ActionDispatcher>,
}
impl<M> SimpleHeaderBarModelWrapper<M> {
pub fn new(
wrapped_model: Rc<M>,
app_model: Rc<AppModel>,
dispatcher: Box<dyn ActionDispatcher>,
) -> Self {
Self {
wrapped_model,
app_model,
dispatcher,
}
}
}
impl<M> HeaderBarModel for SimpleHeaderBarModelWrapper<M>
where
M: SimpleHeaderBarModel + 'static,
{
fn title(&self) -> Option<String> {
self.wrapped_model.title()
}
fn title_updated(&self, event: &AppEvent) -> bool {
self.wrapped_model.title_updated(event)
}
fn go_back(&self) {
self.dispatcher
.dispatch(BrowserAction::NavigationPop.into())
}
fn can_go_back(&self) -> bool {
self.app_model.get_state().browser.can_pop()
}
fn selection_context(&self) -> Option<SelectionContext> {
self.wrapped_model.selection_context()
}
fn can_select_all(&self) -> bool {
true
}
fn start_selection(&self) {
if let Some(context) = self.wrapped_model.selection_context() {
self.dispatcher
.dispatch(AppAction::EnableSelection(context));
}
}
fn select_all(&self) {
self.wrapped_model.select_all()
}
fn cancel_selection(&self) {
self.dispatcher.dispatch(AppAction::CancelSelection)
}
fn selected_count(&self) -> usize {
self.app_model.get_state().selection.count()
}
}
mod common {
use super::*;
pub fn update_for_event<Model>(event: &AppEvent, widget: &HeaderBarWidget, model: &Rc<Model>)
where
Model: HeaderBarModel + 'static,
{
match event {
AppEvent::SelectionEvent(SelectionEvent::SelectionModeChanged(active)) => {
widget.set_selection_active(*active);
}
AppEvent::SelectionEvent(SelectionEvent::SelectionChanged) => {
widget.set_selection_count(model.selected_count());
}
AppEvent::BrowserEvent(BrowserEvent::NavigationPushed(_))
| AppEvent::BrowserEvent(BrowserEvent::NavigationPoppedTo(_))
| AppEvent::BrowserEvent(BrowserEvent::NavigationPopped)
| AppEvent::BrowserEvent(BrowserEvent::NavigationHidden(_)) => {
model.cancel_selection();
widget.set_can_go_back(model.can_go_back());
}
event if model.title_updated(event) => {
widget.set_title(model.title().as_ref().map(|s| &s[..]));
}
_ => {}
}
}
pub fn bind_headerbar<Model>(widget: &HeaderBarWidget, model: &Rc<Model>)
where
Model: HeaderBarModel + 'static,
{
widget.connect_selection_start(clone!(
#[weak]
model,
move || model.start_selection()
));
widget.connect_select_all(clone!(
#[weak]
model,
move || model.select_all()
));
widget.connect_selection_cancel(clone!(
#[weak]
model,
move || model.cancel_selection()
));
widget.connect_go_back(clone!(
#[weak]
model,
move || model.go_back()
));
widget.set_title(model.title().as_ref().map(|s| &s[..]));
widget.set_selection_possible(model.selection_context().is_some());
widget.set_select_all_possible(model.can_select_all());
widget.set_can_go_back(model.can_go_back());
}
}
pub struct HeaderBarComponent<Model: HeaderBarModel> {
widget: HeaderBarWidget,
model: Rc<Model>,
}
impl<Model> HeaderBarComponent<Model>
where
Model: HeaderBarModel + 'static,
{
pub fn new(widget: HeaderBarWidget, model: Rc<Model>) -> Self {
common::bind_headerbar(&widget, &model);
Self { widget, model }
}
}
impl<Model> EventListener for HeaderBarComponent<Model>
where
Model: HeaderBarModel + 'static,
{
fn on_event(&mut self, event: &AppEvent) {
common::update_for_event(event, &self.widget, &self.model);
}
}
// wrapper version ("Screen")
pub struct StandardScreen<Model: HeaderBarModel> {
root: gtk::Widget,
widget: HeaderBarWidget,
model: Rc<Model>,
children: Vec<Box<dyn EventListener>>,
}
impl<Model> StandardScreen<Model>
where
Model: HeaderBarModel + 'static,
{
pub fn new(wrapped: impl ListenerComponent + 'static, model: Rc<Model>) -> Self {
let widget = HeaderBarWidget::new();
common::bind_headerbar(&widget, &model);
let root = gtk::Box::builder()
.orientation(gtk::Orientation::Vertical)
.build();
root.append(&widget);
root.append(wrapped.get_root_widget());
Self {
root: root.upcast(),
widget,
model,
children: vec![Box::new(wrapped)],
}
}
}
impl<Model> Component for StandardScreen<Model>
where
Model: HeaderBarModel + 'static,
{
fn get_root_widget(&self) -> >k::Widget {
&self.root
}
fn get_children(&mut self) -> Option<&mut Vec<Box<dyn EventListener>>> {
Some(&mut self.children)
}
}
impl<Model> EventListener for StandardScreen<Model>
where
Model: HeaderBarModel + 'static,
{
fn on_event(&mut self, event: &AppEvent) {
common::update_for_event(event, &self.widget, &self.model);
self.broadcast_event(event);
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/artist_details/artist_details_model.rs | src/app/components/artist_details/artist_details_model.rs | use gio::prelude::*;
use gio::SimpleActionGroup;
use std::ops::Deref;
use std::rc::Rc;
use crate::api::SpotifyApiError;
use crate::app::components::SimpleHeaderBarModel;
use crate::app::components::{labels, PlaylistModel};
use crate::app::models::*;
use crate::app::state::SelectionContext;
use crate::app::state::{
BrowserAction, BrowserEvent, PlaybackAction, SelectionAction, SelectionState,
};
use crate::app::{ActionDispatcher, AppAction, AppEvent, AppModel, ListStore};
pub struct ArtistDetailsModel {
pub id: String,
app_model: Rc<AppModel>,
dispatcher: Box<dyn ActionDispatcher>,
}
impl ArtistDetailsModel {
pub fn new(id: String, app_model: Rc<AppModel>, dispatcher: Box<dyn ActionDispatcher>) -> Self {
Self {
id,
app_model,
dispatcher,
}
}
pub fn get_artist_name(&self) -> Option<impl Deref<Target = String> + '_> {
self.app_model
.map_state_opt(|s| s.browser.artist_state(&self.id)?.artist.as_ref())
}
pub fn get_list_store(&self) -> Option<impl Deref<Target = ListStore<AlbumModel>> + '_> {
self.app_model
.map_state_opt(|s| Some(&s.browser.artist_state(&self.id)?.albums))
}
pub fn load_artist_details(&self, id: String) {
let api = self.app_model.get_spotify();
self.dispatcher
.call_spotify_and_dispatch(move || async move {
let artist = api.get_artist(&id).await;
match artist {
Ok(artist) => Ok(BrowserAction::SetArtistDetails(Box::new(artist)).into()),
Err(SpotifyApiError::BadStatus(400, _))
| Err(SpotifyApiError::BadStatus(404, _)) => {
Ok(BrowserAction::NavigationPop.into())
}
Err(e) => Err(e),
}
});
}
pub fn open_album(&self, id: String) {
self.dispatcher.dispatch(AppAction::ViewAlbum(id));
}
pub fn load_more(&self) -> Option<()> {
let api = self.app_model.get_spotify();
let state = self.app_model.get_state();
let next_page = &state.browser.artist_state(&self.id)?.next_page;
let id = next_page.data.clone();
let batch_size = next_page.batch_size;
let offset = next_page.next_offset?;
self.dispatcher
.call_spotify_and_dispatch(move || async move {
api.get_artist_albums(&id, offset, batch_size)
.await
.map(|albums| BrowserAction::AppendArtistReleases(id, albums).into())
});
Some(())
}
}
impl PlaylistModel for ArtistDetailsModel {
fn song_list_model(&self) -> SongListModel {
self.app_model
.get_state()
.browser
.artist_state(&self.id)
.expect("illegal attempt to read artist_state")
.top_tracks
.clone()
}
fn is_paused(&self) -> bool {
!self.app_model.get_state().playback.is_playing()
}
fn current_song_id(&self) -> Option<String> {
self.app_model.get_state().playback.current_song_id()
}
fn play_song_at(&self, _pos: usize, id: &str) {
let tracks: Vec<SongDescription> = self.song_list_model().collect();
self.dispatcher
.dispatch(PlaybackAction::LoadSongs(tracks).into());
self.dispatcher
.dispatch(PlaybackAction::Load(id.to_string()).into());
}
fn actions_for(&self, id: &str) -> Option<gio::ActionGroup> {
let song = self.song_list_model().get(id)?;
let song = song.description();
let group = SimpleActionGroup::new();
for view_artist in song.make_artist_actions(self.dispatcher.box_clone(), None) {
group.add_action(&view_artist);
}
group.add_action(&song.make_album_action(self.dispatcher.box_clone(), None));
group.add_action(&song.make_link_action(None));
group.add_action(&song.make_queue_action(self.dispatcher.box_clone(), None));
Some(group.upcast())
}
fn menu_for(&self, id: &str) -> Option<gio::MenuModel> {
let song = self.song_list_model().get(id)?;
let song = song.description();
let menu = gio::Menu::new();
menu.append(Some(&*labels::VIEW_ALBUM), Some("song.view_album"));
for artist in song.artists.iter().filter(|a| self.id != a.id) {
menu.append(
Some(&labels::more_from_label(&artist.name)),
Some(&format!("song.view_artist_{}", artist.id)),
);
}
menu.append(Some(&*labels::COPY_LINK), Some("song.copy_link"));
menu.append(Some(&*labels::ADD_TO_QUEUE), Some("song.queue"));
Some(menu.upcast())
}
fn select_song(&self, id: &str) {
let song = self.song_list_model().get(id);
if let Some(song) = song {
self.dispatcher
.dispatch(SelectionAction::Select(vec![song.into_description()]).into());
}
}
fn deselect_song(&self, id: &str) {
self.dispatcher
.dispatch(SelectionAction::Deselect(vec![id.to_string()]).into());
}
fn enable_selection(&self) -> bool {
self.dispatcher
.dispatch(AppAction::EnableSelection(SelectionContext::Default));
true
}
fn selection(&self) -> Option<Box<dyn Deref<Target = SelectionState> + '_>> {
Some(Box::new(self.app_model.map_state(|s| &s.selection)))
}
}
impl SimpleHeaderBarModel for ArtistDetailsModel {
fn title(&self) -> Option<String> {
Some(self.get_artist_name()?.clone())
}
fn title_updated(&self, event: &AppEvent) -> bool {
matches!(
event,
AppEvent::BrowserEvent(BrowserEvent::ArtistDetailsUpdated(_))
)
}
fn selection_context(&self) -> Option<SelectionContext> {
Some(SelectionContext::Default)
}
fn select_all(&self) {
let songs: Vec<SongDescription> = self.song_list_model().collect();
self.dispatcher
.dispatch(SelectionAction::Select(songs).into());
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/artist_details/mod.rs | src/app/components/artist_details/mod.rs | #[allow(clippy::module_inception)]
mod artist_details;
pub use artist_details::*;
mod artist_details_model;
pub use artist_details_model::*;
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/artist_details/artist_details.rs | src/app/components/artist_details/artist_details.rs | use gtk::prelude::*;
use gtk::subclass::prelude::*;
use gtk::CompositeTemplate;
use std::rc::Rc;
use crate::app::components::{
display_add_css_provider, AlbumWidget, Component, EventListener, Playlist,
};
use crate::app::{models::*, ListStore};
use crate::app::{AppEvent, BrowserEvent, Worker};
use super::ArtistDetailsModel;
mod imp {
use super::*;
#[derive(Debug, Default, CompositeTemplate)]
#[template(resource = "/dev/diegovsky/Riff/components/artist_details.ui")]
pub struct ArtistDetailsWidget {
#[template_child]
pub scrolled_window: TemplateChild<gtk::ScrolledWindow>,
#[template_child]
pub top_tracks: TemplateChild<gtk::ListView>,
#[template_child]
pub artist_releases: TemplateChild<gtk::FlowBox>,
}
#[glib::object_subclass]
impl ObjectSubclass for ArtistDetailsWidget {
const NAME: &'static str = "ArtistDetailsWidget";
type Type = super::ArtistDetailsWidget;
type ParentType = gtk::Box;
fn class_init(klass: &mut Self::Class) {
klass.bind_template();
}
fn instance_init(obj: &glib::subclass::InitializingObject<Self>) {
obj.init_template();
}
}
impl ObjectImpl for ArtistDetailsWidget {}
impl WidgetImpl for ArtistDetailsWidget {}
impl BoxImpl for ArtistDetailsWidget {}
}
glib::wrapper! {
pub struct ArtistDetailsWidget(ObjectSubclass<imp::ArtistDetailsWidget>) @extends gtk::Widget, gtk::Box;
}
impl ArtistDetailsWidget {
fn new() -> Self {
display_add_css_provider(resource!("/components/artist_details.css"));
glib::Object::new()
}
fn top_tracks_widget(&self) -> >k::ListView {
self.imp().top_tracks.as_ref()
}
fn set_loaded(&self) {
self.add_css_class("artist__loaded");
}
fn connect_bottom_edge<F>(&self, f: F)
where
F: Fn() + 'static,
{
self.imp()
.scrolled_window
.connect_edge_reached(move |_, pos| {
if let gtk::PositionType::Bottom = pos {
f()
}
});
}
fn bind_artist_releases<F>(
&self,
worker: Worker,
store: &ListStore<AlbumModel>,
on_album_pressed: F,
) where
F: Fn(String) + Clone + 'static,
{
self.imp()
.artist_releases
.bind_model(Some(store.inner()), move |item| {
let item = item.downcast_ref::<AlbumModel>().unwrap();
let child = gtk::FlowBoxChild::new();
let album = AlbumWidget::for_model(item, worker.clone());
let f = on_album_pressed.clone();
album.connect_album_pressed(clone!(
#[weak]
item,
move || {
f(item.uri());
}
));
child.set_child(Some(&album));
child.upcast::<gtk::Widget>()
});
}
}
pub struct ArtistDetails {
model: Rc<ArtistDetailsModel>,
widget: ArtistDetailsWidget,
children: Vec<Box<dyn EventListener>>,
}
impl ArtistDetails {
pub fn new(model: Rc<ArtistDetailsModel>, worker: Worker) -> Self {
model.load_artist_details(model.id.clone());
let widget = ArtistDetailsWidget::new();
widget.connect_bottom_edge(clone!(
#[weak]
model,
move || {
model.load_more();
}
));
if let Some(store) = model.get_list_store() {
widget.bind_artist_releases(
worker.clone(),
&store,
clone!(
#[weak]
model,
move |id| {
model.open_album(id);
}
),
);
}
let playlist = Box::new(Playlist::new(
widget.top_tracks_widget().clone(),
Rc::clone(&model),
worker,
));
Self {
model,
widget,
children: vec![playlist],
}
}
}
impl Component for ArtistDetails {
fn get_root_widget(&self) -> >k::Widget {
self.widget.upcast_ref()
}
fn get_children(&mut self) -> Option<&mut Vec<Box<dyn EventListener>>> {
Some(&mut self.children)
}
}
impl EventListener for ArtistDetails {
fn on_event(&mut self, event: &AppEvent) {
match event {
AppEvent::BrowserEvent(BrowserEvent::ArtistDetailsUpdated(id))
if id == &self.model.id =>
{
self.widget.set_loaded();
}
_ => {}
}
self.broadcast_event(event);
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/details/details_model.rs | src/app/components/details/details_model.rs | use gio::prelude::*;
use gio::SimpleActionGroup;
use std::cell::Ref;
use std::ops::Deref;
use std::rc::Rc;
use crate::api::SpotifyApiError;
use crate::app::components::labels;
use crate::app::components::HeaderBarModel;
use crate::app::components::PlaylistModel;
use crate::app::components::SimpleHeaderBarModel;
use crate::app::components::SimpleHeaderBarModelWrapper;
use crate::app::dispatch::ActionDispatcher;
use crate::app::models::*;
use crate::app::state::SelectionContext;
use crate::app::state::{BrowserAction, PlaybackAction, SelectionAction, SelectionState};
use crate::app::{AppAction, AppEvent, AppModel, AppState, BatchQuery, SongsSource};
pub struct DetailsModel {
pub id: String,
app_model: Rc<AppModel>,
dispatcher: Box<dyn ActionDispatcher>,
}
impl DetailsModel {
pub fn new(id: String, app_model: Rc<AppModel>, dispatcher: Box<dyn ActionDispatcher>) -> Self {
Self {
id,
app_model,
dispatcher,
}
}
fn state(&self) -> Ref<'_, AppState> {
self.app_model.get_state()
}
pub fn get_album_info(&self) -> Option<impl Deref<Target = AlbumFullDescription> + '_> {
self.app_model
.map_state_opt(|s| s.browser.details_state(&self.id)?.content.as_ref())
}
pub fn get_album_description(&self) -> Option<impl Deref<Target = AlbumDescription> + '_> {
self.app_model.map_state_opt(|s| {
Some(
&s.browser
.details_state(&self.id)?
.content
.as_ref()?
.description,
)
})
}
pub fn load_album_info(&self) {
let id = self.id.clone();
let api = self.app_model.get_spotify();
self.dispatcher
.call_spotify_and_dispatch(move || async move {
let album = api.get_album(&id).await;
match album {
Ok(album) => Ok(BrowserAction::SetAlbumDetails(Box::new(album)).into()),
Err(SpotifyApiError::BadStatus(400, _))
| Err(SpotifyApiError::BadStatus(404, _)) => {
Ok(BrowserAction::NavigationPop.into())
}
Err(e) => Err(e),
}
});
}
pub fn view_artist(&self) {
if let Some(album) = self.get_album_description() {
let artist = &album.artists.first().unwrap().id;
self.dispatcher
.dispatch(AppAction::ViewArtist(artist.to_owned()));
}
}
pub fn toggle_save_album(&self) {
if let Some(album) = self.get_album_description() {
let id = album.id.clone();
let is_liked = album.is_liked;
let api = self.app_model.get_spotify();
self.dispatcher
.call_spotify_and_dispatch(move || async move {
if !is_liked {
api.save_album(&id)
.await
.map(|album| BrowserAction::SaveAlbum(Box::new(album)).into())
} else {
api.remove_saved_album(&id)
.await
.map(|_| BrowserAction::UnsaveAlbum(id).into())
}
});
}
}
pub fn is_playing(&self) -> bool {
self.state().playback.is_playing()
}
pub fn album_is_playing(&self) -> bool {
matches!(
self.app_model.get_state().playback.current_source(),
Some(SongsSource::Album(ref id)) if id == &self.id)
}
pub fn toggle_play_album(&self) {
if let Some(album) = self.get_album_description() {
if !self.album_is_playing() {
if self.state().playback.is_shuffled() {
self.dispatcher
.dispatch(AppAction::PlaybackAction(PlaybackAction::ToggleShuffle));
}
let id_of_first_song = album.songs.songs[0].id.as_str();
self.play_song_at(0, id_of_first_song);
return;
}
if self.state().playback.is_playing() {
self.dispatcher
.dispatch(AppAction::PlaybackAction(PlaybackAction::Pause));
} else {
self.dispatcher
.dispatch(AppAction::PlaybackAction(PlaybackAction::Play));
}
}
}
pub fn load_more(&self) -> Option<()> {
let last_batch = self.song_list_model().last_batch()?;
let query = BatchQuery {
source: SongsSource::Album(self.id.clone()),
batch: last_batch,
};
let id = self.id.clone();
let next_query = query.next()?;
let loader = self.app_model.get_batch_loader();
self.dispatcher.dispatch_async(Box::pin(async move {
loader
.query(next_query, |_s, song_batch| {
BrowserAction::AppendAlbumTracks(id, Box::new(song_batch)).into()
})
.await
}));
Some(())
}
pub fn to_headerbar_model(self: &Rc<Self>) -> Rc<impl HeaderBarModel> {
Rc::new(SimpleHeaderBarModelWrapper::new(
self.clone(),
self.app_model.clone(),
self.dispatcher.box_clone(),
))
}
}
impl PlaylistModel for DetailsModel {
fn song_list_model(&self) -> SongListModel {
self.app_model
.get_state()
.browser
.details_state(&self.id)
.expect("illegal attempt to read details_state")
.songs
.clone()
}
fn is_paused(&self) -> bool {
!self.app_model.get_state().playback.is_playing()
}
fn show_song_covers(&self) -> bool {
false
}
fn select_song(&self, id: &str) {
let songs = self.song_list_model();
if let Some(song) = songs.get(id) {
self.dispatcher
.dispatch(SelectionAction::Select(vec![song.description().clone()]).into());
}
}
fn deselect_song(&self, id: &str) {
self.dispatcher
.dispatch(SelectionAction::Deselect(vec![id.to_string()]).into());
}
fn enable_selection(&self) -> bool {
self.dispatcher
.dispatch(AppAction::EnableSelection(SelectionContext::Default));
true
}
fn selection(&self) -> Option<Box<dyn Deref<Target = SelectionState> + '_>> {
Some(Box::new(self.app_model.map_state(|s| &s.selection)))
}
fn current_song_id(&self) -> Option<String> {
self.state().playback.current_song_id()
}
fn play_song_at(&self, pos: usize, id: &str) {
let source = SongsSource::Album(self.id.clone());
let batch = self.song_list_model().song_batch_for(pos);
if let Some(batch) = batch {
self.dispatcher
.dispatch(PlaybackAction::LoadPagedSongs(source, batch).into());
self.dispatcher
.dispatch(PlaybackAction::Load(id.to_string()).into());
}
}
fn actions_for(&self, id: &str) -> Option<gio::ActionGroup> {
let song = self.song_list_model().get(id)?;
let song = song.description();
let group = SimpleActionGroup::new();
for view_artist in song.make_artist_actions(self.dispatcher.box_clone(), None) {
group.add_action(&view_artist);
}
group.add_action(&song.make_link_action(None));
group.add_action(&song.make_queue_action(self.dispatcher.box_clone(), None));
Some(group.upcast())
}
fn menu_for(&self, id: &str) -> Option<gio::MenuModel> {
let song = self.song_list_model().get(id)?;
let song = song.description();
let menu = gio::Menu::new();
for artist in song.artists.iter() {
menu.append(
Some(&labels::more_from_label(&artist.name)),
Some(&format!("song.view_artist_{}", artist.id)),
);
}
menu.append(Some(&*labels::COPY_LINK), Some("song.copy_link"));
menu.append(Some(&*labels::ADD_TO_QUEUE), Some("song.queue"));
Some(menu.upcast())
}
}
impl SimpleHeaderBarModel for DetailsModel {
fn title(&self) -> Option<String> {
None
}
fn title_updated(&self, _: &AppEvent) -> bool {
false
}
fn selection_context(&self) -> Option<SelectionContext> {
Some(SelectionContext::Default)
}
fn select_all(&self) {
let songs: Vec<SongDescription> = self.song_list_model().collect();
self.dispatcher
.dispatch(SelectionAction::Select(songs).into());
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/details/mod.rs | src/app/components/details/mod.rs | mod album_header;
#[allow(clippy::module_inception)]
mod details;
mod details_model;
mod release_details;
pub use details::Details;
pub use details_model::DetailsModel;
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/details/details.rs | src/app/components/details/details.rs | use gtk::prelude::*;
use gtk::subclass::prelude::*;
use gtk::CompositeTemplate;
use libadwaita::prelude::AdwDialogExt;
use std::rc::Rc;
use super::album_header::AlbumHeaderWidget;
use super::release_details::ReleaseDetailsDialog;
use super::DetailsModel;
use crate::app::components::{
Component, EventListener, HeaderBarComponent, HeaderBarWidget, Playlist, ScrollingHeaderWidget,
};
use crate::app::dispatch::Worker;
use crate::app::loader::ImageLoader;
use crate::app::state::PlaybackEvent;
use crate::app::{AppEvent, BrowserEvent};
mod imp {
use libadwaita::subclass::prelude::BinImpl;
use super::*;
#[derive(Debug, Default, CompositeTemplate)]
#[template(resource = "/dev/diegovsky/Riff/components/details.ui")]
pub struct AlbumDetailsWidget {
#[template_child]
pub scrolling_header: TemplateChild<ScrollingHeaderWidget>,
#[template_child]
pub headerbar: TemplateChild<HeaderBarWidget>,
#[template_child]
pub header_widget: TemplateChild<AlbumHeaderWidget>,
#[template_child]
pub album_tracks: TemplateChild<gtk::ListView>,
}
#[glib::object_subclass]
impl ObjectSubclass for AlbumDetailsWidget {
const NAME: &'static str = "AlbumDetailsWidget";
type Type = super::AlbumDetailsWidget;
type ParentType = libadwaita::Bin;
fn class_init(klass: &mut Self::Class) {
klass.bind_template();
}
fn instance_init(obj: &glib::subclass::InitializingObject<Self>) {
obj.init_template();
}
}
impl ObjectImpl for AlbumDetailsWidget {
fn constructed(&self) {
self.parent_constructed();
// self.header_mobile.set_centered();
self.headerbar.add_classes(&["details__headerbar"]);
}
}
impl WidgetImpl for AlbumDetailsWidget {}
impl BinImpl for AlbumDetailsWidget {}
}
glib::wrapper! {
pub struct AlbumDetailsWidget(ObjectSubclass<imp::AlbumDetailsWidget>) @extends gtk::Widget, libadwaita::Bin;
}
impl AlbumDetailsWidget {
fn new() -> Self {
glib::Object::new()
}
fn set_header_visible(&self, visible: bool) {
let widget = self.imp();
widget.headerbar.set_title_visible(true);
if visible {
widget.headerbar.add_classes(&["flat"]);
} else {
widget.headerbar.remove_classes(&["flat"]);
}
}
fn connect_header(&self) {
self.set_header_visible(false);
self.imp()
.scrolling_header
.connect_header_visibility(clone!(
#[weak(rename_to = _self)]
self,
move |visible| {
_self.set_header_visible(visible);
}
));
}
fn connect_bottom_edge<F>(&self, f: F)
where
F: Fn() + 'static,
{
self.imp().scrolling_header.connect_bottom_edge(f);
}
fn headerbar_widget(&self) -> &HeaderBarWidget {
self.imp().headerbar.as_ref()
}
fn album_tracks_widget(&self) -> >k::ListView {
self.imp().album_tracks.as_ref()
}
fn set_loaded(&self) {
self.imp()
.scrolling_header
.add_css_class("container--loaded");
}
fn connect_liked<F>(&self, f: F)
where
F: Fn() + 'static,
{
self.imp().header_widget.connect_liked(f);
}
fn connect_play<F>(&self, f: F)
where
F: Fn() + 'static,
{
self.imp().header_widget.connect_play(f);
}
fn connect_info<F>(&self, f: F)
where
F: Fn(&Self) + 'static,
{
self.imp().header_widget.connect_info(clone!(
#[weak(rename_to = _self)]
self,
move || f(&_self)
));
}
fn set_liked(&self, is_liked: bool) {
self.imp().header_widget.set_liked(is_liked);
}
fn set_playing(&self, is_playing: bool) {
self.imp().header_widget.set_playing(is_playing);
}
fn set_album_and_artist_and_year(&self, album: &str, artist: &str, year: Option<u32>) {
self.imp()
.header_widget
.set_album_and_artist_and_year(album, artist, year);
self.imp().headerbar.set_title_and_subtitle(album, artist);
}
fn set_artwork(&self, art: &gdk_pixbuf::Pixbuf) {
self.imp().header_widget.set_artwork(art);
}
fn connect_artist_clicked<F>(&self, f: F)
where
F: Fn() + 'static,
{
self.imp().header_widget.connect_artist_clicked(f);
}
}
pub struct Details {
model: Rc<DetailsModel>,
worker: Worker,
widget: AlbumDetailsWidget,
modal: ReleaseDetailsDialog,
children: Vec<Box<dyn EventListener>>,
}
impl Details {
pub fn new(model: Rc<DetailsModel>, worker: Worker) -> Self {
if model.get_album_info().is_none() {
model.load_album_info();
}
let widget = AlbumDetailsWidget::new();
let playlist = Box::new(Playlist::new(
widget.album_tracks_widget().clone(),
model.clone(),
worker.clone(),
));
let headerbar_widget = widget.headerbar_widget();
let headerbar = Box::new(HeaderBarComponent::new(
headerbar_widget.clone(),
model.to_headerbar_model(),
));
let modal = ReleaseDetailsDialog::new();
widget.connect_liked(clone!(
#[weak]
model,
move || model.toggle_save_album()
));
widget.connect_play(clone!(
#[weak]
model,
move || model.toggle_play_album()
));
widget.connect_header();
widget.connect_bottom_edge(clone!(
#[weak]
model,
move || {
model.load_more();
}
));
widget.connect_info(clone!(
#[weak]
modal,
move |w| {
let modal = modal.upcast_ref::<libadwaita::Dialog>();
let parent = w.root().and_then(|r| r.downcast::<gtk::Window>().ok());
modal.present(parent.as_ref());
}
));
Self {
model,
worker,
widget,
modal,
children: vec![playlist, headerbar],
}
}
fn update_liked(&self) {
if let Some(info) = self.model.get_album_info() {
let is_liked = info.description.is_liked;
self.widget.set_liked(is_liked);
self.widget.set_liked(is_liked);
}
}
fn update_playing(&self, is_playing: bool) {
if !self.model.album_is_playing() || !self.model.is_playing() {
self.widget.set_playing(false);
return;
}
self.widget.set_playing(is_playing);
}
fn update_details(&mut self) {
if let Some(album) = self.model.get_album_info() {
let details = &album.release_details;
let album = &album.description;
self.widget.set_liked(album.is_liked);
self.widget.set_album_and_artist_and_year(
&album.title[..],
&album.artists_name(),
album.year(),
);
self.widget.connect_artist_clicked(clone!(
#[weak(rename_to = model)]
self.model,
move || model.view_artist()
));
self.modal.set_details(
&album.title,
&album.artists_name(),
&details.label,
album.release_date.as_ref().unwrap(),
details.total_tracks,
&details.copyright_text,
);
if let Some(art) = album.art.clone() {
let widget = self.widget.downgrade();
self.worker.send_local_task(async move {
let pixbuf = ImageLoader::new()
.load_remote(&art[..], "jpg", 320, 320)
.await;
if let (Some(widget), Some(ref pixbuf)) = (widget.upgrade(), pixbuf) {
widget.set_artwork(pixbuf);
widget.set_loaded();
}
});
} else {
self.widget.set_loaded();
}
}
}
}
impl Component for Details {
fn get_root_widget(&self) -> >k::Widget {
self.widget.upcast_ref()
}
fn get_children(&mut self) -> Option<&mut Vec<Box<dyn EventListener>>> {
Some(&mut self.children)
}
}
impl EventListener for Details {
fn on_event(&mut self, event: &AppEvent) {
match event {
AppEvent::BrowserEvent(BrowserEvent::AlbumDetailsLoaded(id))
if id == &self.model.id =>
{
self.update_details();
self.update_playing(true);
}
AppEvent::BrowserEvent(BrowserEvent::AlbumSaved(id))
| AppEvent::BrowserEvent(BrowserEvent::AlbumUnsaved(id))
if id == &self.model.id =>
{
self.update_liked();
}
AppEvent::PlaybackEvent(PlaybackEvent::PlaybackPaused) => {
self.update_playing(false);
}
AppEvent::PlaybackEvent(PlaybackEvent::PlaybackResumed) => {
self.update_playing(true);
}
_ => {}
}
self.broadcast_event(event);
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/details/album_header.rs | src/app/components/details/album_header.rs | use crate::app::components::display_add_css_provider;
use gettextrs::gettext;
use gtk::prelude::*;
use gtk::subclass::prelude::*;
use gtk::{glib, CompositeTemplate};
mod imp {
use std::cell::Cell;
use super::*;
#[derive(Debug, Default, CompositeTemplate, glib::Properties)]
#[properties(wrapper_type = super::AlbumHeaderWidget)]
#[template(resource = "/dev/diegovsky/Riff/components/album_header.ui")]
pub struct AlbumHeaderWidget {
#[template_child]
pub album_overlay: TemplateChild<gtk::Overlay>,
#[template_child]
pub album_label: TemplateChild<gtk::Label>,
#[template_child]
pub album_art: TemplateChild<gtk::Picture>,
#[template_child]
pub button_box: TemplateChild<gtk::Box>,
#[template_child]
pub like_button: TemplateChild<gtk::Button>,
#[template_child]
pub play_button: TemplateChild<gtk::Button>,
#[template_child]
pub info_button: TemplateChild<gtk::Button>,
#[template_child]
pub album_info: TemplateChild<gtk::Box>,
#[template_child]
pub artist_button: TemplateChild<gtk::LinkButton>,
#[template_child]
pub artist_button_label: TemplateChild<gtk::Label>,
#[template_child]
pub year_label: TemplateChild<gtk::Label>,
#[property(get, set = Self::set_vertical, name = "vertical-layout")]
pub vertical_layout: Cell<bool>,
}
impl AlbumHeaderWidget {
pub fn set_vertical(&self, vertical: bool) {
let self_ = self.obj();
let box_ = self_.upcast_ref::<gtk::Box>();
if vertical {
box_.set_orientation(gtk::Orientation::Vertical);
box_.set_spacing(12);
self.album_label.set_halign(gtk::Align::Center);
self.album_label.set_justify(gtk::Justification::Center);
self.artist_button.set_halign(gtk::Align::Center);
self.year_label.set_halign(gtk::Align::Center);
self.button_box.set_halign(gtk::Align::Center);
self.album_overlay.set_margin_start(0);
self.button_box.set_margin_end(0);
self.album_info.set_margin_start(0);
} else {
box_.set_orientation(gtk::Orientation::Horizontal);
box_.set_spacing(0);
self.album_label.set_halign(gtk::Align::Start);
self.album_label.set_justify(gtk::Justification::Left);
self.artist_button.set_halign(gtk::Align::Start);
self.year_label.set_halign(gtk::Align::Start);
self.button_box.set_halign(gtk::Align::Start);
self.album_overlay.set_margin_start(6);
self.button_box.set_margin_end(6);
self.album_info.set_margin_start(18);
}
}
}
#[glib::object_subclass]
impl ObjectSubclass for AlbumHeaderWidget {
const NAME: &'static str = "AlbumHeaderWidget";
type Type = super::AlbumHeaderWidget;
type ParentType = gtk::Box;
fn class_init(klass: &mut Self::Class) {
klass.bind_template();
}
fn instance_init(obj: &glib::subclass::InitializingObject<Self>) {
display_add_css_provider(resource!("/components/album_header.css"));
obj.init_template();
}
}
#[glib::derived_properties]
impl ObjectImpl for AlbumHeaderWidget {}
impl WidgetImpl for AlbumHeaderWidget {}
impl BoxImpl for AlbumHeaderWidget {}
}
glib::wrapper! {
pub struct AlbumHeaderWidget(ObjectSubclass<imp::AlbumHeaderWidget>) @extends gtk::Widget, gtk::Box;
}
impl Default for AlbumHeaderWidget {
fn default() -> Self {
Self::new()
}
}
impl AlbumHeaderWidget {
pub fn new() -> Self {
glib::Object::new()
}
pub fn connect_play<F>(&self, f: F)
where
F: Fn() + 'static,
{
self.imp().play_button.connect_clicked(move |_| f());
}
pub fn connect_liked<F>(&self, f: F)
where
F: Fn() + 'static,
{
self.imp().like_button.connect_clicked(move |_| f());
}
pub fn connect_info<F>(&self, f: F)
where
F: Fn() + 'static,
{
self.imp().info_button.connect_clicked(move |_| f());
}
pub fn connect_artist_clicked<F>(&self, f: F)
where
F: Fn() + 'static,
{
self.imp().artist_button.connect_activate_link(move |_| {
f();
glib::Propagation::Stop
});
}
pub fn set_liked(&self, is_liked: bool) {
self.imp().like_button.set_icon_name(if is_liked {
"starred-symbolic"
} else {
"non-starred-symbolic"
});
}
pub fn set_playing(&self, is_playing: bool) {
let playback_icon = if is_playing {
"media-playback-pause-symbolic"
} else {
"media-playback-start-symbolic"
};
let translated_tooltip = if is_playing {
gettext("Pause")
} else {
gettext("Play")
};
let tooltip_text = Some(translated_tooltip.as_str());
self.imp().play_button.set_icon_name(playback_icon);
self.imp().play_button.set_tooltip_text(tooltip_text);
}
pub fn set_artwork(&self, pixbuf: &gdk_pixbuf::Pixbuf) {
let texture = gdk::Texture::for_pixbuf(pixbuf);
self.imp().album_art.set_paintable(Some(&texture));
}
pub fn set_album_and_artist_and_year(&self, album: &str, artist: &str, year: Option<u32>) {
let widget = self.imp();
widget.album_label.set_label(album);
widget.artist_button_label.set_label(artist);
match year {
Some(year) => widget.year_label.set_label(&year.to_string()),
None => widget.year_label.set_visible(false),
}
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/details/release_details.rs | src/app/components/details/release_details.rs | use gtk::subclass::prelude::*;
use gtk::CompositeTemplate;
use libadwaita::subclass::prelude::*;
use crate::app::components::labels;
mod imp {
use super::*;
#[derive(Debug, Default, CompositeTemplate)]
#[template(resource = "/dev/diegovsky/Riff/components/release_details.ui")]
pub struct ReleaseDetailsDialog {
#[template_child]
pub album_artist: TemplateChild<libadwaita::WindowTitle>,
#[template_child]
pub label: TemplateChild<gtk::Label>,
#[template_child]
pub release: TemplateChild<gtk::Label>,
#[template_child]
pub tracks: TemplateChild<gtk::Label>,
#[template_child]
pub copyright: TemplateChild<gtk::Label>,
}
#[glib::object_subclass]
impl ObjectSubclass for ReleaseDetailsDialog {
const NAME: &'static str = "ReleaseDetailsDialog";
type Type = super::ReleaseDetailsDialog;
type ParentType = libadwaita::Dialog;
fn class_init(klass: &mut Self::Class) {
klass.bind_template();
}
fn instance_init(obj: &glib::subclass::InitializingObject<Self>) {
obj.init_template();
}
}
impl ObjectImpl for ReleaseDetailsDialog {}
impl WidgetImpl for ReleaseDetailsDialog {}
impl AdwDialogImpl for ReleaseDetailsDialog {}
}
glib::wrapper! {
pub struct
ReleaseDetailsDialog(ObjectSubclass<imp::ReleaseDetailsDialog>) @extends gtk::Widget, libadwaita::Dialog;
}
impl ReleaseDetailsDialog {
pub fn new() -> Self {
glib::Object::new()
}
#[allow(clippy::too_many_arguments)]
pub fn set_details(
&self,
album: &str,
artist: &str,
label: &str,
release_date: &str,
track_count: usize,
copyright: &str,
) {
let widget = self.imp();
widget
.album_artist
.set_title(&labels::album_by_artist_label(album, artist));
widget.label.set_text(label);
widget.release.set_text(release_date);
widget.tracks.set_text(&track_count.to_string());
widget.copyright.set_text(copyright);
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/navigation/home.rs | src/app/components/navigation/home.rs | use gtk::prelude::*;
use crate::app::components::sidebar::SidebarDestination;
use crate::app::components::{Component, EventListener, ScreenFactory};
use crate::app::{AppEvent, BrowserEvent};
pub struct HomePane {
stack: gtk::Stack,
components: Vec<Box<dyn EventListener>>,
}
impl HomePane {
pub fn new(listbox: gtk::ListBox, screen_factory: &ScreenFactory) -> Self {
let library = screen_factory.make_library();
let saved_playlists = screen_factory.make_saved_playlists();
let saved_tracks = screen_factory.make_saved_tracks();
let now_playing = screen_factory.make_now_playing();
let sidebar = screen_factory.make_sidebar(listbox);
let stack = gtk::Stack::new();
stack.set_transition_type(gtk::StackTransitionType::Crossfade);
let dest = SidebarDestination::Library;
stack.add_titled(
library.get_root_widget(),
Option::from(dest.id()),
&dest.title(),
);
let dest = SidebarDestination::SavedTracks;
stack.add_titled(
saved_tracks.get_root_widget(),
Option::from(dest.id()),
&dest.title(),
);
let dest = SidebarDestination::SavedPlaylists;
stack.add_titled(
saved_playlists.get_root_widget(),
Option::from(dest.id()),
&dest.title(),
);
let dest = SidebarDestination::NowPlaying;
stack.add_titled(
now_playing.get_root_widget(),
Option::from(dest.id()),
&dest.title(),
);
Self {
stack,
components: vec![
Box::new(sidebar),
Box::new(library),
Box::new(saved_playlists),
Box::new(saved_tracks),
Box::new(now_playing),
],
}
}
}
impl Component for HomePane {
fn get_root_widget(&self) -> >k::Widget {
self.stack.upcast_ref()
}
fn get_children(&mut self) -> Option<&mut Vec<Box<dyn EventListener>>> {
Some(&mut self.components)
}
}
impl EventListener for HomePane {
fn on_event(&mut self, event: &AppEvent) {
match event {
AppEvent::NowPlayingShown => {
self.stack
.set_visible_child_name(SidebarDestination::NowPlaying.id());
}
AppEvent::BrowserEvent(BrowserEvent::HomeVisiblePageChanged(page)) => {
self.stack.set_visible_child_name(page);
}
_ => {}
}
self.broadcast_event(event);
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/navigation/navigation.rs | src/app/components/navigation/navigation.rs | use gtk::prelude::WidgetExt;
use std::rc::Rc;
use crate::app::components::{EventListener, ListenerComponent};
use crate::app::state::ScreenName;
use crate::app::{AppEvent, BrowserEvent};
use super::{factory::ScreenFactory, home::HomePane, NavigationModel};
pub struct Navigation {
model: Rc<NavigationModel>,
split_view: libadwaita::NavigationSplitView,
navigation_stack: gtk::Stack,
home_listbox: gtk::ListBox,
screen_factory: ScreenFactory,
children: Vec<Box<dyn ListenerComponent>>,
}
impl Navigation {
pub fn new(
model: NavigationModel,
split_view: libadwaita::NavigationSplitView,
navigation_stack: gtk::Stack,
home_listbox: gtk::ListBox,
screen_factory: ScreenFactory,
) -> Self {
let model = Rc::new(model);
split_view.connect_collapsed_notify(clone!(
#[weak]
model,
move |split_view| {
let is_main = split_view.shows_content();
let folded = split_view.is_collapsed();
if folded {
split_view.add_css_class("collapsed");
} else {
split_view.remove_css_class("collapsed");
}
model.set_nav_hidden(folded && is_main);
}
));
split_view.connect_show_content_notify(clone!(
#[weak]
model,
move |split_view| {
let is_main = split_view.shows_content();
let folded = split_view.is_collapsed();
if folded {
split_view.add_css_class("collapsed");
} else {
split_view.remove_css_class("collapsed");
}
model.set_nav_hidden(folded && is_main);
}
));
Self {
model,
split_view,
navigation_stack,
home_listbox,
screen_factory,
children: vec![],
}
}
fn make_home(&self) -> Box<dyn ListenerComponent> {
Box::new(HomePane::new(
self.home_listbox.clone(),
&self.screen_factory,
))
}
fn show_navigation(&self) {
self.split_view.set_show_content(false);
}
fn push_screen(&mut self, name: &ScreenName) {
let component: Box<dyn ListenerComponent> = match name {
ScreenName::Home => self.make_home(),
ScreenName::AlbumDetails(id) => {
Box::new(self.screen_factory.make_album_details(id.to_owned()))
}
ScreenName::Search => Box::new(self.screen_factory.make_search_results()),
ScreenName::Artist(id) => {
Box::new(self.screen_factory.make_artist_details(id.to_owned()))
}
ScreenName::PlaylistDetails(id) => {
Box::new(self.screen_factory.make_playlist_details(id.to_owned()))
}
ScreenName::User(id) => Box::new(self.screen_factory.make_user_details(id.to_owned())),
};
let widget = component.get_root_widget().clone();
self.children.push(component);
self.split_view.set_show_content(true);
self.navigation_stack
.add_named(&widget, Some(name.identifier().as_ref()));
self.navigation_stack
.set_visible_child_name(name.identifier().as_ref());
glib::source::idle_add_local_once(move || {
widget.grab_focus();
});
}
fn pop(&mut self) {
let children = &mut self.children;
let popped = children.pop();
let name = self.model.visible_child_name();
self.navigation_stack
.set_visible_child_name(name.identifier().as_ref());
if let Some(child) = popped {
self.navigation_stack.remove(child.get_root_widget());
}
}
fn pop_to(&mut self, screen: &ScreenName) {
self.navigation_stack
.set_visible_child_name(screen.identifier().as_ref());
let remainder = self.children.split_off(self.model.children_count());
for widget in remainder {
self.navigation_stack.remove(widget.get_root_widget());
}
}
}
impl EventListener for Navigation {
fn on_event(&mut self, event: &AppEvent) {
match event {
AppEvent::Started => {
self.push_screen(&ScreenName::Home);
}
AppEvent::BrowserEvent(BrowserEvent::NavigationPushed(name)) => {
self.push_screen(name);
}
AppEvent::BrowserEvent(BrowserEvent::NavigationHidden(false)) => {
self.show_navigation();
}
AppEvent::BrowserEvent(BrowserEvent::NavigationPopped) => {
self.pop();
}
AppEvent::BrowserEvent(BrowserEvent::NavigationPoppedTo(name)) => {
self.pop_to(name);
}
AppEvent::BrowserEvent(BrowserEvent::HomeVisiblePageChanged(_)) => {
self.split_view.set_show_content(true);
}
_ => {}
};
for child in self.children.iter_mut() {
child.on_event(event);
}
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/navigation/mod.rs | src/app/components/navigation/mod.rs | #[allow(clippy::module_inception)]
mod navigation;
pub use navigation::*;
mod navigation_model;
pub use navigation_model::*;
mod home;
mod factory;
pub use factory::*;
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/navigation/navigation_model.rs | src/app/components/navigation/navigation_model.rs | use crate::app::state::ScreenName;
use crate::app::{ActionDispatcher, AppModel, BrowserAction};
use std::ops::Deref;
use std::rc::Rc;
pub struct NavigationModel {
app_model: Rc<AppModel>,
dispatcher: Box<dyn ActionDispatcher>,
}
impl NavigationModel {
pub fn new(app_model: Rc<AppModel>, dispatcher: Box<dyn ActionDispatcher>) -> Self {
Self {
app_model,
dispatcher,
}
}
pub fn visible_child_name(&self) -> impl Deref<Target = ScreenName> + '_ {
self.app_model.map_state(|s| s.browser.current_screen())
}
pub fn set_nav_hidden(&self, hidden: bool) {
self.dispatcher
.dispatch(BrowserAction::SetNavigationHidden(hidden).into());
}
pub fn children_count(&self) -> usize {
self.app_model.get_state().browser.count()
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/navigation/factory.rs | src/app/components/navigation/factory.rs | use std::rc::Rc;
use crate::app::components::sidebar::{Sidebar, SidebarModel};
use crate::app::components::*;
use crate::app::state::SelectionContext;
use crate::app::{ActionDispatcher, AppModel, Worker};
pub struct ScreenFactory {
app_model: Rc<AppModel>,
dispatcher: Box<dyn ActionDispatcher>,
worker: Worker,
}
impl ScreenFactory {
pub fn new(
app_model: Rc<AppModel>,
dispatcher: Box<dyn ActionDispatcher>,
worker: Worker,
) -> Self {
Self {
app_model,
dispatcher,
worker,
}
}
pub fn make_library(&self) -> impl ListenerComponent {
let model = LibraryModel::new(Rc::clone(&self.app_model), self.dispatcher.box_clone());
let screen_model = DefaultHeaderBarModel::new(
Some(gettext("Library")),
None,
Rc::clone(&self.app_model),
self.dispatcher.box_clone(),
);
StandardScreen::new(
Library::new(self.worker.clone(), model),
Rc::new(screen_model),
)
}
pub fn make_sidebar(&self, listbox: gtk::ListBox) -> impl ListenerComponent {
let model = SidebarModel::new(Rc::clone(&self.app_model), self.dispatcher.box_clone());
Sidebar::new(listbox, Rc::new(model))
}
pub fn make_saved_playlists(&self) -> impl ListenerComponent {
let model =
SavedPlaylistsModel::new(Rc::clone(&self.app_model), self.dispatcher.box_clone());
let screen_model = DefaultHeaderBarModel::new(
Some(gettext("Playlists")),
None,
Rc::clone(&self.app_model),
self.dispatcher.box_clone(),
);
StandardScreen::new(
SavedPlaylists::new(self.worker.clone(), model),
Rc::new(screen_model),
)
}
pub fn make_now_playing(&self) -> impl ListenerComponent {
let model = Rc::new(NowPlayingModel::new(
Rc::clone(&self.app_model),
self.dispatcher.box_clone(),
));
NowPlaying::new(model, self.worker.clone())
}
pub fn make_saved_tracks(&self) -> impl ListenerComponent {
let screen_model = DefaultHeaderBarModel::new(
Some(gettext("Saved tracks")),
Some(SelectionContext::SavedTracks),
Rc::clone(&self.app_model),
self.dispatcher.box_clone(),
);
let model = Rc::new(SavedTracksModel::new(
Rc::clone(&self.app_model),
self.dispatcher.box_clone(),
));
StandardScreen::new(
SavedTracks::new(model, self.worker.clone()),
Rc::new(screen_model),
)
}
pub fn make_album_details(&self, id: String) -> impl ListenerComponent {
let model = Rc::new(DetailsModel::new(
id,
Rc::clone(&self.app_model),
self.dispatcher.box_clone(),
));
Details::new(model, self.worker.clone())
}
pub fn make_search_results(&self) -> impl ListenerComponent {
let model =
SearchResultsModel::new(Rc::clone(&self.app_model), self.dispatcher.box_clone());
SearchResults::new(model, self.worker.clone())
}
pub fn make_artist_details(&self, id: String) -> impl ListenerComponent {
let model = Rc::new(ArtistDetailsModel::new(
id,
Rc::clone(&self.app_model),
self.dispatcher.box_clone(),
));
let screen_model = SimpleHeaderBarModelWrapper::new(
Rc::clone(&model),
Rc::clone(&self.app_model),
self.dispatcher.box_clone(),
);
StandardScreen::new(
ArtistDetails::new(model, self.worker.clone()),
Rc::new(screen_model),
)
}
pub fn make_playlist_details(&self, id: String) -> impl ListenerComponent {
let model = Rc::new(PlaylistDetailsModel::new(
id,
Rc::clone(&self.app_model),
self.dispatcher.box_clone(),
));
PlaylistDetails::new(model, self.worker.clone())
}
pub fn make_user_details(&self, id: String) -> impl ListenerComponent {
let screen_model = DefaultHeaderBarModel::new(
None,
None,
Rc::clone(&self.app_model),
self.dispatcher.box_clone(),
);
let model =
UserDetailsModel::new(id, Rc::clone(&self.app_model), self.dispatcher.box_clone());
StandardScreen::new(
UserDetails::new(model, self.worker.clone()),
Rc::new(screen_model),
)
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/sidebar/sidebar_item.rs | src/app/components/sidebar/sidebar_item.rs | use gettextrs::gettext;
use glib::Properties;
use gtk::prelude::*;
use gtk::subclass::prelude::*;
use crate::app::models::PlaylistSummary;
const LIBRARY: &str = "library";
const SAVED_TRACKS: &str = "saved_tracks";
const NOW_PLAYING: &str = "now_playing";
const SAVED_PLAYLISTS: &str = "saved_playlists";
const PLAYLIST: &str = "playlist";
pub const SAVED_PLAYLISTS_SECTION: &str = "saved_playlists_section";
pub const CREATE_PLAYLIST_ITEM: &str = "create_playlist";
#[derive(Debug)]
pub enum SidebarDestination {
Library,
SavedTracks,
NowPlaying,
SavedPlaylists,
Playlist(PlaylistSummary),
}
impl SidebarDestination {
pub fn id(&self) -> &'static str {
match self {
Self::Library => LIBRARY,
Self::SavedTracks => SAVED_TRACKS,
Self::NowPlaying => NOW_PLAYING,
Self::SavedPlaylists => SAVED_PLAYLISTS,
Self::Playlist(_) => PLAYLIST,
}
}
pub fn title(&self) -> String {
match self {
// translators: This is a sidebar entry to browse to saved albums.
Self::Library => gettext("Library"),
// translators: This is a sidebar entry to browse to saved tracks.
Self::SavedTracks => gettext("Saved tracks"),
// translators: This is a sidebar entry to browse to saved playlists.
Self::NowPlaying => gettext("Now playing"),
// translators: This is a sidebar entry that marks that the entries below are playlists.
Self::SavedPlaylists => gettext("Playlists"),
Self::Playlist(PlaylistSummary { title, .. }) => title.clone(),
}
}
pub fn icon(&self) -> &'static str {
match self {
Self::Library => "library-music-symbolic",
Self::SavedTracks => "starred-symbolic",
Self::NowPlaying => "music-queue-symbolic",
Self::SavedPlaylists => "view-app-grid-symbolic",
Self::Playlist(_) => "playlist2-symbolic",
}
}
}
impl SidebarItem {
pub fn from_destination(dest: SidebarDestination) -> Self {
let (id, data, title) = match dest {
SidebarDestination::Playlist(PlaylistSummary { id, title }) => {
(PLAYLIST, Some(id), title)
}
_ => (dest.id(), None, dest.title()),
};
glib::Object::builder()
.property("id", id)
.property("data", data.unwrap_or_default())
.property("title", &title)
.property("navigatable", true)
.build()
}
pub fn playlists_section() -> Self {
glib::Object::builder()
.property("id", SAVED_PLAYLISTS_SECTION)
.property("data", String::new())
.property("title", gettext("All Playlists"))
.property("navigatable", false)
.build()
}
pub fn create_playlist_item() -> Self {
glib::Object::builder()
.property("id", CREATE_PLAYLIST_ITEM)
.property("data", String::new())
.property("title", gettext("New Playlist"))
.property("navigatable", false)
.build()
}
pub fn destination(&self) -> Option<SidebarDestination> {
let navigatable = self.property::<bool>("navigatable");
if navigatable {
let id = self.id();
let data = self.property::<String>("data");
let title = self.title();
match id.as_str() {
LIBRARY => Some(SidebarDestination::Library),
SAVED_TRACKS => Some(SidebarDestination::SavedTracks),
NOW_PLAYING => Some(SidebarDestination::NowPlaying),
SAVED_PLAYLISTS => Some(SidebarDestination::SavedPlaylists),
PLAYLIST => Some(SidebarDestination::Playlist(PlaylistSummary {
id: data,
title,
})),
_ => None,
}
} else {
None
}
}
pub fn icon(&self) -> Option<&str> {
match self.id().as_str() {
CREATE_PLAYLIST_ITEM => Some("list-add-symbolic"),
_ => self.destination().map(|d| d.icon()),
}
}
}
mod imp {
use super::*;
use std::cell::{Cell, RefCell};
#[derive(Debug, Default, Properties)]
#[properties(wrapper_type = super::SidebarItem)]
pub struct SidebarItem {
#[property(get, set)]
pub id: RefCell<String>,
#[property(get, set)]
pub data: RefCell<String>,
#[property(get, set)]
pub title: RefCell<String>,
#[property(get, set)]
pub navigatable: Cell<bool>,
}
#[glib::object_subclass]
impl ObjectSubclass for SidebarItem {
const NAME: &'static str = "SideBarItem";
type Type = super::SidebarItem;
type ParentType = glib::Object;
}
#[glib::derived_properties]
impl ObjectImpl for SidebarItem {}
}
glib::wrapper! {
pub struct SidebarItem(ObjectSubclass<imp::SidebarItem>);
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/sidebar/sidebar_row.rs | src/app/components/sidebar/sidebar_row.rs | use gtk::prelude::*;
use gtk::subclass::prelude::*;
use gtk::CompositeTemplate;
use super::SidebarItem;
impl SidebarRow {
pub fn new(item: SidebarItem) -> Self {
glib::Object::builder().property("item", item).build()
}
}
mod imp {
use super::*;
use glib::Properties;
use std::cell::RefCell;
#[derive(Debug, CompositeTemplate, Properties)]
#[template(resource = "/dev/diegovsky/Riff/sidebar/sidebar_row.ui")]
#[properties(wrapper_type = super::SidebarRow)]
pub struct SidebarRow {
#[template_child]
pub icon: TemplateChild<gtk::Image>,
#[template_child]
pub title: TemplateChild<gtk::Label>,
#[property(get, set = Self::set_item)]
pub item: RefCell<SidebarItem>,
}
impl SidebarRow {
fn set_item(&self, item: SidebarItem) {
self.title.set_text(item.title().as_str());
self.icon.set_icon_name(item.icon());
self.obj().set_tooltip_text(Some(item.title().as_str()));
self.item.replace(item);
}
}
#[glib::object_subclass]
impl ObjectSubclass for SidebarRow {
const NAME: &'static str = "SidebarRow";
type Type = super::SidebarRow;
type ParentType = gtk::ListBoxRow;
fn class_init(klass: &mut Self::Class) {
klass.bind_template();
}
fn instance_init(obj: &glib::subclass::InitializingObject<Self>) {
obj.init_template();
}
fn new() -> Self {
Self {
icon: Default::default(),
title: Default::default(),
item: RefCell::new(glib::Object::new()),
}
}
}
#[glib::derived_properties]
impl ObjectImpl for SidebarRow {}
impl WidgetImpl for SidebarRow {}
impl ListBoxRowImpl for SidebarRow {}
}
glib::wrapper! {
pub struct SidebarRow(ObjectSubclass<imp::SidebarRow>) @extends gtk::Widget, gtk::ListBoxRow;
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/sidebar/mod.rs | src/app/components/sidebar/mod.rs | #[allow(clippy::module_inception)]
mod sidebar;
pub use sidebar::*;
mod sidebar_item;
pub use sidebar_item::*;
mod create_playlist;
mod sidebar_row;
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/sidebar/sidebar.rs | src/app/components/sidebar/sidebar.rs | use gettextrs::gettext;
use gtk::prelude::*;
use std::rc::Rc;
use super::create_playlist::CreatePlaylistPopover;
use super::{
sidebar_row::SidebarRow, SidebarDestination, SidebarItem, CREATE_PLAYLIST_ITEM,
SAVED_PLAYLISTS_SECTION,
};
use crate::app::models::{AlbumModel, PlaylistSummary};
use crate::app::state::ScreenName;
use crate::app::{
ActionDispatcher, AppAction, AppEvent, AppModel, BrowserAction, BrowserEvent, Component,
EventListener,
};
const NUM_FIXED_ENTRIES: u32 = 6;
const NUM_PLAYLISTS: usize = 20;
pub struct SidebarModel {
app_model: Rc<AppModel>,
dispatcher: Box<dyn ActionDispatcher>,
}
impl SidebarModel {
pub fn new(app_model: Rc<AppModel>, dispatcher: Box<dyn ActionDispatcher>) -> Self {
Self {
app_model,
dispatcher,
}
}
fn get_playlists(&self) -> Vec<SidebarDestination> {
self.app_model
.get_state()
.browser
.home_state()
.expect("expected HomeState to be available")
.playlists
.iter()
.take(NUM_PLAYLISTS)
.map(Self::map_to_destination)
.collect()
}
fn map_to_destination(a: AlbumModel) -> SidebarDestination {
let title = Some(a.album())
.filter(|s| !s.is_empty())
.unwrap_or_else(|| gettext("Unnamed playlist"));
let id = a.uri();
SidebarDestination::Playlist(PlaylistSummary { id, title })
}
fn create_new_playlist(&self, name: String) {
let user_id = self.app_model.get_state().logged_user.user.clone().unwrap();
let api = self.app_model.get_spotify();
self.dispatcher
.call_spotify_and_dispatch(move || async move {
api.create_new_playlist(name.as_str(), user_id.as_str())
.await
.map(AppAction::CreatePlaylist)
})
}
fn navigate(&self, dest: SidebarDestination) {
let actions = match dest {
SidebarDestination::Library
| SidebarDestination::SavedTracks
| SidebarDestination::NowPlaying
| SidebarDestination::SavedPlaylists => {
vec![
BrowserAction::NavigationPopTo(ScreenName::Home).into(),
BrowserAction::SetHomeVisiblePage(dest.id()).into(),
]
}
SidebarDestination::Playlist(PlaylistSummary { id, .. }) => {
vec![AppAction::ViewPlaylist(id)]
}
};
self.dispatcher.dispatch_many(actions);
}
}
pub struct Sidebar {
listbox: gtk::ListBox,
list_store: gio::ListStore,
model: Rc<SidebarModel>,
}
impl Sidebar {
pub fn new(listbox: gtk::ListBox, model: Rc<SidebarModel>) -> Self {
let popover = CreatePlaylistPopover::new();
popover.connect_create(clone!(
#[weak]
model,
move |t| model.create_new_playlist(t)
));
let list_store = gio::ListStore::new::<SidebarItem>();
list_store.append(&SidebarItem::from_destination(SidebarDestination::Library));
list_store.append(&SidebarItem::from_destination(
SidebarDestination::SavedTracks,
));
list_store.append(&SidebarItem::from_destination(
SidebarDestination::NowPlaying,
));
list_store.append(&SidebarItem::playlists_section());
list_store.append(&SidebarItem::create_playlist_item());
list_store.append(&SidebarItem::from_destination(
SidebarDestination::SavedPlaylists,
));
listbox.bind_model(
Some(&list_store),
clone!(
#[weak]
popover,
#[upgrade_or_panic]
move |obj| {
let item = obj.downcast_ref::<SidebarItem>().unwrap();
if item.navigatable() {
Self::make_navigatable(item)
} else {
match item.id().as_str() {
SAVED_PLAYLISTS_SECTION => Self::make_section_label(item),
CREATE_PLAYLIST_ITEM => Self::make_create_playlist(item, popover),
_ => unimplemented!(),
}
}
}
),
);
listbox.connect_row_activated(clone!(
#[weak]
popover,
#[weak]
model,
move |_, row| {
if let Some(row) = row.downcast_ref::<SidebarRow>() {
if let Some(dest) = row.item().destination() {
model.navigate(dest);
} else {
match row.item().id().as_str() {
CREATE_PLAYLIST_ITEM => popover.popup(),
_ => unimplemented!(),
}
}
}
}
));
Self {
listbox,
list_store,
model,
}
}
fn make_navigatable(item: &SidebarItem) -> gtk::Widget {
let row = SidebarRow::new(item.clone());
row.set_selectable(false);
row.upcast()
}
fn make_section_label(item: &SidebarItem) -> gtk::Widget {
let label = gtk::Label::new(Some(item.title().as_str()));
label.add_css_class("caption-heading");
let row = gtk::ListBoxRow::builder()
.activatable(false)
.selectable(false)
.sensitive(false)
.child(&label)
.build();
row.upcast()
}
fn make_create_playlist(item: &SidebarItem, popover: CreatePlaylistPopover) -> gtk::Widget {
let row = SidebarRow::new(item.clone());
row.set_activatable(true);
row.set_selectable(false);
row.set_sensitive(true);
popover.set_parent(&row);
row.upcast()
}
fn update_playlists_in_sidebar(&self) {
let playlists: Vec<SidebarItem> = self
.model
.get_playlists()
.into_iter()
.map(SidebarItem::from_destination)
.collect();
self.list_store.splice(
NUM_FIXED_ENTRIES,
self.list_store.n_items() - NUM_FIXED_ENTRIES,
playlists.as_slice(),
);
}
}
impl Component for Sidebar {
fn get_root_widget(&self) -> >k::Widget {
self.listbox.upcast_ref()
}
}
impl EventListener for Sidebar {
fn on_event(&mut self, event: &AppEvent) {
if let AppEvent::BrowserEvent(BrowserEvent::SavedPlaylistsUpdated) = event {
self.update_playlists_in_sidebar();
}
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/sidebar/create_playlist.rs | src/app/components/sidebar/create_playlist.rs | use gtk::prelude::*;
use gtk::subclass::prelude::*;
use gtk::CompositeTemplate;
mod imp {
use super::*;
#[derive(Debug, Default, CompositeTemplate)]
#[template(resource = "/dev/diegovsky/Riff/components/create_playlist.ui")]
pub struct CreatePlaylistPopover {
#[template_child]
pub label: TemplateChild<gtk::Label>,
#[template_child]
pub entry: TemplateChild<gtk::Entry>,
#[template_child]
pub button: TemplateChild<gtk::Button>,
}
#[glib::object_subclass]
impl ObjectSubclass for CreatePlaylistPopover {
const NAME: &'static str = "CreatePlaylistPopover";
type Type = super::CreatePlaylistPopover;
type ParentType = gtk::Popover;
fn class_init(klass: &mut Self::Class) {
Self::bind_template(klass);
}
fn instance_init(obj: &glib::subclass::InitializingObject<Self>) {
obj.init_template();
}
}
impl ObjectImpl for CreatePlaylistPopover {}
impl WidgetImpl for CreatePlaylistPopover {}
impl PopoverImpl for CreatePlaylistPopover {}
}
glib::wrapper! {
pub struct CreatePlaylistPopover(ObjectSubclass<imp::CreatePlaylistPopover>) @extends gtk::Widget, gtk::Popover;
}
impl Default for CreatePlaylistPopover {
fn default() -> Self {
Self::new()
}
}
impl CreatePlaylistPopover {
pub fn new() -> Self {
glib::Object::new()
}
pub fn connect_create<F: Clone + Fn(String) + 'static>(&self, create_fun: F) {
let entry = self.imp().entry.get();
let closure = clone!(
#[weak(rename_to = popover)]
self,
#[weak]
entry,
#[strong]
create_fun,
move || {
create_fun(entry.text().to_string());
popover.popdown();
entry.buffer().delete_text(0, None);
}
);
let closure_clone = closure.clone();
entry.connect_activate(move |_| closure());
self.imp().button.connect_clicked(move |_| closure_clone());
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/device_selector/widget.rs | src/app/components/device_selector/widget.rs | use crate::app::models::{ConnectDevice, ConnectDeviceKind};
use crate::app::state::Device;
use gdk::prelude::FromVariant;
use gettextrs::gettext;
use gio::{Action, SimpleAction, SimpleActionGroup};
use gtk::prelude::*;
use gtk::subclass::prelude::*;
use gtk::CompositeTemplate;
const ACTIONS: &str = "devices";
const CONNECT_ACTION: &str = "connect";
const REFRESH_ACTION: &str = "refresh";
mod imp {
use super::*;
#[derive(Debug, Default, CompositeTemplate)]
#[template(resource = "/dev/diegovsky/Riff/components/device_selector.ui")]
pub struct DeviceSelectorWidget {
#[template_child]
pub button_content: TemplateChild<libadwaita::ButtonContent>,
#[template_child]
pub popover: TemplateChild<gtk::PopoverMenu>,
#[template_child]
pub custom_content: TemplateChild<gtk::Box>,
#[template_child]
pub devices: TemplateChild<gtk::Box>,
#[template_child]
pub this_device_button: TemplateChild<gtk::CheckButton>,
#[template_child]
pub menu: TemplateChild<gio::MenuModel>,
pub action_group: SimpleActionGroup,
}
#[glib::object_subclass]
impl ObjectSubclass for DeviceSelectorWidget {
const NAME: &'static str = "DeviceSelectorWidget";
type Type = super::DeviceSelectorWidget;
type ParentType = gtk::Button;
fn class_init(klass: &mut Self::Class) {
Self::bind_template(klass);
}
fn instance_init(obj: &glib::subclass::InitializingObject<Self>) {
obj.init_template();
}
}
impl ObjectImpl for DeviceSelectorWidget {
fn constructed(&self) {
self.parent_constructed();
let popover: >k::PopoverMenu = &self.popover;
popover.set_menu_model(Some(&*self.menu));
popover.add_child(&*self.custom_content, "custom_content");
popover.set_parent(&*self.obj());
popover.set_autohide(true);
let this_device = &*self.this_device_button;
this_device.set_action_name(Some(&format!("{}.{}", ACTIONS, CONNECT_ACTION)));
this_device.set_action_target_value(Some(&Option::<String>::None.to_variant()));
self.obj()
.insert_action_group(ACTIONS, Some(&self.action_group));
self.obj().connect_clicked(clone!(
#[weak]
popover,
move |_| {
popover.set_visible(true);
popover.present();
popover.grab_focus();
}
));
}
}
impl WidgetImpl for DeviceSelectorWidget {}
impl ButtonImpl for DeviceSelectorWidget {}
}
glib::wrapper! {
pub struct DeviceSelectorWidget(ObjectSubclass<imp::DeviceSelectorWidget>) @extends gtk::Widget, gtk::Button;
}
impl DeviceSelectorWidget {
fn action(&self, name: &str) -> Option<Action> {
self.imp().action_group.lookup_action(name)
}
pub fn connect_refresh<F>(&self, f: F)
where
F: Fn() + 'static,
{
self.imp().action_group.add_action(&{
let refresh = SimpleAction::new(REFRESH_ACTION, None);
refresh.connect_activate(move |_, _| f());
refresh
});
}
pub fn connect_switch_device<F>(&self, f: F)
where
F: Fn(Option<String>) + 'static,
{
self.imp().action_group.add_action(&{
let connect = SimpleAction::new_stateful(
CONNECT_ACTION,
Some(Option::<String>::static_variant_type().as_ref()),
&Option::<String>::None.to_variant(),
);
connect.connect_activate(move |action, device_id| {
if let Some(device_id) = device_id {
action.change_state(device_id);
f(Option::<String>::from_variant(device_id).unwrap());
}
});
connect
});
}
pub fn set_current_device(&self, device: &Device) {
if let Some(action) = self.action(CONNECT_ACTION) {
let device_id = match device {
Device::Local => None,
Device::Connect(connect) => Some(&connect.id),
};
action.change_state(&device_id.to_variant());
}
let label = match device {
Device::Local => gettext("This device"),
Device::Connect(connect) => connect.label.clone(),
};
let icon = match device {
Device::Local => "audio-x-generic-symbolic",
Device::Connect(connect) => match connect.kind {
ConnectDeviceKind::Phone => "phone-symbolic",
ConnectDeviceKind::Computer => "computer-symbolic",
ConnectDeviceKind::Speaker => "audio-speakers-symbolic",
ConnectDeviceKind::Other => "audio-x-generic-symbolic",
},
};
self.imp().button_content.set_label(&label);
self.imp().button_content.set_icon_name(icon);
}
pub fn update_devices_list(&self, devices: &[ConnectDevice]) {
let widget = self.imp();
widget.this_device_button.set_sensitive(!devices.is_empty());
while let Some(child) = widget.devices.upcast_ref::<gtk::Widget>().first_child() {
widget.devices.remove(&child);
}
for device in devices {
let check = gtk::CheckButton::builder()
.action_name(format!("{}.{}", ACTIONS, CONNECT_ACTION))
.action_target(&Some(&device.id).to_variant())
.group(&*widget.this_device_button)
.label(&device.label)
.build();
widget.devices.append(&check);
}
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/device_selector/mod.rs | src/app/components/device_selector/mod.rs | use gtk::prelude::StaticType;
mod component;
pub use component::*;
mod widget;
pub use widget::*;
pub fn expose_widgets() {
widget::DeviceSelectorWidget::static_type();
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/device_selector/component.rs | src/app/components/device_selector/component.rs | use std::ops::Deref;
use std::rc::Rc;
use gtk::prelude::Cast;
use crate::app::components::{Component, EventListener};
use crate::app::models::ConnectDevice;
use crate::app::state::{Device, LoginEvent, PlaybackAction, PlaybackEvent};
use crate::app::{ActionDispatcher, AppEvent, AppModel};
use super::widget::DeviceSelectorWidget;
pub struct DeviceSelectorModel {
app_model: Rc<AppModel>,
dispatcher: Box<dyn ActionDispatcher>,
}
impl DeviceSelectorModel {
pub fn new(app_model: Rc<AppModel>, dispatcher: Box<dyn ActionDispatcher>) -> Self {
Self {
app_model,
dispatcher,
}
}
pub fn refresh_available_devices(&self) {
let api = self.app_model.get_spotify();
self.dispatcher
.call_spotify_and_dispatch(move || async move {
api.list_available_devices()
.await
.map(|devices| PlaybackAction::SetAvailableDevices(devices).into())
});
}
pub fn get_available_devices(&self) -> impl Deref<Target = Vec<ConnectDevice>> + '_ {
self.app_model.map_state(|s| s.playback.available_devices())
}
pub fn get_current_device(&self) -> impl Deref<Target = Device> + '_ {
self.app_model.map_state(|s| s.playback.current_device())
}
pub fn set_current_device(&self, id: Option<String>) {
let devices = self.get_available_devices();
let connect_device = id
.and_then(|id| devices.iter().find(|&d| d.id == id))
.cloned();
let device = connect_device.map(Device::Connect).unwrap_or(Device::Local);
self.dispatcher
.dispatch(PlaybackAction::SwitchDevice(device).into());
}
}
pub struct DeviceSelector {
widget: DeviceSelectorWidget,
model: Rc<DeviceSelectorModel>,
}
impl DeviceSelector {
pub fn new(widget: DeviceSelectorWidget, model: DeviceSelectorModel) -> Self {
let model = Rc::new(model);
widget.connect_refresh(clone!(
#[weak]
model,
move || {
model.refresh_available_devices();
}
));
widget.connect_switch_device(clone!(
#[weak]
model,
move |id| {
model.set_current_device(id);
}
));
Self { widget, model }
}
}
impl Component for DeviceSelector {
fn get_root_widget(&self) -> >k::Widget {
self.widget.upcast_ref()
}
}
impl EventListener for DeviceSelector {
fn on_event(&mut self, event: &AppEvent) {
match event {
AppEvent::LoginEvent(LoginEvent::LoginCompleted) => {
self.model.refresh_available_devices();
}
AppEvent::PlaybackEvent(PlaybackEvent::AvailableDevicesChanged) => {
self.widget
.update_devices_list(&self.model.get_available_devices());
}
AppEvent::PlaybackEvent(PlaybackEvent::SwitchedDevice(_)) => {
self.widget
.set_current_device(&self.model.get_current_device());
}
_ => (),
}
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/playback/playback_info.rs | src/app/components/playback/playback_info.rs | use gettextrs::gettext;
use gtk::prelude::*;
use gtk::subclass::prelude::*;
use gtk::{glib, CompositeTemplate};
mod imp {
use super::*;
#[derive(Debug, Default, CompositeTemplate)]
#[template(resource = "/dev/diegovsky/Riff/components/playback_info.ui")]
pub struct PlaybackInfoWidget {
#[template_child]
pub playing_image: TemplateChild<gtk::Picture>,
#[template_child]
pub current_song_info: TemplateChild<gtk::Label>,
}
#[glib::object_subclass]
impl ObjectSubclass for PlaybackInfoWidget {
const NAME: &'static str = "PlaybackInfoWidget";
type Type = super::PlaybackInfoWidget;
type ParentType = gtk::Button;
fn class_init(klass: &mut Self::Class) {
klass.bind_template();
}
fn instance_init(obj: &glib::subclass::InitializingObject<Self>) {
obj.init_template();
}
}
impl ObjectImpl for PlaybackInfoWidget {}
impl WidgetImpl for PlaybackInfoWidget {}
impl ButtonImpl for PlaybackInfoWidget {}
}
glib::wrapper! {
pub struct PlaybackInfoWidget(ObjectSubclass<imp::PlaybackInfoWidget>) @extends gtk::Widget, gtk::Button;
}
impl PlaybackInfoWidget {
pub fn set_title_and_artist(&self, title: &str, artist: &str) {
let widget = self.imp();
let title = glib::markup_escape_text(title);
let artist = glib::markup_escape_text(artist);
let label = format!("<b>{}</b>\n{}", title.as_str(), artist.as_str());
widget.current_song_info.set_label(&label[..]);
}
pub fn reset_info(&self) {
let widget = self.imp();
widget
.current_song_info
// translators: Short text displayed instead of a song title when nothing plays
.set_label(&gettext("No song playing"));
widget
.playing_image
.set_paintable(None::<gdk::Paintable>.as_ref());
}
pub fn set_info_visible(&self, visible: bool) {
self.imp().current_song_info.set_visible(visible);
}
pub fn set_artwork(&self, pixbuf: &gdk_pixbuf::Pixbuf) {
let texture = gdk::Texture::for_pixbuf(pixbuf);
self.imp().playing_image.set_paintable(Some(&texture));
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/playback/mod.rs | src/app/components/playback/mod.rs | mod component;
mod playback_controls;
mod playback_info;
mod playback_widget;
pub use component::*;
use glib::prelude::*;
pub fn expose_widgets() {
playback_widget::PlaybackWidget::static_type();
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/playback/playback_controls.rs | src/app/components/playback/playback_controls.rs | use gettextrs::gettext;
use gtk::prelude::*;
use gtk::subclass::prelude::*;
use gtk::{glib, CompositeTemplate};
use crate::app::models::RepeatMode;
mod imp {
use super::*;
#[derive(Debug, Default, CompositeTemplate)]
#[template(resource = "/dev/diegovsky/Riff/components/playback_controls.ui")]
pub struct PlaybackControlsWidget {
#[template_child]
pub play_pause: TemplateChild<gtk::Button>,
#[template_child]
pub next: TemplateChild<gtk::Button>,
#[template_child]
pub prev: TemplateChild<gtk::Button>,
#[template_child]
pub shuffle: TemplateChild<gtk::ToggleButton>,
#[template_child]
pub repeat: TemplateChild<gtk::Button>,
}
#[glib::object_subclass]
impl ObjectSubclass for PlaybackControlsWidget {
const NAME: &'static str = "PlaybackControlsWidget";
type Type = super::PlaybackControlsWidget;
type ParentType = gtk::Box;
fn class_init(klass: &mut Self::Class) {
klass.bind_template();
}
fn instance_init(obj: &glib::subclass::InitializingObject<Self>) {
obj.init_template();
}
}
impl ObjectImpl for PlaybackControlsWidget {}
impl WidgetImpl for PlaybackControlsWidget {}
impl BoxImpl for PlaybackControlsWidget {}
}
glib::wrapper! {
pub struct PlaybackControlsWidget(ObjectSubclass<imp::PlaybackControlsWidget>) @extends gtk::Widget, gtk::Box;
}
impl PlaybackControlsWidget {
pub fn set_playing(&self, is_playing: bool) {
let playback_icon = if is_playing {
"media-playback-pause-symbolic"
} else {
"media-playback-start-symbolic"
};
let translated_tooltip = if is_playing {
gettext("Pause")
} else {
gettext("Play")
};
let tooltip_text = Some(translated_tooltip.as_str());
let playback_control = self.imp();
playback_control.play_pause.set_icon_name(playback_icon);
playback_control.play_pause.set_tooltip_text(tooltip_text);
}
pub fn set_shuffled(&self, shuffled: bool) {
self.imp().shuffle.set_active(shuffled);
}
pub fn set_repeat_mode(&self, mode: RepeatMode) {
let repeat_mode_icon = match mode {
RepeatMode::Song => "media-playlist-repeat-song-symbolic",
RepeatMode::Playlist => "media-playlist-repeat-symbolic",
RepeatMode::None => "media-playlist-consecutive-symbolic",
};
self.imp().repeat.set_icon_name(repeat_mode_icon);
}
pub fn connect_play_pause<F>(&self, f: F)
where
F: Fn() + 'static,
{
self.imp().play_pause.connect_clicked(move |_| f());
}
pub fn connect_prev<F>(&self, f: F)
where
F: Fn() + 'static,
{
self.imp().prev.connect_clicked(move |_| f());
}
pub fn connect_next<F>(&self, f: F)
where
F: Fn() + 'static,
{
self.imp().next.connect_clicked(move |_| f());
}
pub fn connect_shuffle<F>(&self, f: F)
where
F: Fn() + 'static,
{
self.imp().shuffle.connect_clicked(move |_| f());
}
pub fn connect_repeat<F>(&self, f: F)
where
F: Fn() + 'static,
{
self.imp().repeat.connect_clicked(move |_| f());
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/playback/playback_widget.rs | src/app/components/playback/playback_widget.rs | use gtk::prelude::*;
use gtk::subclass::prelude::*;
use gtk::{glib, CompositeTemplate};
use crate::app::components::display_add_css_provider;
use crate::app::components::utils::{format_duration, Clock, Debouncer};
use crate::app::loader::ImageLoader;
use crate::app::models::RepeatMode;
use crate::app::Worker;
use super::playback_controls::PlaybackControlsWidget;
use super::playback_info::PlaybackInfoWidget;
mod imp {
use super::*;
#[derive(Debug, Default, CompositeTemplate)]
#[template(resource = "/dev/diegovsky/Riff/components/playback_widget.ui")]
pub struct PlaybackWidget {
#[template_child]
pub controls: TemplateChild<PlaybackControlsWidget>,
#[template_child]
pub now_playing: TemplateChild<PlaybackInfoWidget>,
#[template_child]
pub seek_bar: TemplateChild<gtk::Scale>,
#[template_child]
pub track_position: TemplateChild<gtk::Label>,
#[template_child]
pub track_duration: TemplateChild<gtk::Label>,
#[template_child]
pub volume_slider: TemplateChild<gtk::Scale>,
pub clock: Clock,
}
#[glib::object_subclass]
impl ObjectSubclass for PlaybackWidget {
const NAME: &'static str = "PlaybackWidget";
type Type = super::PlaybackWidget;
type ParentType = gtk::Box;
fn class_init(klass: &mut Self::Class) {
klass.bind_template();
}
fn instance_init(obj: &glib::subclass::InitializingObject<Self>) {
obj.init_template();
}
}
impl ObjectImpl for PlaybackWidget {
fn constructed(&self) {
self.parent_constructed();
self.now_playing.set_info_visible(true);
display_add_css_provider(resource!("/components/playback.css"));
}
}
impl WidgetImpl for PlaybackWidget {}
impl BoxImpl for PlaybackWidget {}
}
glib::wrapper! {
pub struct PlaybackWidget(ObjectSubclass<imp::PlaybackWidget>) @extends gtk::Widget, gtk::Box;
}
impl PlaybackWidget {
pub fn set_title_and_artist(&self, title: &str, artist: &str) {
let widget = self.imp();
widget.now_playing.set_title_and_artist(title, artist);
}
pub fn reset_info(&self) {
let widget = self.imp();
widget.now_playing.reset_info();
self.set_song_duration(None);
}
fn set_artwork(&self, image: &gdk_pixbuf::Pixbuf) {
let widget = self.imp();
widget.now_playing.set_artwork(image);
}
pub fn set_artwork_from_url(&self, url: String, worker: &Worker) {
let weak_self = self.downgrade();
worker.send_local_task(async move {
let loader = ImageLoader::new();
let result = loader.load_remote(&url, "jpg", 48, 48).await;
if let (Some(ref _self), Some(ref result)) = (weak_self.upgrade(), result) {
_self.set_artwork(result);
}
});
}
pub fn set_song_duration(&self, duration: Option<f64>) {
let widget = self.imp();
let class = "seek-bar--active";
if let Some(duration) = duration {
self.add_css_class(class);
widget.seek_bar.set_range(0.0, duration);
widget.seek_bar.set_value(0.0);
widget.track_position.set_text("0∶00");
widget
.track_duration
.set_text(&format!("{}", format_duration(duration)));
widget.track_position.set_visible(true);
widget.track_duration.set_visible(true);
} else {
self.remove_css_class(class);
widget.seek_bar.set_range(0.0, 0.0);
widget.track_position.set_visible(false);
widget.track_duration.set_visible(false);
}
}
pub fn set_seek_position(&self, pos: f64) {
let widget = self.imp();
widget.seek_bar.set_value(pos);
widget.track_position.set_text(&format_duration(pos));
}
pub fn increment_seek_position(&self) {
let value = self.imp().seek_bar.value() + 1_000.0;
self.set_seek_position(value);
}
pub fn connect_now_playing_clicked<F>(&self, f: F)
where
F: Fn() + Clone + 'static,
{
let widget = self.imp();
let f_clone = f.clone();
widget.now_playing.connect_clicked(move |_| f_clone());
}
pub fn connect_seek<Seek>(&self, seek: Seek)
where
Seek: Fn(u32) + Clone + 'static,
{
let debouncer = Debouncer::new();
let widget = self.imp();
widget.seek_bar.set_increments(5_000.0, 10_000.0);
widget.seek_bar.connect_change_value(clone!(
#[weak(rename_to = _self)]
self,
#[upgrade_or]
glib::Propagation::Proceed,
move |_, _, requested| {
_self
.imp()
.track_position
.set_text(&format_duration(requested));
let seek = seek.clone();
debouncer.debounce(200, move || seek(requested as u32));
glib::Propagation::Proceed
}
));
}
pub fn set_playing(&self, is_playing: bool) {
let widget = self.imp();
widget.controls.set_playing(is_playing);
if is_playing {
widget.clock.start(clone!(
#[weak(rename_to = _self)]
self,
move || _self.increment_seek_position()
));
} else {
widget.clock.stop();
}
}
pub fn set_repeat_mode(&self, mode: RepeatMode) {
let widget = self.imp();
widget.controls.set_repeat_mode(mode);
}
pub fn set_shuffled(&self, shuffled: bool) {
let widget = self.imp();
widget.controls.set_shuffled(shuffled);
}
pub fn set_seekbar_visible(&self, visible: bool) {
let widget = self.imp();
widget.seek_bar.set_visible(visible);
}
pub fn set_volume(&self, value: f64) {
let widget = self.imp();
widget.volume_slider.set_value(value)
}
pub fn connect_play_pause<F>(&self, f: F)
where
F: Fn() + Clone + 'static,
{
let widget = self.imp();
widget.controls.connect_play_pause(f.clone());
}
pub fn connect_prev<F>(&self, f: F)
where
F: Fn() + Clone + 'static,
{
let widget = self.imp();
widget.controls.connect_prev(f.clone());
}
pub fn connect_next<F>(&self, f: F)
where
F: Fn() + Clone + 'static,
{
let widget = self.imp();
widget.controls.connect_next(f.clone());
}
pub fn connect_shuffle<F>(&self, f: F)
where
F: Fn() + Clone + 'static,
{
let widget = self.imp();
widget.controls.connect_shuffle(f.clone());
}
pub fn connect_repeat<F>(&self, f: F)
where
F: Fn() + Clone + 'static,
{
let widget = self.imp();
widget.controls.connect_repeat(f.clone());
}
pub fn connect_volume_changed<F>(&self, f: F)
where
F: Fn(f64) + Clone + 'static,
{
let widget = self.imp();
widget
.volume_slider
.connect_value_changed(move |scale| f(scale.value()));
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/playback/component.rs | src/app/components/playback/component.rs | use std::ops::Deref;
use std::rc::Rc;
use crate::app::components::EventListener;
use crate::app::models::*;
use crate::app::state::{PlaybackAction, PlaybackEvent, ScreenName, SelectionEvent};
use crate::app::{
ActionDispatcher, AppAction, AppEvent, AppModel, AppState, BrowserAction, Worker,
};
use super::playback_widget::PlaybackWidget;
pub struct PlaybackModel {
app_model: Rc<AppModel>,
dispatcher: Box<dyn ActionDispatcher>,
}
impl PlaybackModel {
pub fn new(app_model: Rc<AppModel>, dispatcher: Box<dyn ActionDispatcher>) -> Self {
Self {
app_model,
dispatcher,
}
}
fn state(&self) -> impl Deref<Target = AppState> + '_ {
self.app_model.get_state()
}
fn go_home(&self) {
self.dispatcher.dispatch(AppAction::ViewNowPlaying);
self.dispatcher
.dispatch(BrowserAction::NavigationPopTo(ScreenName::Home).into());
}
fn is_playing(&self) -> bool {
self.state().playback.is_playing()
}
fn is_shuffled(&self) -> bool {
self.state().playback.is_shuffled()
}
fn current_song(&self) -> Option<SongDescription> {
self.app_model.get_state().playback.current_song()
}
fn play_next_song(&self) {
self.dispatcher.dispatch(PlaybackAction::Next.into());
}
fn play_prev_song(&self) {
self.dispatcher.dispatch(PlaybackAction::Previous.into());
}
fn toggle_playback(&self) {
self.dispatcher.dispatch(PlaybackAction::TogglePlay.into());
}
fn toggle_shuffle(&self) {
self.dispatcher
.dispatch(PlaybackAction::ToggleShuffle.into());
}
fn toggle_repeat(&self) {
self.dispatcher
.dispatch(PlaybackAction::ToggleRepeat.into());
}
fn seek_to(&self, position: u32) {
self.dispatcher
.dispatch(PlaybackAction::Seek(position).into());
}
fn set_volume(&self, value: f64) {
self.dispatcher.dispatch(PlaybackAction::SetVolume(value).into())
}
}
pub struct PlaybackControl {
model: Rc<PlaybackModel>,
widget: PlaybackWidget,
worker: Worker,
}
impl PlaybackControl {
pub fn new(model: PlaybackModel, widget: PlaybackWidget, worker: Worker) -> Self {
let model = Rc::new(model);
widget.connect_play_pause(clone!(
#[weak]
model,
move || model.toggle_playback()
));
widget.connect_next(clone!(
#[weak]
model,
move || model.play_next_song()
));
widget.connect_prev(clone!(
#[weak]
model,
move || model.play_prev_song()
));
widget.connect_shuffle(clone!(
#[weak]
model,
move || model.toggle_shuffle()
));
widget.connect_repeat(clone!(
#[weak]
model,
move || model.toggle_repeat()
));
widget.connect_seek(clone!(
#[weak]
model,
move |position| model.seek_to(position)
));
widget.connect_now_playing_clicked(clone!(
#[weak]
model,
move || model.go_home()
));
widget.connect_volume_changed(clone!(
#[weak]
model,
move |value| model.set_volume(value)
));
Self {
model,
widget,
worker,
}
}
fn update_repeat(&self, mode: &RepeatMode) {
self.widget.set_repeat_mode(*mode);
}
fn update_shuffled(&self) {
self.widget.set_shuffled(self.model.is_shuffled());
}
fn update_playing(&self) {
let is_playing = self.model.is_playing();
self.widget.set_playing(is_playing);
}
fn update_current_info(&self) {
if let Some(song) = self.model.current_song() {
self.widget
.set_title_and_artist(&song.title, &song.artists_name());
self.widget.set_song_duration(Some(song.duration as f64));
if let Some(url) = song.art {
self.widget.set_artwork_from_url(url, &self.worker);
}
} else {
self.widget.reset_info();
}
}
fn sync_seek(&self, pos: u32) {
self.widget.set_seek_position(pos as f64);
}
}
impl EventListener for PlaybackControl {
fn on_event(&mut self, event: &AppEvent) {
match event {
AppEvent::PlaybackEvent(PlaybackEvent::PlaybackPaused)
| AppEvent::PlaybackEvent(PlaybackEvent::PlaybackResumed) => {
self.update_playing();
}
AppEvent::PlaybackEvent(PlaybackEvent::RepeatModeChanged(mode)) => {
self.update_repeat(mode);
}
AppEvent::PlaybackEvent(PlaybackEvent::ShuffleChanged(_)) => {
self.update_shuffled();
}
AppEvent::PlaybackEvent(PlaybackEvent::TrackChanged(_)) => {
self.update_current_info();
}
AppEvent::PlaybackEvent(PlaybackEvent::PlaybackStopped) => {
self.update_playing();
self.update_current_info();
}
AppEvent::PlaybackEvent(PlaybackEvent::SeekSynced(pos))
| AppEvent::PlaybackEvent(PlaybackEvent::TrackSeeked(pos)) => {
self.sync_seek(*pos);
}
AppEvent::SelectionEvent(SelectionEvent::SelectionModeChanged(active)) => {
self.widget.set_seekbar_visible(!active);
}
AppEvent::PlaybackEvent(PlaybackEvent::VolumeSet(value)) => {
self.widget.set_volume(*value)
}
_ => {}
}
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/artist/mod.rs | src/app/components/artist/mod.rs | use gtk::prelude::*;
use gtk::subclass::prelude::*;
use gtk::CompositeTemplate;
use crate::app::loader::ImageLoader;
use crate::app::models::ArtistModel;
use crate::app::Worker;
mod imp {
use super::*;
#[derive(Debug, Default, CompositeTemplate)]
#[template(resource = "/dev/diegovsky/Riff/components/artist.ui")]
pub struct ArtistWidget {
#[template_child]
pub artist: TemplateChild<gtk::Label>,
#[template_child]
pub avatar_btn: TemplateChild<gtk::Button>,
#[template_child]
pub avatar: TemplateChild<libadwaita::Avatar>,
}
#[glib::object_subclass]
impl ObjectSubclass for ArtistWidget {
const NAME: &'static str = "ArtistWidget";
type Type = super::ArtistWidget;
type ParentType = gtk::Box;
fn class_init(klass: &mut Self::Class) {
klass.bind_template();
}
fn instance_init(obj: &glib::subclass::InitializingObject<Self>) {
obj.init_template();
}
}
impl ObjectImpl for ArtistWidget {}
impl WidgetImpl for ArtistWidget {}
impl BoxImpl for ArtistWidget {}
}
glib::wrapper! {
pub struct ArtistWidget(ObjectSubclass<imp::ArtistWidget>) @extends gtk::Widget, gtk::Box;
}
impl Default for ArtistWidget {
fn default() -> Self {
Self::new()
}
}
impl ArtistWidget {
pub fn new() -> Self {
glib::Object::new()
}
pub fn for_model(model: &ArtistModel, worker: Worker) -> Self {
let _self = Self::new();
_self.bind(model, worker);
_self
}
pub fn connect_artist_pressed<F: Fn() + 'static>(&self, f: F) {
self.imp().avatar_btn.connect_clicked(move |_| {
f();
});
}
fn bind(&self, model: &ArtistModel, worker: Worker) {
let widget = self.imp();
if let Some(url) = model.image() {
let avatar = widget.avatar.downgrade();
worker.send_local_task(async move {
if let Some(avatar) = avatar.upgrade() {
let loader = ImageLoader::new();
let pixbuf = loader.load_remote(&url, "jpg", 200, 200).await;
let texture = pixbuf.as_ref().map(gdk::Texture::for_pixbuf);
avatar.set_custom_image(texture.as_ref());
}
});
}
model
.bind_property("artist", &*widget.artist, "label")
.flags(glib::BindingFlags::DEFAULT | glib::BindingFlags::SYNC_CREATE)
.build();
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Diegovsky/riff | https://github.com/Diegovsky/riff/blob/28e5c58658aaee9095b3ed7b6f92bfefeca4baa1/src/app/components/saved_tracks/saved_tracks.rs | src/app/components/saved_tracks/saved_tracks.rs | use gtk::prelude::*;
use gtk::subclass::prelude::*;
use gtk::CompositeTemplate;
use std::rc::Rc;
use super::SavedTracksModel;
use crate::app::components::{Component, EventListener, Playlist};
use crate::app::state::LoginEvent;
use crate::app::{AppEvent, Worker};
use libadwaita::subclass::prelude::BinImpl;
mod imp {
use super::*;
#[derive(Debug, Default, CompositeTemplate)]
#[template(resource = "/dev/diegovsky/Riff/components/saved_tracks.ui")]
pub struct SavedTracksWidget {
#[template_child]
pub song_list: TemplateChild<gtk::ListView>,
#[template_child]
pub scrolled_window: TemplateChild<gtk::ScrolledWindow>,
}
#[glib::object_subclass]
impl ObjectSubclass for SavedTracksWidget {
const NAME: &'static str = "SavedTracksWidget";
type Type = super::SavedTracksWidget;
type ParentType = libadwaita::Bin;
fn class_init(klass: &mut Self::Class) {
klass.bind_template();
}
fn instance_init(obj: &glib::subclass::InitializingObject<Self>) {
obj.init_template();
}
}
impl ObjectImpl for SavedTracksWidget {}
impl WidgetImpl for SavedTracksWidget {}
impl BinImpl for SavedTracksWidget {}
}
glib::wrapper! {
pub struct SavedTracksWidget(ObjectSubclass<imp::SavedTracksWidget>) @extends gtk::Widget, libadwaita::Bin;
}
impl SavedTracksWidget {
fn new() -> Self {
glib::Object::new()
}
fn connect_bottom_edge<F>(&self, f: F)
where
F: Fn() + 'static,
{
self.imp()
.scrolled_window
.connect_edge_reached(move |_, pos| {
if let gtk::PositionType::Bottom = pos {
f()
}
});
}
fn song_list_widget(&self) -> >k::ListView {
self.imp().song_list.as_ref()
}
}
pub struct SavedTracks {
widget: SavedTracksWidget,
model: Rc<SavedTracksModel>,
children: Vec<Box<dyn EventListener>>,
}
impl SavedTracks {
pub fn new(model: Rc<SavedTracksModel>, worker: Worker) -> Self {
let widget = SavedTracksWidget::new();
widget.connect_bottom_edge(clone!(
#[weak]
model,
move || {
model.load_more();
}
));
let playlist = Playlist::new(widget.song_list_widget().clone(), model.clone(), worker);
Self {
widget,
model,
children: vec![Box::new(playlist)],
}
}
}
impl Component for SavedTracks {
fn get_root_widget(&self) -> >k::Widget {
self.widget.upcast_ref()
}
fn get_children(&mut self) -> Option<&mut Vec<Box<dyn EventListener>>> {
Some(&mut self.children)
}
}
impl EventListener for SavedTracks {
fn on_event(&mut self, event: &AppEvent) {
match event {
AppEvent::Started | AppEvent::LoginEvent(LoginEvent::LoginCompleted) => {
self.model.load_initial();
}
_ => {}
}
self.broadcast_event(event);
}
}
| rust | MIT | 28e5c58658aaee9095b3ed7b6f92bfefeca4baa1 | 2026-01-04T20:22:28.974811Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.