diff --git a/.github/workflows/addons.yml b/.github/workflows/addons.yml index 4180cfa..83c365b 100644 --- a/.github/workflows/addons.yml +++ b/.github/workflows/addons.yml @@ -1,21 +1,24 @@ name: Addons package -# Builds the community add-ons package (packaging/addons/build.sh) and, on -# main or by hand, publishes it on GitHub Packages as the OCI artifact -# ghcr.io//corerules-addons, tagged with the app version and latest. +# Builds the add-ons installer, one AppImage with the add-ons inside +# (crates/cr-addons), and, on main or by hand, publishes it on GitHub +# Packages as the OCI artifact ghcr.io//corerules-addons, tagged with +# the app version and latest. on: push: branches: [main] paths: - 'addons/**' - - 'packaging/addons/**' - - 'packaging/extract-data.sh' + - 'crates/cr-addons/**' + - 'data/addons/**' + - 'packaging/appimage/**' - '.github/workflows/addons.yml' pull_request: paths: - 'addons/**' - - 'packaging/addons/**' - - 'packaging/extract-data.sh' + - 'crates/cr-addons/**' + - 'data/addons/**' + - 'packaging/appimage/**' - '.github/workflows/addons.yml' workflow_dispatch: @@ -23,40 +26,38 @@ permissions: contents: read packages: write -env: - CARGO_TERM_COLOR: always - jobs: package: runs-on: ubuntu-24.04 + container: + image: ghcr.io/flathub-infra/flatpak-github-actions:gnome-51 + options: --privileged steps: - uses: actions/checkout@v4 - - run: sudo apt-get update && sudo apt-get install -y musl-tools - - uses: dtolnay/rust-toolchain@stable - with: - targets: x86_64-unknown-linux-musl - - uses: Swatinem/rust-cache@v2 - - run: packaging/addons/build.sh - - name: Check the package + # The checkout belongs to the runner's user; root inside the SDK + # sandbox has no capabilities to write there. + - run: chown -R "$(id -u):$(id -g)" "$GITHUB_WORKSPACE" + - id: v + run: echo "version=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1)" >> "$GITHUB_OUTPUT" + - run: packaging/appimage/build-in-sdk.sh ${{ steps.v.outputs.version }} addons + - name: Check the AppImage run: | - tmp=$(mktemp -d) - tar -xzf target/addons/addons-comunidade-expansion.tar.gz -C "$tmp" - cd "$tmp/addons-comunidade-expansion" - sha256sum -c SHA256SUMS - ! ls ./*.AppImage 2>/dev/null - ./instalar-addons.sh --help + cd target/AppDir + test -x usr/bin/corerules-addons + test -f usr/share/icons/hicolor/256x256/apps/io.github.brahm.CoreRules.Addons.png + ls -l "$GITHUB_WORKSPACE"/dist/CoreRules-Addons-*.AppImage - if: github.event_name != 'pull_request' uses: oras-project/setup-oras@v1 - if: github.event_name != 'pull_request' name: Publish on GitHub Packages run: | - version=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1) - image=ghcr.io/${GITHUB_REPOSITORY_OWNER,,}/corerules-addons + version=${{ steps.v.outputs.version }} + owner=$(echo "$GITHUB_REPOSITORY_OWNER" | tr '[:upper:]' '[:lower:]') echo "${{ secrets.GITHUB_TOKEN }}" | oras login ghcr.io -u "${{ github.actor }}" --password-stdin - cd target/addons - oras push "$image:$version,latest" \ + cd dist + oras push "ghcr.io/$owner/corerules-addons:$version,latest" \ --artifact-type application/vnd.corerules.addons \ --annotation "org.opencontainers.image.source=https://github.com/${GITHUB_REPOSITORY}" \ - --annotation "org.opencontainers.image.description=Addons da comunidade para o Core Rules Expansion, com o instalador" \ + --annotation "org.opencontainers.image.description=Instalador dos addons da comunidade para o Core Rules Expansion" \ --annotation "org.opencontainers.image.version=$version" \ - addons-comunidade-expansion.tar.gz:application/gzip + "CoreRules-Addons-$version-x86_64.AppImage:application/vnd.appimage" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0e4e622..3118f03 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -15,5 +15,5 @@ jobs: with: components: clippy, rustfmt - run: cargo fmt --check - - run: cargo clippy --all-targets -- -D warnings - - run: cargo test + - run: cargo clippy --workspace --all-targets -- -D warnings + - run: cargo test --workspace diff --git a/Cargo.lock b/Cargo.lock index 975195e..ed49a59 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -14,6 +14,12 @@ version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + [[package]] name = "cairo-rs" version = "0.20.12" @@ -53,6 +59,17 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +[[package]] +name = "cr-addons" +version = "0.7.2" +dependencies = [ + "cr-formats", + "cr-store", + "gtk4", + "libadwaita", + "lzma-rs", +] + [[package]] name = "cr-cli" version = "0.7.2" @@ -94,6 +111,21 @@ dependencies = [ "thiserror", ] +[[package]] +name = "crc" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d" +dependencies = [ + "crc-catalog", +] + +[[package]] +name = "crc-catalog" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853" + [[package]] name = "encoding_rs" version = "0.8.35" @@ -488,6 +520,16 @@ version = "0.2.190" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" +[[package]] +name = "lzma-rs" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "297e814c836ae64db86b36cf2a557ba54368d03f6afcd7d947c266692f71115e" +dependencies = [ + "byteorder", + "crc", +] + [[package]] name = "memchr" version = "2.8.3" diff --git a/Cargo.toml b/Cargo.toml index efc3267..52d7a0c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,9 @@ [workspace] resolver = "3" -members = ["crates/cr-i18n", "crates/cr-formats", "crates/cr-store", "crates/cr-cli", "crates/cr-gtk"] +members = ["crates/cr-i18n", "crates/cr-formats", "crates/cr-store", "crates/cr-cli", "crates/cr-gtk", "crates/cr-addons"] +# The add-ons installer carries 9 MB of add-ons; only its own AppImage +# builds it (cargo build -p cr-addons). +default-members = ["crates/cr-i18n", "crates/cr-formats", "crates/cr-store", "crates/cr-cli", "crates/cr-gtk"] [workspace.package] version = "0.7.2" diff --git a/README.md b/README.md index 4f8d845..fd95061 100644 --- a/README.md +++ b/README.md @@ -174,12 +174,13 @@ your own use and do not redistribute it. [`addons/`](addons/README.md) holds 686 add-ons the community made for Core Rules 2.0 and the Expansion (races, classes, kits, spells, monsters, modules and the AD&D Core Rules User Database), converted to the -Expansion's format and consolidated into one file. The package, with that -file, an installer and the `cr` tool, is published on GitHub Packages as +Expansion's format and consolidated into one file. They ship as a +self-installing app, a single AppImage with the add-ons inside +(`crates/cr-addons`, GTK 4 and libadwaita), published on GitHub Packages as [`corerules-addons`](https://github.com/brahm/corerules/pkgs/container/corerules-addons); it needs the app 0.7.2 or newer. The [guide](addons/README.md), which says -how to download and install it, and the [report](addons/relatorio.md) are -in Portuguese. +how to download and use it, and the [report](addons/relatorio.md) are in +Portuguese. ## Testing against your own installation @@ -200,6 +201,7 @@ CORERULES_DIR="$HOME/.wine/drive_c/Program Files/AD&D Core Rules 2.0" cargo test | `cr-cli` | `cr` command for inspecting data | | `cr-i18n` | Translations of the interface (`po/*.po`, built into the program) | | `cr-gtk` | The GNOME app | +| `cr-addons` | The community add-ons installer, with the add-ons built in | The backend crates have no GTK dependency so macOS and Windows front ends can reuse them later. diff --git a/addons/README.md b/addons/README.md index 740f4b5..c125aac 100644 --- a/addons/README.md +++ b/addons/README.md @@ -4,9 +4,19 @@ Este pacote junta 686 addons feitos pela comunidade para o AD&D Core Rules 2.0 e Mapas do Map Maker II e desenhos do Campaign Mapper não fazem parte do pacote, porque o app não trata desses programas. +## O instalador + +Os addons são distribuídos num único arquivo, `CoreRules-Addons-VERSÃO-x86_64.AppImage`. Ele é um programa com janela que leva os addons dentro dele e os instala no Core Rules, sem script nem outros arquivos. + +O que é preciso: + +* Linux x86-64 com glibc 2.43 ou mais nova (Fedora 44, Ubuntu 26.04 ou mais novos). +* O app Core Rules 0.7.2 ou mais novo, da [página de releases](https://github.com/brahm/corerules/releases). Até a versão 0.7.1 o app não lia parte destes addons: classes com habilidades por nível (`CClassFreeSpellsOb`) e o que a Expansion com patch grava. +* Os dados da sua Expansion no app. Se ainda não tiver, abra o Core Rules e use **Extrair dados do CD…** no menu. + ## Onde baixar -O pacote é publicado no GitHub Packages do projeto, como [`corerules-addons`](https://github.com/brahm/corerules/pkgs/container/corerules-addons). É um artefato OCI, e não uma imagem de contêiner: o `docker pull` que a página do GitHub mostra não serve. Baixe com o [ORAS](https://oras.land): +O instalador é publicado no GitHub Packages do projeto, como [`corerules-addons`](https://github.com/brahm/corerules/pkgs/container/corerules-addons). É um artefato OCI, e não uma imagem de contêiner: o `docker pull` que a página do GitHub mostra não serve. Baixe com o [ORAS](https://oras.land): ```sh oras pull ghcr.io/brahm/corerules-addons:latest @@ -21,80 +31,50 @@ layer=$(curl -s -H "Authorization: Bearer $token" \ -H "Accept: application/vnd.oci.image.manifest.v1+json" \ "https://ghcr.io/v2/$repo/manifests/latest" | grep -o '"digest":"sha256:[0-9a-f]*"' | tail -n 1 | cut -d'"' -f4) -curl -L -H "Authorization: Bearer $token" -o addons-comunidade-expansion.tar.gz \ +curl -L -H "Authorization: Bearer $token" -o CoreRules-Addons-x86_64.AppImage \ "https://ghcr.io/v2/$repo/blobs/$layer" ``` Além de `latest`, cada versão do app tem a sua tag, como `0.7.2`. -## O que vem no pacote - -`addons-comunidade-expansion.tar.gz` traz: - -| arquivo | para que serve | -|---|---| -| `Comunidade.xpx` | os addons consolidados, no formato da Expansion | -| `instalar-addons.sh` | importa os addons no pacote de dados do app | -| `bin/cr` | a ferramenta de linha de comando que o instalador usa (binário estático, roda em qualquer Linux x86-64) | -| `extract-data.sh` | cria o pacote de dados a partir da sua instalação do Core Rules | -| `README.md`, `relatorio.md`, `compatibilidade.csv`, `conflitos.csv` | este guia e o relatório por addon | -| `SHA256SUMS` | as somas de verificação | - -O aplicativo não vem no pacote. Instale o Core Rules 0.7.2 ou mais novo pela [página de releases](https://github.com/brahm/corerules/releases) (.deb, .rpm, Flatpak ou AppImage). Até a versão 0.7.1 o app não lia parte destes addons: classes com habilidades por nível (`CClassFreeSpellsOb`) e o que a Expansion com patch grava. - -## O que é preciso - -* Linux x86-64. -* O app Core Rules 0.7.2 ou mais novo. -* Uma instalação sua do AD&D Core Rules 2.0 Expansion, no Wine ou copiada do CD. Os addons não trazem as regras. - ## Instalação -1. Abra o pacote: - - ```sh - tar -xzf addons-comunidade-expansion.tar.gz - cd addons-comunidade-expansion - ``` - -2. Crie o pacote de dados do app a partir da sua instalação, se ainda não tiver um. Ele fica em `~/.local/share/corerules/data`. +1. Torne o arquivo executável e abra-o: ```sh - ./extract-data.sh --install "$HOME/.wine" # Core Rules instalado no Wine - ./extract-data.sh --install /caminho/do/Program # ou a pasta que tem Database/ + chmod +x CoreRules-Addons-*-x86_64.AppImage + ./CoreRules-Addons-*-x86_64.AppImage ``` -3. Instale os addons: + Sem FUSE, rode com `APPIMAGE_EXTRACT_AND_RUN=1`. - ```sh - ./instalar-addons.sh - ``` +2. A janela mostra a pasta de dados que o Core Rules usa, normalmente `~/.local/share/corerules/data`. Para outra instalação da Expansion, como a do programa original no Wine, clique em **Escolher…** e indique a pasta que tem `Database`. - Para outra instalação da Expansion, informe a pasta: `./instalar-addons.sh /caminho/da/instalacao`. +3. Clique em **Instalar**. A importação leva menos de um minuto. -4. Abra o app. Os addons aparecem nos bancos de dados do usuário (Raças, Classes, Magias, Monstros e o resto) e os personagens dos módulos na lista de personagens. +4. Abra o Core Rules. Os addons aparecem nos bancos de dados do usuário (Raças, Classes, Magias, Monstros e o resto) e os personagens dos módulos na lista de personagens. Se o app já estava aberto, feche e abra de novo. ## O que o instalador faz 1. Confere se a pasta é uma instalação da Expansion. -2. Guarda `UserDbas/` e `Chars/` num `.tar.gz` ao lado da pasta, por exemplo `data-antes-dos-addons-20261017-230000.tar.gz`. +2. Copia `UserDbas/` e `Chars/` para uma pasta ao lado, por exemplo `data-antes-dos-addons-20261019-010700/`. 3. Importa o `Comunidade.xpx`. Um registro do usuário com o mesmo nome de um addon é substituído pelo do addon, como no Import do programa original. 4. Importa de novo só as classes. Uma combinação raça/classe que cita duas classes novas só entra quando as duas já existem. -Um registro do log fica ao lado da pasta. Os avisos "No race/class combinations could be added" da primeira passagem são esperados, porque a segunda passagem resolve todos eles. +O registro da importação fica ao lado da pasta, como `data-addons-20261019-010700.log`, e o botão **Abrir o registro** o mostra no fim. -Rodar o instalador de novo não duplica os personagens. Se a pasta estiver dentro de um prefixo do Wine, ele pede confirmação antes de mexer; o programa original do CD também lê o `Comunidade.xpx`, mas a leitura no original leva cerca de 35 minutos. +Instalar de novo não duplica os personagens. Se a pasta estiver dentro de um prefixo do Wine, o instalador pede confirmação antes de mexer. O programa original do CD também lê os addons, mas o Import dele leva cerca de 35 minutos. ## Como desfazer -Apague `UserDbas/` e `Chars/` da pasta de dados e extraia a cópia de segurança no lugar: +Troque `UserDbas/` e `Chars/` pela cópia de segurança, pondo no lugar de `DATA` a data da cópia que quer usar: ```sh cd ~/.local/share/corerules rm -rf data/UserDbas data/Chars -tar -xzf data-antes-dos-addons-*.tar.gz -C data +cp -r data-antes-dos-addons-DATA/UserDbas data-antes-dos-addons-DATA/Chars data/ ``` -## Como o pacote é gerado +## Como o instalador é gerado -`packaging/addons/build.sh` monta o pacote a partir de `addons/Comunidade.xpx.xz` e do `cr` compilado deste repositório. O workflow `Addons package` (`.github/workflows/addons.yml`) roda esse script e publica o resultado no GitHub Packages a cada mudança na main. O instalador fica em `packaging/addons/instalar-addons.sh`. +O instalador é o crate `crates/cr-addons`, em Rust com GTK 4 e libadwaita. Ele embute `addons/Comunidade.xpx.xz` e importa pelo mesmo código do app (`cr-store`). `packaging/appimage/build-in-sdk.sh VERSÃO addons` gera a AppImage no SDK do GNOME 51, e o workflow `Addons package` (`.github/workflows/addons.yml`) a publica no GitHub Packages a cada mudança na main. diff --git a/addons/relatorio.md b/addons/relatorio.md index 0b531c5..0248161 100644 --- a/addons/relatorio.md +++ b/addons/relatorio.md @@ -2,7 +2,7 @@ O `addons.zip` (50.842.950 bytes) traz 686 pacotes: 492 `.xpx` da Expansion e 194 `.xpt` do Core Rules 2.0, contando a User Database e os dois arquivos que precisaram de conserto. Todos foram consolidados num único pacote, `Comunidade.xpx`, no formato que o `TSRP3.EXE` do CD da Expansion lê. -O pacote `addons-comunidade-expansion.tar.gz` e como instalá-lo estão no [README.md](README.md). Junto deste relatório: +O instalador, que leva o `Comunidade.xpx` dentro dele, e como usá-lo estão no [README.md](README.md). Junto deste relatório: | arquivo | conteúdo | |---|---| @@ -58,10 +58,11 @@ Algumas regras do Import do original se aplicam aqui: * **Leitura e regravação:** os 686 pacotes, o consolidado incluído, são lidos e regravados byte a byte pelo leitor do projeto. * **Original da Expansion no Wine:** o diálogo Import do original abriu o `Comunidade.xpx` e listou os itens. A leitura levou cerca de 35 minutos. O Import All não foi executado no original. * **Edição no app Linux:** depois da instalação, cada registro dos addons foi aberto, editado e salvo pelos mesmos editores que o app usa, e relido depois. Foram 10.993 magias, 173 armadilhas, 160 poderes psiônicos, 1.874 tipos de monstro, 5.315 monstros, 515 raças, 558 classes, 16.290 partes, 59 tesouros, 299 encontros e os 105 personagens importados. Nenhum falhou. Regravar os bancos sem mudanças mantém os arquivos idênticos byte a byte. Salvar um registro pelo editor faz os mesmos ajustes do original, como tirar espaços do fim do nome. Dez registros têm o nome de um registro padrão: seis classes ("Fighter", "Cleric", "Mage", "Illusionist", "Ranger" e "Thief"), três magias e uma raça. O app recusava salvá-los e agora aceita, desde que o nome continue o mesmo. -* **Script de instalação:** testado numa cópia limpa do pacote de dados. - * Importou 36.716 itens e 105 personagens em cerca de 40 segundos. +* **Instalador:** a AppImage foi testada numa cópia limpa do pacote de dados. + * Importou 36.716 itens, 105 deles personagens, em menos de um minuto. * A segunda passagem terminou sem nenhum aviso. - * Rodar o script de novo não duplica personagens nem altera os registros, a não ser por 4 combinações de raças cujo nome se repete no pacote. + * Os bancos do usuário ficaram idênticos byte a byte aos que o antigo script de instalação gravava. + * Instalar de novo não duplica personagens nem altera os registros, a não ser por 4 combinações de raças cujo nome se repete no pacote. ## Imagens e documentação diff --git a/crates/cr-addons/Cargo.toml b/crates/cr-addons/Cargo.toml new file mode 100644 index 0000000..ebe286b --- /dev/null +++ b/crates/cr-addons/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "cr-addons" +description = "Installer of the community add-ons for Core Rules" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + +[[bin]] +name = "corerules-addons" +path = "src/main.rs" + +[dependencies] +cr-formats.workspace = true +cr-store.workspace = true +gtk = { package = "gtk4", version = "0.9", features = ["v4_14"] } +adw = { package = "libadwaita", version = "0.7", features = ["v1_5"] } +lzma-rs = "0.3" diff --git a/crates/cr-addons/src/install.rs b/crates/cr-addons/src/install.rs new file mode 100644 index 0000000..bebfdff --- /dev/null +++ b/crates/cr-addons/src/install.rs @@ -0,0 +1,180 @@ +//! Installing the add-ons into a data folder, without the interface: the +//! same steps as the old `instalar-addons.sh`. + +use std::fmt::Write as _; +use std::fs; +use std::io; +use std::path::{Path, PathBuf}; + +use cr_formats::export::ExportFile; +use cr_store::Installation; +use cr_store::export::{Category, ImportReport, contents}; + +/// The consolidated add-ons, compressed with xz. +static PACKAGE: &[u8] = include_bytes!("../../../addons/Comunidade.xpx.xz"); + +/// Written into `UserDbas/` once the add-ons are in; a second install then +/// leaves the characters out, which would otherwise come in twice. +const MARKER: &str = ".addons-comunidade"; + +/// What a folder offers for the install. +pub enum Folder { + Ready { + install: Installation, + /// The add-ons were installed there before. + again: bool, + /// The folder is the original program's, inside a Wine prefix. + wine: bool, + }, + /// A Core Rules 2.0 installation; the add-ons are the Expansion's. + Core20, + NotAnInstallation, +} + +pub fn check(dir: &Path) -> Folder { + let Ok(install) = Installation::open(dir) else { + return Folder::NotAnInstallation; + }; + if install.is_core20() { + return Folder::Core20; + } + let again = install + .path("UserDbas") + .is_some_and(|d| d.join(MARKER).exists()); + let wine = install.root().to_string_lossy().contains("/drive_c/"); + Folder::Ready { + install, + again, + wine, + } +} + +/// The built-in package, unpacked and read. +pub fn package() -> Result { + let mut data = Vec::new(); + lzma_rs::xz_decompress(&mut io::Cursor::new(PACKAGE), &mut data) + .map_err(|e| format!("Os addons embutidos estão corrompidos: {e}"))?; + ExportFile::parse(&data).map_err(|e| format!("Não consegui ler os addons embutidos: {e}")) +} + +/// Copies `UserDbas/` and `Chars/` into a folder beside the data folder; +/// returns that folder. +pub fn backup(install: &Installation, stamp: &str) -> Result { + let to = beside(install.root(), &format!("antes-dos-addons-{stamp}")); + for name in ["UserDbas", "Chars"] { + if let Some(from) = install.path(name) { + let target = to.join(from.file_name().unwrap_or(name.as_ref())); + copy_dir(&from, &target) + .map_err(|e| format!("Não consegui copiar {}: {e}", from.display()))?; + } + } + Ok(to) +} + +/// What the install did. +pub struct Outcome { + pub imported: usize, + pub characters: usize, + pub log: PathBuf, +} + +/// Imports `file` into `install`, then the classes again: a race/class +/// combination that names two new classes only comes in once both exist. +pub fn import(install: &Installation, file: &ExportFile, stamp: &str) -> Result { + let items = contents(file); + let again = matches!(check(install.root()), Folder::Ready { again: true, .. }); + let first: Option> = again.then(|| { + (0..items.len()) + .filter(|&n| items[n].category != Category::Character) + .collect() + }); + let failed = |e: cr_store::Error| format!("A importação falhou: {e}"); + let report = install.import(file, first.as_deref()).map_err(failed)?; + let classes: Vec = (0..items.len()) + .filter(|&n| items[n].category == Category::Class) + .collect(); + let second = install.import(file, Some(&classes)).map_err(failed)?; + + let mut log = String::new(); + write_report(&mut log, &report); + log.push_str("=== segunda passagem (classes)\n"); + write_report(&mut log, &second); + let path = beside(install.root(), &format!("addons-{stamp}.log")); + fs::write(&path, log).map_err(|e| format!("Não consegui gravar {}: {e}", path.display()))?; + if let Some(userdbas) = install.path("UserDbas") { + let _ = fs::write(userdbas.join(MARKER), stamp); + } + Ok(Outcome { + imported: report.imported.len(), + characters: report.characters.len(), + log: path, + }) +} + +/// The report in the words `cr import` prints. +fn write_report(out: &mut String, report: &ImportReport) { + for c in &report.imported { + let _ = writeln!(out, "imported {}: {}", c.category.label(), c.name); + } + for (category, name) in &report.replaced { + let _ = writeln!(out, "replaced {}: {name}", category.label()); + } + for c in &report.skipped { + let _ = writeln!(out, "skipped {}: {}", c.category.label(), c.name); + } + for (c, name) in &report.renamed { + let _ = writeln!(out, "renamed {}: {} to {name}", c.category.label(), c.name); + } + for file in &report.characters { + let _ = writeln!(out, "wrote Chars/{file}"); + } + for warning in &report.warnings { + let _ = writeln!(out, "warning: {warning}"); + } +} + +/// `data` → `data-SUFFIX`, in the same parent folder. +fn beside(root: &Path, suffix: &str) -> PathBuf { + let name = root + .file_name() + .map_or("data".into(), |n| n.to_string_lossy()); + root.with_file_name(format!("{name}-{suffix}")) +} + +fn copy_dir(from: &Path, to: &Path) -> io::Result<()> { + fs::create_dir_all(to)?; + for entry in fs::read_dir(from)? { + let entry = entry?; + let target = to.join(entry.file_name()); + if entry.file_type()?.is_dir() { + copy_dir(&entry.path(), &target)?; + } else { + fs::copy(entry.path(), target)?; + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_built_in_package_reads() { + let file = package().unwrap(); + assert!(file.is_expansion()); + let items = contents(&file); + assert_eq!(items.len(), 36_716); + let characters = items.iter().filter(|c| c.category == Category::Character); + assert_eq!(characters.count(), 105); + } + + #[test] + fn backups_and_logs_sit_beside_the_folder() { + let root = Path::new("/home/u/.local/share/corerules/data"); + assert_eq!( + beside(root, "addons-1.log"), + Path::new("/home/u/.local/share/corerules/data-addons-1.log") + ); + } +} diff --git a/crates/cr-addons/src/main.rs b/crates/cr-addons/src/main.rs new file mode 100644 index 0000000..f7760b8 --- /dev/null +++ b/crates/cr-addons/src/main.rs @@ -0,0 +1,358 @@ +//! The community add-ons installer: one window that imports the +//! consolidated add-ons, built into the program, into the Core Rules data +//! folder. The add-ons and their documents are in Portuguese, and so is +//! this window. + +mod install; + +use std::cell::RefCell; +use std::path::PathBuf; +use std::rc::Rc; + +use adw::prelude::*; +use cr_store::Installation; +use gtk::{gdk, gio, glib}; +use install::Folder; + +const APP_ID: &str = "io.github.brahm.CoreRules.Addons"; + +static ICON: &[u8] = include_bytes!( + "../../../data/addons/icons/hicolor/256x256/apps/io.github.brahm.CoreRules.Addons.png" +); + +fn main() -> glib::ExitCode { + let app = adw::Application::builder().application_id(APP_ID).build(); + app.connect_activate(|app| { + gtk::Window::set_default_icon_name(APP_ID); + Window::new(app).window.present(); + }); + app.run() +} + +#[derive(Clone)] +struct Window { + window: adw::ApplicationWindow, + stack: gtk::Stack, + folder_row: adw::ActionRow, + notice: gtk::Label, + install_button: gtk::Button, + progress: adw::StatusPage, + done: adw::StatusPage, + log: Rc>>, + dir: Rc>>, +} + +impl Window { + fn new(app: &adw::Application) -> Self { + let window = adw::ApplicationWindow::builder() + .application(app) + .title("Addons da comunidade") + .default_width(560) + .default_height(640) + .width_request(360) + .height_request(294) + .build(); + + let folder_row = adw::ActionRow::builder() + .title("Pasta de dados do Core Rules") + .subtitle_selectable(true) + .build(); + let choose = gtk::Button::builder() + .label("Escolher…") + .valign(gtk::Align::Center) + .build(); + folder_row.add_suffix(&choose); + let group = adw::PreferencesGroup::new(); + group.add(&folder_row); + let notice = gtk::Label::builder() + .wrap(true) + .xalign(0.0) + .css_classes(["dim-label"]) + .build(); + let install_button = gtk::Button::builder() + .label("Instalar") + .halign(gtk::Align::Center) + .css_classes(["pill", "suggested-action"]) + .build(); + let form = gtk::Box::builder() + .orientation(gtk::Orientation::Vertical) + .spacing(18) + .build(); + form.append(&group); + form.append(¬ice); + form.append(&install_button); + let clamp = adw::Clamp::builder().maximum_size(480).child(&form).build(); + + let start = adw::StatusPage::builder() + .title("Addons da comunidade") + .description( + "Os 686 addons feitos pela comunidade para o AD&D Core Rules 2.0 e a \ + Expansion, num só pacote: raças, classes, kits, magias, monstros, \ + equipamentos, encontros, os personagens dos módulos e a User Database. \ + São 36.716 itens.", + ) + .child(&clamp) + .build(); + start.set_paintable( + gdk::Texture::from_bytes(&glib::Bytes::from_static(ICON)) + .ok() + .as_ref(), + ); + start.add_css_class("compact"); + + let spinner = gtk::Spinner::builder() + .spinning(true) + .width_request(32) + .height_request(32) + .halign(gtk::Align::Center) + .build(); + let progress = adw::StatusPage::builder() + .title("Instalando os addons") + .child(&spinner) + .build(); + + let open_log = gtk::Button::builder().label("Abrir o registro").build(); + let close = gtk::Button::builder() + .label("Fechar") + .css_classes(["suggested-action"]) + .build(); + let buttons = gtk::Box::builder() + .spacing(12) + .halign(gtk::Align::Center) + .css_classes(["pill"]) + .build(); + buttons.append(&open_log); + buttons.append(&close); + let done = adw::StatusPage::builder() + .icon_name("emblem-ok-symbolic") + .title("Addons instalados") + .child(&buttons) + .build(); + + let stack = gtk::Stack::builder() + .transition_type(gtk::StackTransitionType::Crossfade) + .build(); + stack.add_named(&start, Some("start")); + stack.add_named(&progress, Some("progress")); + stack.add_named(&done, Some("done")); + let view = adw::ToolbarView::new(); + view.add_top_bar(&adw::HeaderBar::builder().show_title(false).build()); + view.set_content(Some(&stack)); + window.set_content(Some(&view)); + + let this = Self { + window, + stack, + folder_row, + notice, + install_button, + progress, + done, + log: Rc::default(), + dir: Rc::default(), + }; + choose.connect_clicked({ + let this = this.clone(); + move |_| this.choose_folder() + }); + this.install_button.connect_clicked({ + let this = this.clone(); + move |_| this.confirm_and_install() + }); + open_log.connect_clicked({ + let this = this.clone(); + move |_| { + if let Some(log) = this.log.borrow().as_ref() { + gtk::FileLauncher::new(Some(&gio::File::for_path(log))).launch( + Some(&this.window), + gio::Cancellable::NONE, + |_| {}, + ); + } + } + }); + close.connect_clicked({ + let window = this.window.clone(); + move |_| window.close() + }); + let found = Installation::discover().map(|i| i.root().to_path_buf()); + this.set_folder(found); + this + } + + fn set_folder(&self, dir: Option) { + let ready = match &dir { + None => { + self.folder_row + .set_subtitle("Não encontrei os dados do Core Rules"); + self.notice.set_label( + "Abra o Core Rules e use Extrair dados do CD… no menu para criar a pasta \ + de dados; depois volte aqui. Se os dados já estão em outro lugar, como \ + uma instalação da Expansion no Wine, escolha a pasta que tem Database.", + ); + false + } + Some(dir) => { + self.folder_row + .set_subtitle(&glib::markup_escape_text(&dir.to_string_lossy())); + let (ready, text) = match install::check(dir) { + Folder::Ready { again: true, .. } => ( + true, + "Os addons já foram instalados nesta pasta. Instalar de novo \ + atualiza os registros sem duplicar os personagens.", + ), + Folder::Ready { .. } => ( + true, + "Antes de importar, o instalador guarda uma cópia de UserDbas e \ + Chars ao lado da pasta. Um registro seu com o mesmo nome de um \ + addon é substituído pelo do addon.", + ), + Folder::Core20 => ( + false, + "Esta pasta é do Core Rules 2.0. Os addons são para a Expansion.", + ), + Folder::NotAnInstallation => ( + false, + "Esta pasta não tem os dados do Core Rules (falta a pasta Database).", + ), + }; + self.notice.set_label(text); + ready + } + }; + self.install_button.set_sensitive(ready); + self.dir.replace(dir); + } + + fn choose_folder(&self) { + let dialog = gtk::FileDialog::builder() + .title("Pasta de dados do Core Rules") + .modal(true) + .build(); + if let Some(dir) = self.dir.borrow().as_ref() { + dialog.set_initial_folder(Some(&gio::File::for_path(dir))); + } + let this = self.clone(); + glib::spawn_future_local(async move { + if let Ok(file) = dialog.select_folder_future(Some(&this.window)).await + && let Some(path) = file.path() + { + this.set_folder(Some(path)); + } + }); + } + + fn confirm_and_install(&self) { + let Some(dir) = self.dir.borrow().clone() else { + return; + }; + let Folder::Ready { install, wine, .. } = install::check(&dir) else { + return; + }; + let this = self.clone(); + glib::spawn_future_local(async move { + if wine { + let dialog = adw::AlertDialog::new( + Some("Instalar no programa original?"), + Some( + "Esta pasta é a instalação do programa original dentro do Wine. \ + Os addons também funcionam nele, mas o Import do original leva \ + cerca de 35 minutos para ler o mesmo pacote.", + ), + ); + dialog.add_responses(&[("cancel", "Cancelar"), ("install", "Instalar")]); + dialog.set_response_appearance("install", adw::ResponseAppearance::Suggested); + if dialog.choose_future(&this.window).await != "install" { + return; + } + } + this.run(install).await; + }); + } + + async fn run(&self, install: Installation) { + self.stack.set_visible_child_name("progress"); + self.window.set_deletable(false); + let stamp = glib::DateTime::now_local() + .and_then(|t| t.format("%Y%m%d-%H%M%S")) + .map_or_else(|_| "addons".into(), |s| s.to_string()); + + self.progress + .set_description(Some("Guardando uma cópia de UserDbas e Chars…")); + let result = async { + let (install, backup) = { + let stamp = stamp.clone(); + gio::spawn_blocking(move || { + let backup = install::backup(&install, &stamp); + (install, backup) + }) + .await + .map_err(|_| "A cópia de segurança falhou.".to_string())? + }; + let backup = backup?; + self.progress + .set_description(Some("Importando os addons. Isso leva menos de um minuto.")); + let outcome = gio::spawn_blocking(move || { + let file = install::package()?; + install::import(&install, &file, &stamp) + }) + .await + .map_err(|_| "A importação parou com um erro inesperado.".to_string())??; + Ok::<_, String>((backup, outcome)) + } + .await; + self.window.set_deletable(true); + + match result { + Ok((backup, outcome)) => { + let imported = match outcome.characters { + 0 => format!("{} itens importados.", thousands(outcome.imported)), + n => format!( + "{} itens importados, {n} deles personagens.", + thousands(outcome.imported) + ), + }; + let markup = format!( + "{imported}\n\nA cópia de segurança ficou em {}. Se o Core Rules \ + estiver aberto, feche e abra de novo para ver os addons.", + glib::markup_escape_text(&backup.to_string_lossy()), + ); + self.done.set_description(Some(&markup)); + self.log.replace(Some(outcome.log)); + self.stack.set_visible_child_name("done"); + } + Err(message) => { + self.stack.set_visible_child_name("start"); + let dialog = + adw::AlertDialog::new(Some("Os addons não foram instalados"), Some(&message)); + dialog.add_response("close", "Fechar"); + dialog.present(Some(&self.window)); + let dir = self.dir.borrow().clone(); + self.set_folder(dir); + } + } + } +} + +/// 36716 → "36.716", as Portuguese writes it. +fn thousands(n: usize) -> String { + let digits = n.to_string(); + let mut out = String::new(); + for (i, c) in digits.chars().enumerate() { + if i > 0 && (digits.len() - i).is_multiple_of(3) { + out.push('.'); + } + out.push(c); + } + out +} + +#[cfg(test)] +mod tests { + #[test] + fn thousands_are_dotted() { + assert_eq!(super::thousands(36_716), "36.716"); + assert_eq!(super::thousands(105), "105"); + assert_eq!(super::thousands(1_000_000), "1.000.000"); + } +} diff --git a/data/addons/icons/hicolor/128x128/apps/io.github.brahm.CoreRules.Addons.png b/data/addons/icons/hicolor/128x128/apps/io.github.brahm.CoreRules.Addons.png new file mode 100644 index 0000000..70f51f3 Binary files /dev/null and b/data/addons/icons/hicolor/128x128/apps/io.github.brahm.CoreRules.Addons.png differ diff --git a/data/addons/icons/hicolor/16x16/apps/io.github.brahm.CoreRules.Addons.png b/data/addons/icons/hicolor/16x16/apps/io.github.brahm.CoreRules.Addons.png new file mode 100644 index 0000000..842201a Binary files /dev/null and b/data/addons/icons/hicolor/16x16/apps/io.github.brahm.CoreRules.Addons.png differ diff --git a/data/addons/icons/hicolor/24x24/apps/io.github.brahm.CoreRules.Addons.png b/data/addons/icons/hicolor/24x24/apps/io.github.brahm.CoreRules.Addons.png new file mode 100644 index 0000000..4567f75 Binary files /dev/null and b/data/addons/icons/hicolor/24x24/apps/io.github.brahm.CoreRules.Addons.png differ diff --git a/data/addons/icons/hicolor/256x256/apps/io.github.brahm.CoreRules.Addons.png b/data/addons/icons/hicolor/256x256/apps/io.github.brahm.CoreRules.Addons.png new file mode 100644 index 0000000..a782c53 Binary files /dev/null and b/data/addons/icons/hicolor/256x256/apps/io.github.brahm.CoreRules.Addons.png differ diff --git a/data/addons/icons/hicolor/32x32/apps/io.github.brahm.CoreRules.Addons.png b/data/addons/icons/hicolor/32x32/apps/io.github.brahm.CoreRules.Addons.png new file mode 100644 index 0000000..0a59ffa Binary files /dev/null and b/data/addons/icons/hicolor/32x32/apps/io.github.brahm.CoreRules.Addons.png differ diff --git a/data/addons/icons/hicolor/48x48/apps/io.github.brahm.CoreRules.Addons.png b/data/addons/icons/hicolor/48x48/apps/io.github.brahm.CoreRules.Addons.png new file mode 100644 index 0000000..aef9b9a Binary files /dev/null and b/data/addons/icons/hicolor/48x48/apps/io.github.brahm.CoreRules.Addons.png differ diff --git a/data/addons/icons/hicolor/512x512/apps/io.github.brahm.CoreRules.Addons.png b/data/addons/icons/hicolor/512x512/apps/io.github.brahm.CoreRules.Addons.png new file mode 100644 index 0000000..7bab882 Binary files /dev/null and b/data/addons/icons/hicolor/512x512/apps/io.github.brahm.CoreRules.Addons.png differ diff --git a/data/addons/icons/hicolor/64x64/apps/io.github.brahm.CoreRules.Addons.png b/data/addons/icons/hicolor/64x64/apps/io.github.brahm.CoreRules.Addons.png new file mode 100644 index 0000000..4e6e0b5 Binary files /dev/null and b/data/addons/icons/hicolor/64x64/apps/io.github.brahm.CoreRules.Addons.png differ diff --git a/data/addons/io.github.brahm.CoreRules.Addons.desktop b/data/addons/io.github.brahm.CoreRules.Addons.desktop new file mode 100644 index 0000000..73a25ad --- /dev/null +++ b/data/addons/io.github.brahm.CoreRules.Addons.desktop @@ -0,0 +1,11 @@ +[Desktop Entry] +Name=Core Rules Add-ons +Name[pt_BR]=Addons do Core Rules +Comment=Install the community add-ons into Core Rules +Comment[pt_BR]=Instale os addons da comunidade no Core Rules +Exec=corerules-addons +Icon=io.github.brahm.CoreRules.Addons +Terminal=false +Type=Application +Categories=Game;RolePlaying; +StartupNotify=true diff --git a/packaging/addons/build.sh b/packaging/addons/build.sh deleted file mode 100755 index de38a3b..0000000 --- a/packaging/addons/build.sh +++ /dev/null @@ -1,35 +0,0 @@ -#!/bin/sh -# Builds target/addons/addons-comunidade-expansion.tar.gz, the community -# add-ons package for the Expansion: the consolidated Comunidade.xpx, the -# installer, a static cr that reads it and the data extraction script. The -# Addons package workflow publishes it on GitHub Packages. -# -# packaging/addons/build.sh [COMUNIDADE.xpx] -# -# Without an argument it unpacks addons/Comunidade.xpx.xz. The static cr is -# built here (x86_64-unknown-linux-musl target). -set -eu -root=$(cd "$(dirname "$0")/../.." && pwd) -name=addons-comunidade-expansion -stage=$root/target/addons/$name -out=$root/target/addons/$name.tar.gz - -cargo build --release --locked -p cr-cli --target x86_64-unknown-linux-musl -rm -rf "$stage" -mkdir -p "$stage/bin" -install -m755 "$root/target/x86_64-unknown-linux-musl/release/cr" "$stage/bin/cr" -strip "$stage/bin/cr" -if [ $# -gt 0 ]; then - install -m644 "$1" "$stage/Comunidade.xpx" -else - xz -dc "$root/addons/Comunidade.xpx.xz" > "$stage/Comunidade.xpx" -fi -install -m755 "$root/packaging/addons/instalar-addons.sh" "$stage/instalar-addons.sh" -install -m755 "$root/packaging/extract-data.sh" "$stage/extract-data.sh" -install -m644 "$root/addons/README.md" "$stage/README.md" -for f in relatorio.md compatibilidade.csv conflitos.csv; do - install -m644 "$root/addons/$f" "$stage/$f" -done -(cd "$stage" && sha256sum Comunidade.xpx bin/cr > SHA256SUMS) -tar -C "$(dirname "$stage")" -czf "$out" "$name" -ls -l "$out" diff --git a/packaging/addons/instalar-addons.sh b/packaging/addons/instalar-addons.sh deleted file mode 100755 index 491d5f3..0000000 --- a/packaging/addons/instalar-addons.sh +++ /dev/null @@ -1,99 +0,0 @@ -#!/bin/sh -# Instala os addons da comunidade (Comunidade.xpx) no Core Rules para Linux. -# -# Uso: ./instalar-addons.sh [-y] [PASTA_DA_INSTALACAO] -# -# Sem PASTA_DA_INSTALACAO usa o pacote de dados do aplicativo -# ($XDG_DATA_HOME/corerules/data, senão ~/.local/share/corerules/data). -# Antes de importar, guarda UserDbas/ e Chars/ num .tar.gz ao lado da pasta. -set -eu - -here=$(cd "$(dirname "$0")" && pwd) -package="$here/Comunidade.xpx" -cr="$here/bin/cr" -yes=0 - -while [ $# -gt 0 ]; do - case $1 in - -y) yes=1; shift ;; - -h|--help) sed -n '2,8p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;; - -*) echo "opção desconhecida: $1" >&2; exit 2 ;; - *) break ;; - esac -done - -if [ $# -gt 0 ]; then - dir=$1 -else - dir=${XDG_DATA_HOME:-$HOME/.local/share}/corerules/data -fi - -die() { echo "erro: $*" >&2; exit 1; } - -[ -f "$package" ] || die "não achei $package" -[ -x "$cr" ] || die "não achei $cr" -[ -d "$dir" ] || die "$dir não existe; crie o pacote de dados com ./extract-data.sh --install PASTA_DO_CORE_RULES (veja o README.md) ou informe a pasta" -dir=$(cd "$dir" && pwd) - -# Acha um caminho dentro da instalação sem ligar para maiúsculas. -find_ci() { find "$dir" -maxdepth 2 -ipath "$dir/$1" 2>/dev/null | head -n 1; } - -userdbas=$(find_ci UserDbas) -[ -n "$(find_ci Database)" ] || die "$dir não é uma instalação do Core Rules (falta Database/)" -[ -n "$userdbas" ] && [ -n "$(find_ci UserDbas/AllowedU.dat)" ] || - die "$dir não é da Expansion (falta UserDbas/AllowedU.dat); os addons são para a Expansion" - -case $dir in - */drive_c/*) wine=1 ;; - *) wine=0 ;; -esac -if [ $wine -eq 1 ] && [ $yes -eq 0 ]; then - echo "$dir é a instalação do programa original dentro do Wine." - printf "Importar os addons nela mesmo assim? [s/N] " - read -r answer - case $answer in s|S|sim|Sim) ;; *) echo "nada foi alterado"; exit 1 ;; esac -fi - -# Cópia de segurança dos registros e personagens do usuário. -stamp=$(date +%Y%m%d-%H%M%S) -backup="$(dirname "$dir")/$(basename "$dir")-antes-dos-addons-$stamp.tar.gz" -chars=$(find_ci Chars) -( - cd "$dir" - set -- "$(basename "$userdbas")" - [ -n "$chars" ] && set -- "$@" "$(basename "$chars")" - tar -czf "$backup" "$@" -) -echo "cópia de segurança: $backup" - -log="$(dirname "$dir")/$(basename "$dir")-addons-$stamp.log" -marker="$userdbas/.addons-comunidade" -list=$(mktemp) -trap 'rm -f "$list"' EXIT - -if [ -f "$marker" ]; then - # Já instalado antes: importa tudo menos os personagens, que viriam em - # dobro (cada personagem importado vira um arquivo novo em Chars/). - echo "reinstalando (os personagens já foram importados antes)..." - "$cr" import "$dir" "$package" --list | - awk -F'\t' '$1 != "Characters" && $1 !~ /^\(/ { print $1 ":" $2 }' > "$list" - tr '\n' '\0' < "$list" | xargs -0 "$cr" import "$dir" "$package" > "$log" 2>&1 -else - echo "importando $(basename "$package") (alguns segundos)..." - "$cr" import "$dir" "$package" > "$log" 2>&1 -fi - -imported=$(grep -c '^imported ' "$log" || true) -characters=$(grep -c '^wrote Chars/' "$log" || true) - -# Segunda passagem só com as classes: uma combinação raça/classe que cita -# duas classes do pacote só entra quando as duas já existem. -"$cr" import "$dir" "$package" --list | - awk -F'\t' '$1 == "Classes" { print $1 ":" $2 }' > "$list" -echo "segunda passagem: $(wc -l < "$list") classes..." -echo "=== segunda passagem (classes)" >> "$log" -tr '\n' '\0' < "$list" | xargs -0 "$cr" import "$dir" "$package" >> "$log" 2>&1 - -date > "$marker" -echo "pronto: $imported itens importados, $characters personagens" -echo "detalhes: $log" diff --git a/packaging/appimage/build-in-sdk.sh b/packaging/appimage/build-in-sdk.sh index a0e4d24..08cae1f 100755 --- a/packaging/appimage/build-in-sdk.sh +++ b/packaging/appimage/build-in-sdk.sh @@ -25,6 +25,9 @@ flatpak run --share=network --filesystem=host --cwd="$PWD" --command=sh \ "org.gnome.Sdk//$gnome" -c ' set -eu export PATH=/usr/lib/sdk/rust-stable/bin:$PATH CARGO_HOME=$PWD/target/cargo-home - cargo build --release --locked - packaging/appimage/build.sh "$1" - ' sh "$version" + case $2 in + addons) cargo build --release --locked -p cr-addons ;; + *) cargo build --release --locked ;; + esac + packaging/appimage/build.sh "$1" "$2" + ' sh "$version" "${2:-app}" diff --git a/packaging/appimage/build.sh b/packaging/appimage/build.sh index d9d7f95..3221e61 100755 --- a/packaging/appimage/build.sh +++ b/packaging/appimage/build.sh @@ -1,12 +1,19 @@ #!/bin/sh # Builds dist/CoreRules-VERSION-ARCH.AppImage from target/release with # linuxdeploy and its GTK plugin, which bundle GTK 4, libadwaita and their -# data from the system it runs on. Releases run it inside the GNOME 51 SDK -# (build-in-sdk.sh), so the AppImage carries that platform's libraries and -# runs on systems with the SDK's glibc or newer. +# data from the system it runs on. `build.sh VERSION addons` builds the +# add-ons installer instead, dist/CoreRules-Addons-VERSION-ARCH.AppImage. +# Releases run it inside the GNOME 51 SDK (build-in-sdk.sh), so the +# AppImage carries that platform's libraries and runs on systems with the +# SDK's glibc or newer. set -eu version=$1 arch=$(uname -m) +case ${2:-app} in + app) app=io.github.brahm.CoreRules exe=corerules name=CoreRules ;; + addons) app=io.github.brahm.CoreRules.Addons exe=corerules-addons name=CoreRules-Addons ;; + *) echo "$0: unknown target $2" >&2; exit 2 ;; +esac tools=${TOOLS_DIR:-$PWD/target/appimage-tools} appdir=$PWD/target/AppDir mkdir -p "$tools" @@ -25,22 +32,30 @@ grep -q 'pixbuf loaders, if any' "$plugin" || sed -i \ -e 's|^echo "Copying more libraries"$|fi\n&|' "$plugin" rm -rf "$appdir" -packaging/install.sh "$appdir" /usr +if [ "$exe" = corerules ]; then + packaging/install.sh "$appdir" /usr +else + install -Dm755 "target/release/$exe" "$appdir/usr/bin/$exe" + install -Dm644 "data/addons/$app.desktop" "$appdir/usr/share/applications/$app.desktop" + for icon in data/addons/icons/hicolor/*/apps/$app.png; do + size=$(basename "$(dirname "$(dirname "$icon")")") + install -Dm644 "$icon" "$appdir/usr/share/icons/hicolor/$size/apps/$app.png" + done +fi # The GTK plugin reads the version to bundle from DEPLOY_GTK_VERSION. export DEPLOY_GTK_VERSION=4 APPIMAGE_EXTRACT_AND_RUN=1 NO_STRIP=1 PATH="$tools:$PATH" linuxdeploy --appdir "$appdir" \ - --executable "$appdir/usr/bin/corerules" \ - --desktop-file "$appdir/usr/share/applications/io.github.brahm.CoreRules.desktop" \ - --icon-file "$appdir/usr/share/icons/hicolor/256x256/apps/io.github.brahm.CoreRules.png" \ + --executable "$appdir/usr/bin/$exe" \ + --desktop-file "$appdir/usr/share/applications/$app.desktop" \ + --icon-file "$appdir/usr/share/icons/hicolor/256x256/apps/$app.png" \ --plugin gtk # libadwaita draws its own light and dark styles; a GTK_THEME set by the # plugin's hook only makes it warn and breaks the dark style. sed -i '/export GTK_THEME=/d' "$appdir"/apprun-hooks/*gtk*.sh # linuxdeploy links the smallest bundled size; file managers show .DirIcon. -ln -sf usr/share/icons/hicolor/256x256/apps/io.github.brahm.CoreRules.png \ - "$appdir/io.github.brahm.CoreRules.png" +ln -sf "usr/share/icons/hicolor/256x256/apps/$app.png" "$appdir/$app.png" # The app plays no video, and GStreamer is not bundled. rm -rf "$appdir"/usr/lib/gtk-4.0/4.0.0/media mkdir -p dist VERSION=$version ARCH=$arch "$tools/appimagetool" --no-appstream "$appdir" \ - "dist/CoreRules-$version-$arch.AppImage" + "dist/$name-$version-$arch.AppImage"