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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 8 additions & 7 deletions Cargo.lock

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

10 changes: 5 additions & 5 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,12 @@ ash = { version = "0.38", default-features = false, features = ["debug", "std"]
# Same Skia as the shared console; only the PS5 build adds the Vulkan backend (pf-ps5-vk).
skia-safe = { version = "0.153", features = ["textlayout"] }
# One REV for all three shared crates: a tag and a rev build two copies whose types don't unify.
punktfunk-core = { git = "https://git.unom.io/unom/punktfunk", rev = "9eb2eb64113b6848e921a7153edd2248b8f61d7a", features = ["quic"] }
pf-client-core = { git = "https://git.unom.io/unom/punktfunk", rev = "9eb2eb64113b6848e921a7153edd2248b8f61d7a", default-features = false }
pf-console-ui = { git = "https://git.unom.io/unom/punktfunk", rev = "9eb2eb64113b6848e921a7153edd2248b8f61d7a", default-features = false }
pf-client-video = { git = "https://git.unom.io/unom/punktfunk", rev = "9eb2eb64113b6848e921a7153edd2248b8f61d7a", default-features = false, features = ["pyrowave"] }
punktfunk-core = { git = "https://git.unom.io/unom/punktfunk", rev = "6e1381e3e976ece0362c734b2b3cf39ffd5537d1", features = ["quic"] }
pf-client-core = { git = "https://git.unom.io/unom/punktfunk", rev = "6e1381e3e976ece0362c734b2b3cf39ffd5537d1", default-features = false }
pf-console-ui = { git = "https://git.unom.io/unom/punktfunk", rev = "6e1381e3e976ece0362c734b2b3cf39ffd5537d1", default-features = false }
pf-client-video = { git = "https://git.unom.io/unom/punktfunk", rev = "6e1381e3e976ece0362c734b2b3cf39ffd5537d1", default-features = false, features = ["pyrowave"] }
# The messages the console UI and this title word their text from; the kit reads the same rev.
pf-l10n = { git = "https://git.unom.io/unom/punktfunk", rev = "9eb2eb64113b6848e921a7153edd2248b8f61d7a", default-features = false, features = ["client", "console", "host"] }
pf-l10n = { git = "https://git.unom.io/unom/punktfunk", rev = "6e1381e3e976ece0362c734b2b3cf39ffd5537d1", default-features = false, features = ["client", "console", "host"] }

[workspace.lints.rust]
unsafe_op_in_unsafe_fn = "deny"
Expand Down
6 changes: 5 additions & 1 deletion crates/pf-ps5-app/src/platform/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
//! Three implementations exist: the console (`pf-ps5-platform`), a developer box
//! (`pf-ps5-host`) and [`fake`] for tests. The binary builds one [`Platform`] and hands it to
//! [`crate::run`]; nothing in this crate names a console API, a Vulkan handle or a file path
//! outside [`Storage::data_dir`]. The contract tests in `tests/seams.rs` are the spec.
//! outside [`Storage::data_dir`] and [`DeviceInfo::fonts`]. The contract tests in
//! `tests/seams.rs` are the spec.

pub mod fake;

Expand Down Expand Up @@ -43,6 +44,9 @@ pub struct DeviceInfo {
pub ui: String,
/// The system's languages as BCP-47 tags, most preferred first. Empty reads English.
pub languages: Vec<String>,
/// The system's font files for what Geist lacks (Han, kana, Hangul), most fitting first.
/// Empty where Skia has a font manager to ask instead.
pub fonts: Vec<std::path::PathBuf>,
}

/// Refresh rate of the scan-out, in millihertz (59 940, 119 880).
Expand Down
7 changes: 6 additions & 1 deletion crates/pf-ps5-app/src/runtime/menu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ pub(super) fn run(app: &mut App, notice: Option<String>) -> Result<UiOutcome> {
let caps = crate::core::caps::video_caps();
let opts = ConsoleOptions {
device_name: "PlayStation 5".into(),
device_code: pf_client_core::trust::device_code(&app.identity),
version: Some(crate::core::build_id()),
system_keyboard: false,
tv: true,
Expand Down Expand Up @@ -70,7 +71,11 @@ pub(super) fn run(app: &mut App, notice: Option<String>) -> Result<UiOutcome> {
.selected_row()
.map_or(ConsoleEntry::Home, |row| ConsoleEntry::Library(Box::new(row))),
};
let mut console = Console::new(opts, entry, &handles).context("console shell")?;
let faces = super::system_faces(&app.device.fonts);
let faces: Vec<&[u8]> = faces.iter().map(Vec::as_slice).collect();
let mut console = Console::new(opts, entry, &handles)
.and_then(|console| console.with_fallback_fonts(&faces))
.context("console shell")?;
let viewport = {
let (w, h) = app.display.ui_size();
Viewport::plain(w, h)
Expand Down
45 changes: 45 additions & 0 deletions crates/pf-ps5-app/src/runtime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,38 @@ fn alternate(app: &mut App) -> Option<ExitPlan> {
}
}

/// The system's font files ([`crate::platform::DeviceInfo::fonts`]) as faces for the kit's
/// fallback. A file that is missing or not a face is logged and left out: the kit refuses all
/// faces for one bad one.
fn system_faces(paths: &[std::path::PathBuf]) -> Vec<Vec<u8>> {
let started = std::time::Instant::now();
let mgr = skia_safe::FontMgr::new();
let faces: Vec<Vec<u8>> = paths
.iter()
.filter_map(|path| match std::fs::read(path) {
Ok(bytes) if mgr.new_from_data(skia_safe::Data::new_copy(&bytes), None).is_some() => Some(bytes),
Ok(_) => {
tracing::warn!(path = %path.display(), "system font is not a face");
None
}
Err(e) => {
tracing::warn!(path = %path.display(), error = %e, "system font unreadable");
None
}
})
.collect();
if !paths.is_empty() {
tracing::info!(
"fonts: {} of {} system faces, {} KiB, in {} ms",
faces.len(),
paths.len(),
faces.iter().map(Vec::len).sum::<usize>() / 1024,
started.elapsed().as_millis()
);
}
faces
}

/// A panic on any thread goes to the log with its frames, then the process aborts.
fn install_panic_hook() {
std::panic::set_hook(Box::new(|info| {
Expand All @@ -174,3 +206,16 @@ fn teardown(connected: session::Connected) {
connected.disconnect_quit();
connected.shutdown_and_quit();
}

#[cfg(test)]
mod tests {
#[test]
fn a_missing_or_foreign_file_is_no_face() {
let dir = std::env::temp_dir().join(format!("pf-faces-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let text = dir.join("not-a-font.otf");
std::fs::write(&text, b"not a font").unwrap();
assert!(super::system_faces(&[text, dir.join("missing.ttf")]).is_empty());
let _ = std::fs::remove_dir_all(dir);
}
}
4 changes: 3 additions & 1 deletion crates/pf-ps5-app/src/runtime/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,9 @@ fn stream(
};
let router = PadRouter::new(&settings.shortcuts, &settings.overlay_actions);
let input = InputThread::start(pads, connected.input(), settings.gamepad_type(), router);
let fonts = match pf_console_ui::theme::build_fonts() {
let faces = super::system_faces(&app.device.fonts);
let faces: Vec<&[u8]> = faces.iter().map(Vec::as_slice).collect();
let fonts = match pf_console_ui::theme::build_fonts_with(&faces) {
Ok(f) => Some(f),
Err(e) => {
tracing::warn!("overlay fonts: {e:#}");
Expand Down
17 changes: 13 additions & 4 deletions crates/pf-ps5-app/src/ui/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ use pf_console_ui::{
SpeedPhase, Stale, WakeStatus,
};
use punktfunk_core::client::NativeClient;
use punktfunk_core::PunktfunkError;

use crate::core::model::{GameEntry, KnownHost};
use crate::services::discovery::{DiscoveredHost, Discovery};
Expand Down Expand Up @@ -318,6 +319,8 @@ impl Service {
game_presets: h.game_presets.clone(),
profile: h.profile.clone(),
running: String::new(),
// Never fetched: this client offers no screen pick.
screens: None,
key,
}
}
Expand Down Expand Up @@ -345,7 +348,7 @@ impl Service {
.map_err(|e| crate::core::errors::pair_message(&e))
}),
// The host parks this console until its operator approves it, held to the advertised
// fingerprint. Never streams.
// fingerprint. Never streams. The console offers a request only for a row with one.
ConsoleCmd::RequestAccess {
addr,
port,
Expand All @@ -355,6 +358,10 @@ impl Service {
} => {
let pin = shared::parse_fp(&fp_hex);
self.start_pair(addr, port, req, move |addr, port, id| {
let Some(pin) = pin else {
let e = PunktfunkError::InvalidArg("fingerprint");
return Err(crate::core::errors::access_message(&e));
};
NativeClient::request_access(addr, port, (&id.0, &id.1), pin, &device_name, budget::HOST_WAIT, None)
.map_err(|e| crate::core::errors::access_message(&e))
});
Expand Down Expand Up @@ -427,8 +434,8 @@ impl Service {
ConsoleCmd::SetPin { key, preset_id, pin } => self.set_pin(&key, preset_id, pin),
ConsoleCmd::PadTest { on } => self.pad_test = on,
// Nothing to do: no status client (Resume badges stay off), no clipboard, no prompt
// here, no title is endable or installable (`to_model`), and the profile picker is
// off (`ConsoleOptions::profiles`).
// here, no title is endable or installable (`to_model`), the profile picker is off
// (`ConsoleOptions::profiles`), and no row carries `screens`.
ConsoleCmd::RefreshRunning { .. }
| ConsoleCmd::SetClipboard { .. }
| ConsoleCmd::PromptAnswer { .. }
Expand All @@ -437,7 +444,8 @@ impl Service {
| ConsoleCmd::FetchProfiles { .. }
| ConsoleCmd::FetchAvatar { .. }
| ConsoleCmd::WakeProfile { .. }
| ConsoleCmd::SetProfile { .. } => {}
| ConsoleCmd::SetProfile { .. }
| ConsoleCmd::SetScreen { .. } => {}
}
}

Expand Down Expand Up @@ -1203,6 +1211,7 @@ fn discovered_row(d: &DiscoveredHost) -> HostRow {
// Needs `/api/v1/status`, which this client does not ask — the same reason
// `LibraryGame::running` is false here. Empty renders as no line.
running: String::new(),
screens: None,
}
}

Expand Down
1 change: 1 addition & 0 deletions crates/pf-ps5-host/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,7 @@ pub fn platform(opts: &Options) -> Result<Platform> {
gpu,
ui,
languages: Vec::new(),
fonts: Vec::new(),
},
})
}
Expand Down
15 changes: 14 additions & 1 deletion crates/pf-ps5-platform/src/console/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,17 @@ fn system_languages() -> Vec<String> {
tags
}

/// The console's CJK font files for the kit, by the system language, from the first font
/// directory that exists. Reports to the kernel log, since logging does not exist yet.
fn system_fonts(language: Option<&str>) -> Vec<PathBuf> {
use std::io::Write as _;
let dirs = crate::fonts::dirs(pf_ps5_sys::kernel::sandbox_word().as_deref());
let found = dirs.iter().find(|d| d.is_dir());
let line = found.map_or_else(|| format!("none of {dirs:?}"), |d| d.display().to_string());
let _ = writeln!(klog::Klog::default(), "punktfunk-ps5: fonts: {line}");
found.map(|d| crate::fonts::faces(d, language)).unwrap_or_default()
}

/// The data directory and the kernel log, for the probe, which needs nothing else.
pub fn probe_parts() -> (PathBuf, Box<dyn std::io::Write + Send>) {
(storage().0, Box::new(klog::Klog::default()))
Expand All @@ -176,14 +187,16 @@ pub fn platform() -> Result<Platform> {
let dev = Arc::new(GpuDevice::new(entry(), Target::Display).context("bring up the GPU")?);
let slot = Arc::new(VideoSlot::default());
let presenter = Presenter::new(dev.clone(), slot.clone()).context("bring up the display")?;
let languages = system_languages();
let device = DeviceInfo {
platform: "ps5",
model: "PlayStation 5".into(),
firmware: pf_ps5_sys::kernel::system_version()
.map_or_else(String::new, |v| format!("{:x}.{:02x}", v >> 24, (v >> 16) & 0xff)),
gpu: format!("{} (mesa {MESA_PIN})", dev.name),
ui: presenter.ui(),
languages: system_languages(),
fonts: system_fonts(languages.first().map(String::as_str)),
languages,
};
Ok(Platform {
display: Box::new(presenter),
Expand Down
72 changes: 72 additions & 0 deletions crates/pf-ps5-platform/src/fonts.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
//! The console's own fonts for what Geist lacks: Han, kana and Hangul. Pure, so it tests anywhere.

use std::path::{Path, PathBuf};

/// Kana and JIS kanji (`SST-JPPRO-R`).
const JAPANESE: &str = "SSTJpPro-Regular.otf";
/// Simplified Chinese Hei (`SST-CNGB-HEI-R`).
const CHINESE: &str = "DFHEI5-SONY.ttf";
/// Hangul only (`SCE-EXT-HANGUL-R`).
const KOREAN: &str = "SCEPS4Yoongd-Medium.otf";

/// The system font directory under the sandbox's word, else where it lives outside a sandbox.
pub fn dirs(word: Option<&str>) -> Vec<PathBuf> {
let mut dirs: Vec<PathBuf> = word
.map(|w| Path::new("/").join(w).join("common/font"))
.into_iter()
.collect();
dirs.push(PathBuf::from("/preinst/common/font"));
dirs
}

/// The CJK faces in `dir`, the system language's own first. The kit draws a character from the
/// first face that has it, so a Han character takes that region's shape; Japanese leads otherwise.
pub fn faces(dir: &Path, language: Option<&str>) -> Vec<PathBuf> {
let lang = language.unwrap_or_default();
let order = if lang.starts_with("zh") {
[CHINESE, JAPANESE, KOREAN]
} else if lang.starts_with("ko") {
[KOREAN, JAPANESE, CHINESE]
} else {
[JAPANESE, CHINESE, KOREAN]
};
order.iter().map(|name| dir.join(name)).collect()
}

#[cfg(test)]
mod tests {
use super::*;

fn names(language: Option<&str>) -> Vec<String> {
faces(Path::new("/f"), language)
.iter()
.map(|p| p.file_name().unwrap().to_string_lossy().into_owned())
.collect()
}

#[test]
fn the_system_language_leads() {
assert_eq!(names(Some("ja")), [JAPANESE, CHINESE, KOREAN]);
assert_eq!(names(Some("zh-Hans")), [CHINESE, JAPANESE, KOREAN]);
assert_eq!(names(Some("zh-Hant")), [CHINESE, JAPANESE, KOREAN]);
assert_eq!(names(Some("ko")), [KOREAN, JAPANESE, CHINESE]);
}

#[test]
fn any_other_language_reads_japanese_first() {
assert_eq!(names(Some("en-US")), [JAPANESE, CHINESE, KOREAN]);
assert_eq!(names(None), [JAPANESE, CHINESE, KOREAN]);
}

#[test]
fn the_sandbox_directory_comes_first() {
assert_eq!(
dirs(Some("abcdefghij")),
[
PathBuf::from("/abcdefghij/common/font"),
PathBuf::from("/preinst/common/font")
]
);
assert_eq!(dirs(None), [PathBuf::from("/preinst/common/font")]);
}
}
8 changes: 8 additions & 0 deletions crates/pf-ps5-platform/src/language.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,14 @@ mod tests {
assert_eq!(tag(29), Some("id"));
}

#[test]
fn chinese_japanese_and_korean_carry_their_script() {
assert_eq!(tag(0), Some("ja"));
assert_eq!(tag(9), Some("ko"));
assert_eq!(tag(10), Some("zh-Hant"));
assert_eq!(tag(11), Some("zh-Hans"));
}

#[test]
fn an_unknown_value_is_no_language() {
assert_eq!(tag(-1), None);
Expand Down
Loading