A GameCube/Wii emulator and debugger written in Rust.
guided setup
Layle8b9b46e1d1fd
diff --git a/Cargo.lock b/Cargo.lockindex d72bec2..3f04fb9 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2383,6 +2383,7 @@ dependencies = ["serde","serde_bytes","spin_sleep",+ "tempfile","tokio","toml","tracing",diff --git a/README.md b/README.mdindex fb2fbd1..3432f98 100644--- a/README.md+++ b/README.md@@ -79,19 +79,23 @@ Prebuilt releases (including debug builds) can be downloaded [here](https://gith./tinyapp --dsp dsp_rom.bin --coef dsp_coef.bin --dvd YourGame.rvz```-A more modern and friendly experience is provided via `gecko` ([short preview on YouTube](https://www.youtube.com/watch?v=wg62ie71JP0)):+A more modern and friendly experience is provided via `gecko` ([short preview on YouTube](https://www.youtube.com/watch?v=aCQSc70FV4k)):-It scans the configured GameCube and Wii folders for `.iso`, `.rvz` and `.zip` files. Double-clicking on a row opens a dedicated player window for that game. The decoded GameCube IPL and DSP files are expected to be inside the `system` folder and **must** be named exactly as follows:+On first launch, a guided setup popup asks for your DSP ROM (`dsp_rom.bin`), DSP coefficient ROM (`dsp_coef.bin`), optional GameCube IPL and game folders. It validates and copies the system files with the correct names, automatically decodes an encoded IPL, saves your settings and scans your games. You can skip setup for now or reopen it from **Settings -> Guided Setup**.++You can also import an optional Wii NAND folder containing `title/` and `shared2/`. The wizard copies it into `fs/` (or `GECKO_FS_ROOT`) only if that destination does not already exist, preserving existing saves. Otherwise, leave NAND unselected to keep existing storage or generate it on first boot.++The launcher scans the configured GameCube and Wii folders for `.iso`, `.rvz` and `.zip` files. Double-clicking on a row opens a dedicated player window for that game. For manual setup, place the decoded GameCube IPL and DSP files inside `system` using the names below. Data paths are relative to the working directory or `GECKO_DATA_DIR` when set:```sh-<gecko exe dir>/+<gecko data dir>/config.toml # settings, auto-generatedcache/library.bin # cached library, auto-generatedscreenshots/ # F12 screenshots, auto-generatedinternal/ # contains SRAM and memory cards, auto-generated- system/ # system file folder (user provided!)+ system/ # system files, copied by guided setupIPL.bin # GameCube only (must be decoded! see multitool)dsp_rom.bin # GameCube and Wiidsp_coef.bin # GameCube and Wii@@ -169,15 +173,15 @@ Keyboard and player-window hotkeys are configurable the same way under `Settings`gecko` player window:-| Key | Action |-| ------- | --------------------------------------------------------------------- |-| `Space` | Pause / resume emulation |-| `Tab` | Toggle the speed limit (run uncapped) |-| `F5` | Save state (overwrites the game's existing state) |-| `F7` | Load state |-| `F10` | Toggle borderless fullscreen |-| `F11` | Toggle the FPS and emulation speed overlay |-| `F12` | Screenshot the emulated framebuffer to `<gecko exe dir>/screenshots/` |+| Key | Action |+| ------- | ---------------------------------------------------------------------- |+| `Space` | Pause / resume emulation |+| `Tab` | Toggle the speed limit (run uncapped) |+| `F5` | Save state (overwrites the game's existing state) |+| `F7` | Load state |+| `F10` | Toggle borderless fullscreen |+| `F11` | Toggle the FPS and emulation speed overlay |+| `F12` | Screenshot the emulated framebuffer to `<gecko data dir>/screenshots/` |</details>diff --git a/crates/app/Cargo.toml b/crates/app/Cargo.tomlindex b1d1d8e..dfe573b 100644--- a/crates/app/Cargo.toml+++ b/crates/app/Cargo.toml@@ -37,3 +37,4 @@ clap = { version = "4.6.1", features = ["derive"] }anyhow = "1.0.102"webbrowser = "1.0.5"reqwest = { version = "0.13.4", features = ["json"] }+tempfile = "3.27.0"diff --git a/crates/app/src/app.rs b/crates/app/src/app.rsindex 40c0671..645a2a6 100644--- a/crates/app/src/app.rs+++ b/crates/app/src/app.rs@@ -15,6 +15,7 @@ use crate::game::{AspectMode, CpuMode, Format, Game, Platform, ThemePreference};use crate::keybinds::{self, KeyTarget};use crate::library::{self, ScanProgress};use crate::player::{self, PlayerState, PlayerStatus};+use crate::setup::{self, Field, Setup, Step};use crate::theme::{self, Palette};use crate::update::{self, Outcome};use crate::widgets::input_settings::{self, BindTarget, InputTab, InvertTarget, KeyboardTab};@@ -28,6 +29,16 @@ const TOAST_DURATION: Duration = Duration::from_secs(3);#[derive(Debug, Clone)]pub enum Message {Noop,+ MenuSetup,+ SetupClose,+ SetupBack,+ SetupNext,+ SetupPick(Field),+ SetupClear(Field),+ SetupPicked(Field, Option<PathBuf>),+ SetupValidated(Result<(), String>),+ SetupInstall,+ SetupInstalled(Result<Box<Config>, String>),LibraryWindowOpened(window::Id),PlayerWindowOpened(window::Id, Box<Game>, Arc<PlayerState>),PlayerTick,@@ -132,6 +143,7 @@ pub struct App {search: String,search_lc: String,scanning: bool,+ setup: Option<Setup>,about_open: bool,input_open: bool,input_tab: InputTab,@@ -151,7 +163,11 @@ pub struct App {impl App {pub fn boot(cli_gcn: Option<PathBuf>, cli_wii: Option<PathBuf>) -> (Self, Task<Message>) {- let config = config::load(&config::config_path());+ let config_path = config::config_path();+ let config = config::load(&config_path);+ let setup = Setup::new(&config, cli_gcn.clone(), cli_wii.clone());+ let setup = setup.needed(&config, config_path.is_file()).then_some(setup);+let cache = cache::load(&cache::cache_path());let mut games: Vec<Game> = cache.entries.values().map(|e| e.game.clone()).collect();@@ -170,6 +186,7 @@ impl App {search: String::new(),search_lc: String::new(),scanning: false,+ setup,about_open: false,input_open: false,input_tab: InputTab::Gc,@@ -240,6 +257,114 @@ impl App {pub fn update(&mut self, message: Message) -> Task<Message> {match message {Message::Noop => Task::none(),+ Message::MenuSetup => {+ if self.setup.is_none() {+ self.setup = Some(Setup::new(+ &self.config,+ self.cli_gcn_override.clone(),+ self.cli_wii_override.clone(),+ ));+ }+ Task::none()+ }+ Message::SetupClose => {+ if self.idle_setup().is_some() {+ self.setup = None;+ }+ Task::none()+ }+ Message::SetupBack => {+ if let Some(setup) = self.idle_setup() {+ setup.step = setup.step.prev();+ setup.error = None;+ }+ Task::none()+ }+ Message::SetupClear(field) => {+ if let Some(setup) = self.idle_setup() {+ *setup.sources.path_mut(field) = None;+ setup.error = None;+ }+ Task::none()+ }+ Message::SetupPick(field) => {+ let Some(setup) = self.idle_setup() else {+ return Task::none();+ };++ setup.busy = true;+ Task::perform(setup::pick(field), move |path| Message::SetupPicked(field, path))+ }+ Message::SetupPicked(field, path) => {+ if let Some(setup) = &mut self.setup {+ setup.busy = false;+ if path.is_some() {+ *setup.sources.path_mut(field) = path;+ setup.error = None;+ }+ }+ Task::none()+ }+ Message::SetupNext => {+ let Some(setup) = self.idle_setup().filter(|s| s.step != Step::Finish) else {+ return Task::none();+ };++ setup.busy = true;+ setup.error = None;+ let sources = setup.sources.clone();+ let step = setup.step;+ Task::perform(+ async move {+ tokio::task::spawn_blocking(move || {+ setup::validate_step(&sources, step).map_err(|e| format!("{e:#}"))+ })+ .await+ .unwrap_or_else(|e| Err(e.to_string()))+ },+ Message::SetupValidated,+ )+ }+ Message::SetupValidated(result) => {+ if let Some(setup) = &mut self.setup {+ setup.busy = false;+ match result {+ Ok(()) => setup.step = setup.step.next(),+ Err(error) => setup.error = Some(error),+ }+ }+ Task::none()+ }+ Message::SetupInstall => {+ let Some(setup) = self.idle_setup().filter(|s| s.step == Step::Finish) else {+ return Task::none();+ };++ setup.busy = true;+ setup.error = None;+ let sources = setup.sources.clone();+ Task::perform(setup::run_install(sources, self.config.clone()), |result| {+ Message::SetupInstalled(result.map(Box::new))+ })+ }+ Message::SetupInstalled(result) => {+ match result {+ Ok(config) => {+ self.config = *config;+ self.setup = None;+ self.cli_gcn_override = None;+ self.cli_wii_override = None;+ return Task::done(Message::ScanRequested);+ }+ Err(error) => {+ if let Some(setup) = &mut self.setup {+ setup.busy = false;+ setup.error = Some(error);+ }+ }+ }+ Task::none()+ }Message::LibraryWindowOpened(id) => {self.library_window = Some(id);Task::none()@@ -291,10 +416,6 @@ impl App {}Message::ScanRequested => {let roots = self.effective_library_roots();- if roots.is_empty() {- return Task::none();- }-self.scanning = true;let prior = self.cache.clone();Task::stream(library::scan_library_stream(roots, prior)).map(Message::ScanProgress)@@ -766,7 +887,7 @@ impl App {let (msg, hint) = if self.scanning {("Scanning...", "Reading disc headers")} else if self.effective_library_roots().is_empty() {- ("No libraries set", "File → Set GameCube / Wii Folder...")+ ("No libraries set", "Choose a GameCube or Wii folder from the File menu")} else {("No games found", "Drop ISO, RVZ, or ZIP files into the library folder")};@@ -847,6 +968,9 @@ impl App {.into();}+ if let Some(setup) = &self.setup {+ root_element = stack![root_element, setup.view(palette, &self.config)].into();+ }root_element}@@ -898,6 +1022,10 @@ impl App {.into()}+ fn idle_setup(&mut self) -> Option<&mut Setup> {+ self.setup.as_mut().filter(|s| !s.busy)+ }+fn effective_library_roots(&self) -> Vec<PathBuf> {let mut roots = Vec::new();if let Some(p) = selfdiff --git a/crates/app/src/config.rs b/crates/app/src/config.rsindex 582da50..99806a5 100644--- a/crates/app/src/config.rs+++ b/crates/app/src/config.rs@@ -8,6 +8,7 @@ use crate::keybinds::KeyboardConfig;#[derive(Debug, Clone, Serialize, Deserialize)]#[serde(default)]pub struct Config {+ pub setup_completed: bool,pub gcn_library: Option<PathBuf>,pub wii_library: Option<PathBuf>,pub cpu_mode: CpuMode,@@ -166,6 +167,7 @@ fn default_sram_enabled() -> bool {impl Default for Config {fn default() -> Self {Self {+ setup_completed: false,gcn_library: None,wii_library: None,cpu_mode: CpuMode::default(),diff --git a/crates/app/src/main.rs b/crates/app/src/main.rsindex 54e8546..b9db5c0 100644--- a/crates/app/src/main.rs+++ b/crates/app/src/main.rs@@ -7,6 +7,7 @@ mod keybinds;mod library;mod library_disc;mod player;+mod setup;mod theme;mod update;mod widgets;diff --git a/crates/app/src/setup.rs b/crates/app/src/setup.rsnew file mode 100644index 0000000..a92de5b--- /dev/null+++ b/crates/app/src/setup.rs@@ -0,0 +1,584 @@+use std::fs;+use std::io::Write;+use std::path::{Path, PathBuf};++use anyhow::{Context, bail, ensure};+use iced::widget::{Space, button, column, container, opaque, row, scrollable, text};+use iced::{Alignment, Background, Border, Color, Element, Length};++use crate::app::Message;+use crate::config::{self, Config, DSP_COEF_FILE, DSP_ROM_FILE, IPL_FILE};+use crate::theme::Palette;+use crate::widgets::overlay;++#[derive(Debug, Clone, Copy)]+pub enum Field {+ Dsp,+ Coef,+ Ipl,+ GameCube,+ Wii,+ Nand,+}++impl Field {+ fn info(self) -> (&'static str, &'static str) {+ match self {+ Self::Dsp => ("DSP ROM", "Required"),+ Self::Coef => ("DSP coefficients", "Required"),+ Self::Ipl => ("GameCube IPL", "GameCube only"),+ Self::GameCube => ("GameCube games", "Optional"),+ Self::Wii => ("Wii games", "Optional"),+ Self::Nand => ("Wii NAND", "Optional"),+ }+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]+pub enum Step {+ System,+ Folders,+ Finish,+}++impl Step {+ const ALL: [Self; 3] = [Self::System, Self::Folders, Self::Finish];++ pub fn next(self) -> Self {+ match self {+ Self::System => Self::Folders,+ _ => Self::Finish,+ }+ }++ pub fn prev(self) -> Self {+ match self {+ Self::Finish => Self::Folders,+ _ => Self::System,+ }+ }++ fn label(self) -> &'static str {+ match self {+ Self::System => "System files",+ Self::Folders => "Game folders",+ Self::Finish => "Finish",+ }+ }+}++#[derive(Debug, Clone, Default)]+pub struct Sources {+ dsp: Option<PathBuf>,+ coef: Option<PathBuf>,+ ipl: Option<PathBuf>,+ gcn: Option<PathBuf>,+ wii: Option<PathBuf>,+ nand: Option<PathBuf>,+}++impl Sources {+ pub fn path_mut(&mut self, field: Field) -> &mut Option<PathBuf> {+ match field {+ Field::Dsp => &mut self.dsp,+ Field::Coef => &mut self.coef,+ Field::Ipl => &mut self.ipl,+ Field::GameCube => &mut self.gcn,+ Field::Wii => &mut self.wii,+ Field::Nand => &mut self.nand,+ }+ }++ fn path(&self, field: Field) -> &Option<PathBuf> {+ match field {+ Field::Dsp => &self.dsp,+ Field::Coef => &self.coef,+ Field::Ipl => &self.ipl,+ Field::GameCube => &self.gcn,+ Field::Wii => &self.wii,+ Field::Nand => &self.nand,+ }+ }+}++pub struct Setup {+ pub sources: Sources,+ pub step: Step,+ pub busy: bool,+ pub error: Option<String>,+}++impl Setup {+ pub fn new(cfg: &Config, gcn: Option<PathBuf>, wii: Option<PathBuf>) -> Self {+ let dir = cfg.system_dir_resolved();+ let existing = |path: &Option<PathBuf>, name| Config::resolve_in_dir(path, &dir, name).filter(|p| p.is_file());++ Self {+ sources: Sources {+ dsp: existing(&cfg.dsp_rom, DSP_ROM_FILE),+ coef: existing(&cfg.dsp_coef, DSP_COEF_FILE),+ ipl: existing(&cfg.ipl, IPL_FILE),+ gcn: gcn.or_else(|| cfg.gcn_library.clone()),+ wii: wii.or_else(|| cfg.wii_library.clone()),+ nand: None,+ },+ step: Step::System,+ busy: false,+ error: None,+ }+ }++ pub fn needed(&self, cfg: &Config, config_exists: bool) -> bool {+ !cfg.setup_completed+ && (!config_exists+ || self.sources.dsp.is_none()+ || self.sources.coef.is_none()+ || (cfg.gcn_library.is_some() && self.sources.ipl.is_none()))+ }++ pub fn view(&self, palette: &Palette, cfg: &Config) -> Element<'static, Message> {+ let heading = text("Set up Gecko").size(24).font(self::semibold()).color(palette.text);++ let mut steps = row![].spacing(16);+ for (index, step) in Step::ALL.into_iter().enumerate() {+ let color = if step == self.step {+ palette.text+ } else {+ palette.text_mute+ };+ let line = if step <= self.step {+ palette.accent+ } else {+ palette.border+ };+ steps = steps.push(+ column![+ text(format!("{} {}", index + 1, step.label())).size(12).color(color),+ self::divider(line),+ ]+ .spacing(10)+ .width(Length::Fill),+ );+ }++ let title = match self.step {+ Step::System => "Add your system files",+ Step::Folders => "Where are your games?",+ Step::Finish => "Ready to finish",+ };+ let mut content = column![text(title).size(17).font(self::semibold()).color(palette.text)].spacing(12);++ let fields_and_note = match self.step {+ Step::System => Some((+ [Field::Dsp, Field::Coef, Field::Ipl],+ "IPL is only needed for GameCube. Encoded IPLs are decoded automatically.",+ )),+ Step::Folders => Some((+ [Field::GameCube, Field::Wii, Field::Nand],+ "NAND is optional. Choose a root with title/ and shared2/, or leave it empty to use existing storage.",+ )),+ Step::Finish => None,+ };++ if let Some((fields, note)) = fields_and_note {+ let mut rows = column![];+ for (index, field) in fields.into_iter().enumerate() {+ if index > 0 {+ rows = rows.push(self::divider(palette.border));+ }+ rows = rows.push(self.path_row(field, palette));+ }+ content = content.push(rows).push(self::note(note, palette));+ } else {+ let names = if self.sources.ipl.is_some() {+ format!("{DSP_ROM_FILE} · {DSP_COEF_FILE} · {IPL_FILE}")+ } else {+ format!("{DSP_ROM_FILE} · {DSP_COEF_FILE}")+ };+ content = content+ .push(self::summary_row("System files", &cfg.system_dir_resolved(), palette))+ .push(self::note(names, palette))+ .push(self::divider(palette.border));++ for (label, path) in [("GameCube games", &self.sources.gcn), ("Wii games", &self.sources.wii)] {+ if let Some(path) = path {+ content = content.push(self::summary_row(label, path, palette));+ }+ }+ if self.sources.gcn.is_none() && self.sources.wii.is_none() {+ content = content.push(self::note(+ "Game folders can be added later from the File menu.",+ palette,+ ));+ }++ content = content.push(if self.sources.nand.is_some() {+ self::summary_row("Import Wii NAND to", &gecko::paths::fs_root(), palette)+ } else {+ self::note("Wii storage will be kept or created on first boot.", palette)+ });+ content = content.push(self::note("System files with these names will be replaced.", palette));+ if self.sources.ipl.is_none() {+ content = content.push(self::note("You can add a GameCube IPL later in Guided Setup.", palette));+ }+ }++ let enabled = !self.busy;+ let mut actions = row![+ self::action("Set up later", Message::SetupClose, palette, ButtonKind::Quiet, enabled),+ Space::new().width(Length::Fill),+ ]+ .spacing(8)+ .align_y(Alignment::Center);+ if self.step > Step::System {+ actions = actions.push(self::action(+ "Back",+ Message::SetupBack,+ palette,+ ButtonKind::Secondary,+ enabled,+ ));+ }+ let (label, message) = if self.step == Step::Finish {+ ("Finish setup", Message::SetupInstall)+ } else {+ ("Continue", Message::SetupNext)+ };+ actions = actions.push(self::action(label, message, palette, ButtonKind::Primary, enabled));++ let mut body = column![heading, steps, scrollable(content).height(Length::Fill).spacing(10)].spacing(24);+ if let Some(error) = &self.error {+ body = body.push(text(error.clone()).size(12).color(palette.purple));+ }+ if self.busy {+ body = body.push(self::note("Working... Please keep Gecko open.", palette));+ }+ let body = body.push(column![self::divider(palette.border), actions].spacing(16));++ opaque(overlay::modal(+ palette,+ 600.0,+ 24.0,+ Message::Noop,+ container(body).height(466).into(),+ ))+ .into()+ }++ fn path_row(&self, field: Field, palette: &Palette) -> Element<'static, Message> {+ let (label, hint) = field.info();+ let path = self.sources.path(field);++ let value: Element<'static, Message> = match path {+ Some(path) => self::path_text(path, palette),+ None => text("No selection").size(12).color(palette.text_mute).into(),+ };+ let info = column![+ row![+ text(label).size(13).font(self::semibold()).color(palette.text),+ text(hint).size(11).color(palette.text_mute)+ ]+ .spacing(10)+ .align_y(Alignment::Center),+ value,+ ]+ .spacing(6)+ .width(Length::Fill);++ let mut controls = row![self::action(+ if path.is_some() { "Change..." } else { "Choose..." },+ Message::SetupPick(field),+ palette,+ ButtonKind::Secondary,+ !self.busy,+ )]+ .spacing(4)+ .align_y(Alignment::Center);+ if path.is_some() {+ controls = controls.push(self::action(+ "Clear",+ Message::SetupClear(field),+ palette,+ ButtonKind::Quiet,+ !self.busy,+ ));+ } else {+ controls = controls.push(Space::new().width(53));+ }++ container(row![info, controls].spacing(14).align_y(Alignment::Center))+ .padding([14, 0])+ .into()+ }+}++fn semibold() -> iced::Font {+ iced::Font {+ weight: iced::font::Weight::Semibold,+ ..iced::Font::DEFAULT+ }+}++fn divider(color: Color) -> Element<'static, Message> {+ container(Space::new())+ .height(1)+ .width(Length::Fill)+ .style(move |_| container::Style {+ background: Some(color.into()),+ ..Default::default()+ })+ .into()+}++fn note(message: impl text::IntoFragment<'static>, palette: &Palette) -> Element<'static, Message> {+ text(message).size(12).color(palette.text_dim).into()+}++fn path_text(path: &Path, palette: &Palette) -> Element<'static, Message> {+ let full = path.display().to_string();+ let short = match full.char_indices().nth_back(44) {+ Some((start, _)) if full.chars().count() > 46 => format!("...{}", &full[start..]),+ _ => full,+ };++ self::note(short, palette)+}++fn summary_row(label: &'static str, path: &Path, palette: &Palette) -> Element<'static, Message> {+ column![+ text(label).size(13).font(self::semibold()).color(palette.text),+ self::path_text(path, palette)+ ]+ .spacing(5)+ .into()+}++#[derive(Clone, Copy)]+enum ButtonKind {+ Primary,+ Secondary,+ Quiet,+}++fn action(+ label: &'static str,+ message: Message,+ palette: &Palette,+ kind: ButtonKind,+ enabled: bool,+) -> Element<'static, Message> {+ let p = *palette;++ button(text(label).size(12).font(self::semibold()))+ .padding([8, 12])+ .on_press_maybe(enabled.then_some(message))+ .style(move |_, status| {+ let hovered = matches!(status, button::Status::Hovered | button::Status::Pressed);+ let disabled = matches!(status, button::Status::Disabled);+ let (background, foreground, border) = match kind {+ ButtonKind::Primary => (if hovered { p.text_dim } else { p.text }, p.bg, Color::TRANSPARENT),+ ButtonKind::Secondary => (if hovered { p.surface_2 } else { p.surface }, p.text, p.border_2),+ ButtonKind::Quiet => (+ if hovered { p.surface } else { Color::TRANSPARENT },+ p.text_dim,+ Color::TRANSPARENT,+ ),+ };++ button::Style {+ background: Some(Background::Color(if disabled { p.surface } else { background })),+ text_color: if disabled { p.text_mute } else { foreground },+ border: Border {+ color: border,+ width: 1.0,+ radius: 6.0.into(),+ },+ ..Default::default()+ }+ })+ .into()+}++pub async fn pick(field: Field) -> Option<PathBuf> {+ let dialog = rfd::AsyncFileDialog::new().set_title(field.info().0);++ let handle = match field {+ Field::Dsp | Field::Coef | Field::Ipl => dialog.pick_file().await,+ _ => dialog.pick_folder().await,+ };+ handle.map(|h| h.path().to_path_buf())+}++fn read_rom(path: &Path, size: usize) -> anyhow::Result<Vec<u8>> {+ let metadata = fs::metadata(path).with_context(|| format!("Cannot read {}", path.display()))?;+ ensure!(+ metadata.is_file() && metadata.len() == size as u64,+ "{} must be a {}-byte ROM file",+ path.display(),+ size+ );++ let data = fs::read(path).with_context(|| format!("Cannot read {}", path.display()))?;+ ensure!(+ data.len() == size,+ "{} changed while being read; select it again",+ path.display()+ );+ Ok(data)+}++fn system_files(sources: &Sources) -> anyhow::Result<Vec<(&'static str, Vec<u8>)>> {+ let dsp = sources+ .dsp+ .as_deref()+ .context("Choose the DSP ROM before continuing.")?;+ let coef = sources+ .coef+ .as_deref()+ .context("Choose the DSP coefficient ROM before continuing.")?;++ let mut files = vec![+ (DSP_ROM_FILE, self::read_rom(dsp, 8192)?),+ (DSP_COEF_FILE, self::read_rom(coef, 4096)?),+ ];++ if let Some(path) = &sources.ipl {+ let mut data = self::read_rom(path, image::ipl::IPL_ROM_SIZE)?;+ if image::ipl::is_encoded(&data) {+ image::ipl::scramble(&mut data);+ }+ ensure!(+ !image::ipl::is_encoded(&data),+ "{} is not a recognized encoded or decoded GameCube IPL",+ path.display()+ );+ files.push((IPL_FILE, data));+ }++ Ok(files)+}++pub fn validate_step(sources: &Sources, step: Step) -> anyhow::Result<()> {+ match step {+ Step::System => self::system_files(sources).map(drop),+ Step::Folders => self::validate_folders(sources),+ Step::Finish => Ok(()),+ }+}++fn validate_folders(sources: &Sources) -> anyhow::Result<()> {+ for path in [&sources.gcn, &sources.wii].into_iter().flatten() {+ ensure!(path.is_dir(), "Game folder does not exist: {}", path.display());+ }++ ensure!(+ sources.gcn.is_none() || sources.ipl.is_some(),+ "Choose a GameCube IPL in step 1 to use a GameCube library."+ );+ Ok(())+}++fn stage_nand(source: &Path, destination: &Path) -> anyhow::Result<Option<tempfile::TempDir>> {+ let source = fs::canonicalize(source).context("Cannot open the selected NAND folder")?;+ if destination.exists() && fs::canonicalize(destination)? == source {+ return Ok(None);+ }++ ensure!(+ !destination.exists(),+ "Wii storage already exists at {}. Leave NAND unselected to keep it. Importing requires an unused destination.",+ destination.display()+ );+ ensure!(+ source.join("title").is_dir() && source.join("shared2").is_dir(),+ "Choose a NAND root containing title/ and shared2/."+ );++ let parent = destination+ .parent()+ .filter(|p| !p.as_os_str().is_empty())+ .unwrap_or(Path::new("."));+ fs::create_dir_all(parent)?;+ ensure!(+ !fs::canonicalize(parent)?.starts_with(&source),+ "The NAND destination cannot be inside the source folder."+ );++ let stage = tempfile::tempdir_in(parent)?;+ let root = stage.path().join("nand");+ fs::create_dir(&root)?;++ for entry in walkdir::WalkDir::new(&source).follow_links(false) {+ let entry = entry.context("Cannot read a NAND entry")?;+ let target = root.join(entry.path().strip_prefix(&source)?);+ if entry.file_type().is_dir() {+ fs::create_dir_all(&target)?;+ } else if entry.file_type().is_file() {+ fs::copy(entry.path(), &target).with_context(|| format!("Cannot copy {}", entry.path().display()))?;+ } else {+ bail!(+ "NAND contains a symbolic link or special file: {}",+ entry.path().display()+ );+ }+ }++ Ok(Some(stage))+}++pub fn install(sources: Sources, mut cfg: Config, config_path: &Path, nand_dest: &Path) -> anyhow::Result<Config> {+ let files = self::system_files(&sources)?;+ self::validate_folders(&sources)?;++ let nand_stage = sources+ .nand+ .as_deref()+ .map(|p| self::stage_nand(p, nand_dest))+ .transpose()?+ .flatten();++ let system = cfg.system_dir_resolved();+ fs::create_dir_all(&system).with_context(|| format!("Cannot create {}", system.display()))?;++ let mut staged = Vec::new();+ for (name, data) in files {+ let mut file = tempfile::NamedTempFile::new_in(&system)?;+ file.write_all(&data)?;+ file.as_file().sync_all()?;+ staged.push((system.join(name), file));+ }++ for (path, file) in staged {+ file.persist(&path)+ .with_context(|| format!("Cannot install {}", path.display()))?;+ }++ if let Some(stage) = nand_stage {+ ensure!(+ !nand_dest.exists(),+ "Wii storage was created during setup; it has not been replaced."+ );+ fs::rename(stage.path().join("nand"), nand_dest).context("Cannot install Wii NAND")?;+ }++ cfg.dsp_rom = Some(system.join(DSP_ROM_FILE));+ cfg.dsp_coef = Some(system.join(DSP_COEF_FILE));+ if sources.ipl.is_some() {+ cfg.ipl = Some(system.join(IPL_FILE));+ }+ cfg.gcn_library = sources.gcn;+ cfg.wii_library = sources.wii;+ cfg.setup_completed = true;++ config::save(config_path, &cfg).context("Files were installed, but settings could not be saved. Check permissions on config.toml. If retrying, leave NAND unselected.")?;+ Ok(cfg)+}++pub async fn run_install(sources: Sources, cfg: Config) -> Result<Config, String> {+ let path = config::config_path();+ let nand = gecko::paths::fs_root();++ tokio::task::spawn_blocking(move || self::install(sources, cfg, &path, &nand).map_err(|e| format!("{e:#}")))+ .await+ .map_err(|e| e.to_string())?+}diff --git a/crates/app/src/widgets.rs b/crates/app/src/widgets.rsindex 8fa7f70..f36d5aa 100644--- a/crates/app/src/widgets.rs+++ b/crates/app/src/widgets.rs@@ -1,6 +1,7 @@pub mod badge;pub mod cover;pub mod game_row;+pub mod icons;pub mod input_settings;pub mod menubar;pub mod overlay;diff --git a/crates/app/src/widgets/icons.rs b/crates/app/src/widgets/icons.rsnew file mode 100644index 0000000..0586656--- /dev/null+++ b/crates/app/src/widgets/icons.rs@@ -0,0 +1,52 @@+use iced::advanced::graphics::mesh::{self, Renderer as _};+use iced::advanced::widget::Tree;+use iced::advanced::{Layout, Widget, layout, mouse, renderer};+use iced::{Color, Element, Length, Rectangle, Size, Transformation};++pub fn chevron_right<Message: 'static>(color: Color) -> Element<'static, Message> {+ Element::new(ChevronRight(color))+}++struct ChevronRight(Color);++impl<Message, Theme> Widget<Message, Theme, iced::Renderer> for ChevronRight {+ fn size(&self) -> Size<Length> {+ Size::new(Length::Fixed(14.0), Length::Fixed(14.0))+ }++ fn layout(&mut self, _tree: &mut Tree, _renderer: &iced::Renderer, limits: &layout::Limits) -> layout::Node {+ layout::Node::new(limits.resolve(14.0, 14.0, Size::ZERO))+ }++ fn draw(+ &self,+ _tree: &Tree,+ renderer: &mut iced::Renderer,+ _theme: &Theme,+ _style: &renderer::Style,+ layout: Layout<'_>,+ _cursor: mouse::Cursor,+ viewport: &Rectangle,+ ) {+ let bounds = layout.bounds();+ let Some(clip_bounds) = bounds.intersection(viewport) else {+ return;+ };+ let color = iced::advanced::graphics::color::pack(self.0);+ let vertices = [[4.5, 2.5], [9.0, 7.0], [4.5, 11.5], [3.5, 10.5], [7.0, 7.0], [3.5, 3.5]]+ .into_iter()+ .map(|[x, y]| mesh::SolidVertex2D {+ position: [bounds.x + x, bounds.y + y],+ color,+ })+ .collect();+ renderer.draw_mesh(mesh::Mesh::Solid {+ buffers: mesh::Indexed {+ vertices,+ indices: vec![0, 1, 4, 0, 4, 5, 1, 2, 3, 1, 3, 4],+ },+ transformation: Transformation::IDENTITY,+ clip_bounds,+ });+ }+}diff --git a/crates/app/src/widgets/menubar.rs b/crates/app/src/widgets/menubar.rsindex 2230fd6..04affe5 100644--- a/crates/app/src/widgets/menubar.rs+++ b/crates/app/src/widgets/menubar.rs@@ -243,6 +243,8 @@ fn settings_menu(let check = |label: &'static str, msg: Message, on: bool| Item::new(self::menu_item(palette, label, msg, Some(on)));Menu::new(vec![+ Item::new(self::menu_item(palette, "Guided Setup...", Message::MenuSetup, None)),+ Item::new(self::separator(palette)),self::submenu(palette,"Execution Engine",@@ -351,7 +353,7 @@ fn submenu(let content = row![text(label).size(13).color(text_color),Space::new().width(Length::Fill),- text("›").size(13).color(palette.text_dim),+ crate::widgets::icons::chevron_right(palette.text_dim),].align_y(iced::Alignment::Center);diff --git a/crates/gecko/src/paths.rs b/crates/gecko/src/paths.rsindex edc97fd..a0d82de 100644--- a/crates/gecko/src/paths.rs+++ b/crates/gecko/src/paths.rs@@ -21,6 +21,14 @@ pub fn resolve(rel: impl AsRef<Path>) -> PathBuf {self::base().join(rel)}+pub fn fs_root() -> PathBuf {+ if let Some(custom) = std::env::var_os("GECKO_FS_ROOT") {+ return PathBuf::from(custom);+ }++ self::resolve("fs")+}+pub fn cache(rel: impl AsRef<Path>) -> PathBuf {self::resolve(Path::new("cache").join(rel))}diff --git a/crates/gecko/src/starlet.rs b/crates/gecko/src/starlet.rsindex 9fe5805..5427402 100644--- a/crates/gecko/src/starlet.rs+++ b/crates/gecko/src/starlet.rs@@ -46,7 +46,7 @@ impl Starlet {handles: HashMap::new(),next_fd: 1,pending: VecDeque::new(),- host_fs_root: self::default_host_fs_root(),+ host_fs_root: crate::paths::fs_root(),delivery_scheduled: false,}}@@ -180,14 +180,6 @@ impl Starlet {}}-fn default_host_fs_root() -> PathBuf {- if let Some(custom) = std::env::var_os("GECKO_FS_ROOT") {- return PathBuf::from(custom);- }-- crate::paths::resolve("fs")-}-impl System<{ crate::WII }> {pub fn initialize_starlet_devices(&mut self) {use crate::hollywood::ipc::{self, stm};diff --git a/crates/image/src/ipl.rs b/crates/image/src/ipl.rsnew file mode 100644index 0000000..924aaa2--- /dev/null+++ b/crates/image/src/ipl.rs@@ -0,0 +1,67 @@+pub const IPL_ROM_SIZE: usize = 0x200000;+const SCRAMBLE_START: usize = 0x100;+const SCRAMBLE_SIZE: usize = 0x1AFE00;++pub fn scramble(data: &mut [u8]) {+ assert_eq!(data.len(), IPL_ROM_SIZE);++ let region = &mut data[SCRAMBLE_START..SCRAMBLE_START + SCRAMBLE_SIZE];++ let mut acc: u8 = 0;+ let mut nacc: u8 = 0;++ let mut t: u16 = 0x2953;+ let mut u: u16 = 0xD9C2;+ let mut v: u16 = 0x3FF1;++ let mut x: u8 = 1;++ let mut it = 0;+ while it < region.len() {+ let t0 = (t & 1) as u8;+ let t1 = ((t >> 1) & 1) as u8;+ let u0 = (u & 1) as u8;+ let u1 = ((u >> 1) & 1) as u8;+ let v0 = (v & 1) as u8;++ x ^= t1 ^ v0;+ x ^= u0 | u1;+ x ^= (t0 ^ u1 ^ v0) & (t0 ^ u0);++ if t0 == u0 {+ v >>= 1;+ if v0 != 0 {+ v ^= 0xB3D0;+ }+ }++ if t0 == 0 {+ u >>= 1;+ if u0 != 0 {+ u ^= 0xFB10;+ }+ }++ t >>= 1;+ if t0 != 0 {+ t ^= 0xA740;+ }++ nacc += 1;+ acc = acc.wrapping_shl(1) + x;+ if nacc == 8 {+ region[it] ^= acc;+ nacc = 0;+ it += 1;+ }+ }+}++pub fn is_encoded(data: &[u8]) -> bool {+ if data.len() < 0x104 {+ return true;+ }++ let w = u32::from_be_bytes(data[0x100..0x104].try_into().unwrap());+ w != 0x3C800011+}diff --git a/crates/image/src/lib.rs b/crates/image/src/lib.rsindex b44c884..cc060fa 100644--- a/crates/image/src/lib.rs+++ b/crates/image/src/lib.rs@@ -2,6 +2,7 @@pub mod banner;pub mod dol;pub mod dvd;+pub mod ipl;pub mod iso;#[cfg(feature = "rvz")]pub mod rvz;diff --git a/crates/multitool/src/ipl.rs b/crates/multitool/src/ipl.rsindex e490d96..4941ce9 100644--- a/crates/multitool/src/ipl.rs+++ b/crates/multitool/src/ipl.rs@@ -3,71 +3,7 @@ use crate::cli::Action;use std::path::Path;use std::{fs, process};-const IPL_ROM_SIZE: usize = 0x200000;-const SCRAMBLE_START: usize = 0x100;-const SCRAMBLE_SIZE: usize = 0x1AFE00;--fn decode(data: &mut [u8]) {- let region = &mut data[SCRAMBLE_START..SCRAMBLE_START + SCRAMBLE_SIZE];-- let mut acc: u8 = 0;- let mut nacc: u8 = 0;-- let mut t: u16 = 0x2953;- let mut u: u16 = 0xD9C2;- let mut v: u16 = 0x3FF1;-- let mut x: u8 = 1;-- let mut it = 0;- while it < region.len() {- let t0 = (t & 1) as u8;- let t1 = ((t >> 1) & 1) as u8;- let u0 = (u & 1) as u8;- let u1 = ((u >> 1) & 1) as u8;- let v0 = (v & 1) as u8;-- x ^= t1 ^ v0;- x ^= u0 | u1;- x ^= (t0 ^ u1 ^ v0) & (t0 ^ u0);-- if t0 == u0 {- v >>= 1;- if v0 != 0 {- v ^= 0xB3D0;- }- }-- if t0 == 0 {- u >>= 1;- if u0 != 0 {- u ^= 0xFB10;- }- }-- t >>= 1;- if t0 != 0 {- t ^= 0xA740;- }-- nacc += 1;- acc = acc.wrapping_shl(1) + x;- if nacc == 8 {- region[it] ^= acc;- nacc = 0;- it += 1;- }- }-}--fn is_encoded(data: &[u8]) -> bool {- if data.len() < 0x104 {- return true;- }- let w = u32::from_be_bytes(data[0x100..0x104].try_into().unwrap());- // Decoded BS1 starts with `lis r4, 0x0011`- w != 0x3C800011-}+use image::ipl::{IPL_ROM_SIZE, is_encoded, scramble};pub fn process(file: &str, output: Option<&str>, action: Action) {let mut data = fs::read(file).unwrap_or_else(|e| {@@ -92,7 +28,7 @@ pub fn process(file: &str, output: Option<&str>, action: Action) {println!("{action_label}: {file}");println!(" {copyright}");- decode(&mut data);+ scramble(&mut data);let out_path = match output {Some(p) => p.to_string(),diff --git a/images/launcher.png b/images/launcher.pngindex bfba468..2676977 100644Binary files a/images/launcher.png and b/images/launcher.png differ