From cd4adca7edb570e047eca13eccea6445caa0b611 Mon Sep 17 00:00:00 2001 From: cammo22 Date: Tue, 3 Nov 2026 19:03:33 +0000 Subject: [PATCH] 2.3.0: DaP Convertitore si apre su Linux MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit La stessa finestra, in un AppImage, con FFmpeg e 7-Zip dentro. Video, musica, foto, testo, archivi e PDF (testo e unione) si convertono; il tasto destro c'è in Nautilus, Nemo e Dolphin. Su Windows il programma resta quello di prima. Le prove Linux compilano l'app e impacchettano l'AppImage. Co-authored-by: Cammo --- .github/workflows/prove-linux.yml | 55 +++ .github/workflows/rilascio.yml | 41 ++ .gitignore | 1 + CHANGELOG.md | 9 + DaP-Convertitore.slnx | 2 + Directory.Build.props | 10 +- linux/LEGGIMI.md | 32 ++ linux/appimage.sh | 38 ++ scripts/prendi-7zip-linux.sh | 19 + scripts/prendi-ffmpeg-linux.sh | 21 + .../DaPConvertitore.Linux.csproj | 29 ++ src/DaPConvertitore.Linux/PonteLinux.cs | 371 ++++++++++++++++++ src/DaPConvertitore.Linux/Programma.cs | 70 ++++ src/DaPConvertitore.Motore/Cestino.cs | 27 ++ .../DaPConvertitore.Motore.csproj | 30 ++ src/DaPConvertitore.Motore/Ffmpeg.cs | 3 +- .../Lettore/Contenuti.cs | 3 - .../Lettore/VoceArchivio.cs | 4 + src/DaPConvertitore.Motore/Linux/Immagini.cs | 80 ++++ src/DaPConvertitore.Motore/Linux/MenuLinux.cs | 71 ++++ src/DaPConvertitore.Motore/Linux/Pdf.cs | 114 ++++++ src/DaPConvertitore.Motore/Strumenti.cs | 52 ++- src/DaPConvertitore.Motore/Versioni.cs | 39 ++ src/DaPConvertitore/DaPConvertitore.csproj | 2 + .../DaPConvertitore.Prove.Linux.csproj | 26 ++ .../DaPConvertitore.Prove.Linux/ProveLinux.cs | 81 ++++ .../DaPConvertitore.Prove.csproj | 3 + ui/src/ponte.ts | 21 +- 28 files changed, 1235 insertions(+), 19 deletions(-) create mode 100644 .github/workflows/prove-linux.yml create mode 100644 linux/LEGGIMI.md create mode 100755 linux/appimage.sh create mode 100755 scripts/prendi-7zip-linux.sh create mode 100755 scripts/prendi-ffmpeg-linux.sh create mode 100644 src/DaPConvertitore.Linux/DaPConvertitore.Linux.csproj create mode 100644 src/DaPConvertitore.Linux/PonteLinux.cs create mode 100644 src/DaPConvertitore.Linux/Programma.cs create mode 100644 src/DaPConvertitore.Motore/Lettore/VoceArchivio.cs create mode 100644 src/DaPConvertitore.Motore/Linux/Immagini.cs create mode 100644 src/DaPConvertitore.Motore/Linux/MenuLinux.cs create mode 100644 src/DaPConvertitore.Motore/Linux/Pdf.cs create mode 100644 src/DaPConvertitore.Motore/Versioni.cs create mode 100644 test/DaPConvertitore.Prove.Linux/DaPConvertitore.Prove.Linux.csproj create mode 100644 test/DaPConvertitore.Prove.Linux/ProveLinux.cs diff --git a/.github/workflows/prove-linux.yml b/.github/workflows/prove-linux.yml new file mode 100644 index 0000000..8e8b2b6 --- /dev/null +++ b/.github/workflows/prove-linux.yml @@ -0,0 +1,55 @@ +# Ogni pull request: su Linux si compila l'app, si fanno le prove e si impacchetta l'AppImage. +# L'app di Windows non passa di qui. +name: Prove Linux + +on: + pull_request: + workflow_dispatch: + +jobs: + prove: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: 10.0.x + + - uses: actions/setup-node@v4 + with: + node-version: 22 + + - name: WebKit + run: | + sudo apt-get update + sudo apt-get install -y libwebkit2gtk-4.1-0 || sudo apt-get install -y libwebkit2gtk-4.0-37 || true + + - name: FFmpeg + run: chmod +x scripts/prendi-ffmpeg-linux.sh && ./scripts/prendi-ffmpeg-linux.sh + + - name: 7-Zip + run: chmod +x scripts/prendi-7zip-linux.sh && ./scripts/prendi-7zip-linux.sh + + - name: Interfaccia + working-directory: ui + run: | + if [ ! -d node_modules ]; then npm ci --no-audit --no-fund; fi + npm run build + + - name: Prove + run: dotnet test test/DaPConvertitore.Prove.Linux -c Release -nologo + + - name: Versione + run: | + dotnet build src/DaPConvertitore.Linux/DaPConvertitore.Linux.csproj -c Release -nologo + ./src/DaPConvertitore.Linux/bin/Release/net10.0/linux-x64/DaPConvertitore --versione + + - name: AppImage + run: chmod +x linux/appimage.sh && ./linux/appimage.sh + + - uses: actions/upload-artifact@v4 + with: + name: DaPConvertitore-linux + path: Releases/DaPConvertitore-linux.AppImage + if-no-files-found: error diff --git a/.github/workflows/rilascio.yml b/.github/workflows/rilascio.yml index 3b60872..95cc4ae 100644 --- a/.github/workflows/rilascio.yml +++ b/.github/workflows/rilascio.yml @@ -80,3 +80,44 @@ jobs: $v = "${{ steps.versione.outputs.numero }}" dotnet vpk upload github --repoUrl https://github.com/${{ github.repository }} --token ${{ github.token }} ` -o Releases --publish --releaseName "DaP Convertitore $v" --tag "v$v" + + linux: + needs: rilascio + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: 10.0.x + + - uses: actions/setup-node@v4 + with: + node-version: 22 + + - name: FFmpeg + run: chmod +x scripts/prendi-ffmpeg-linux.sh && ./scripts/prendi-ffmpeg-linux.sh + + - name: 7-Zip + run: chmod +x scripts/prendi-7zip-linux.sh && ./scripts/prendi-7zip-linux.sh + + - name: Interfaccia + working-directory: ui + run: | + if [ ! -d node_modules ]; then npm ci --no-audit --no-fund; fi + npm run build + + - name: AppImage + run: chmod +x linux/appimage.sh && ./linux/appimage.sh + + - name: Pubblica l'AppImage + shell: bash + env: + GH_TOKEN: ${{ github.token }} + run: | + v=$(grep -oP '(?<=)[^<]+' Directory.Build.props | head -1) + if gh release view "v$v" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then + gh release upload "v$v" Releases/DaPConvertitore-linux.AppImage --clobber --repo "$GITHUB_REPOSITORY" + else + echo "La release v$v non c'è (versione già pubblicata o prove fallite): non carico l'AppImage" + fi diff --git a/.gitignore b/.gitignore index 9f0af5d..1d303af 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ bin/ obj/ publish/ Releases/ +AppDir/ *.user .vs/ diff --git a/CHANGELOG.md b/CHANGELOG.md index f7bf22a..c7083e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,15 @@ Le novità di ogni versione, dette come stanno. La più nuova sta in alto. +## 2.3.0 — 3 novembre 2026 + +- **DaP Convertitore si apre anche su Linux.** È la stessa finestra di Windows. Si scarica un file solo (AppImage), lo si rende avviabile e si apre. + Dentro ci sono FFmpeg e 7-Zip. Video, musica, sottotitoli, foto, testo e archivi si convertono. I PDF si uniscono e se ne legge il testo; + i documenti di Word passano se c'è LibreOffice. Il tasto destro c'è in Nautilus, Nemo e Dolphin («Aggiusta tutto» nelle Impostazioni, oppure + `--menu`). Se esce una versione nuova, l'avviso sta nella barra in alto, come su Windows. +- **Su Windows non cambia niente** di quello che già faceva: l'avatar, il lettore e l'OCR restano lì. +- Come si installa, detto corto: `linux/LEGGIMI.md`. + ## 2.2.6 — 3 novembre 2026 - **Le miniature dei documenti Word non vanno più in errore.** Disegnando la pagina si chiedeva «zero righe» di testo e Windows rifiutava diff --git a/DaP-Convertitore.slnx b/DaP-Convertitore.slnx index e952290..ada2be6 100644 --- a/DaP-Convertitore.slnx +++ b/DaP-Convertitore.slnx @@ -2,8 +2,10 @@ + + diff --git a/Directory.Build.props b/Directory.Build.props index 6f43db4..8e2f7a1 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -2,7 +2,7 @@ - 2.2.6 + 2.3.0 DaProd DaProdProduzioni DaP Convertitore @@ -10,9 +10,11 @@ latest enable enable - net10.0-windows10.0.22621.0 - 10.0.19041.0 - win-x64 + + net10.0-windows10.0.22621.0 + + true it $(NoWarn);CA1416 diff --git a/linux/LEGGIMI.md b/linux/LEGGIMI.md new file mode 100644 index 0000000..f50dbcc --- /dev/null +++ b/linux/LEGGIMI.md @@ -0,0 +1,32 @@ +# DaP Convertitore su Linux + +È lo stesso programma di Windows: la stessa finestra. Si apre un file, si sceglie in cosa diventa, si preme Converti. + +## Cosa c'è + +- Video, musica e sottotitoli (FFmpeg, è dentro il programma). +- Foto (JPG, PNG, WEBP e gli altri che FFmpeg sa fare). +- Testo, tabelle semplici, archivi (7-Zip è dentro il programma). +- PDF: il testo e l'unione di più PDF. Le pagine come immagini, se c'è LibreOffice. +- Documenti di Word, fogli e presentazioni, se c'è LibreOffice (`soffice`). +- Il tasto destro in Nautilus, Nemo e Dolphin. + +L'avatar, l'OCR delle scansioni e il lettore completo restano su Windows. + +## Come si installa + +1. Scarica `DaPConvertitore-linux.AppImage` dalla pagina delle release. +2. Rendilo avviabile: tasto destro sul file → Proprietà → Permetti l'esecuzione come programma. + Oppure, nel terminale: `chmod +x DaPConvertitore-linux.AppImage` +3. Serve WebKit, che quasi tutte le distribuzioni hanno. Se la finestra non si apre: + - Ubuntu o Debian: `sudo apt install libwebkit2gtk-4.1-0` + - Fedora: `sudo dnf install webkit2gtk4.1` +4. Doppio clic sull'AppImage. + +Il tasto destro sui file: apri il programma e, nelle Impostazioni, «Aggiusta tutto». Oppure, nel terminale, una volta: + +`./DaPConvertitore-linux.AppImage --menu` + +Poi riavvia il gestore dei file se la voce non compare subito. + +Gli aggiornamenti: se ne esce uno, compare il tasto in alto, come su Windows. Non si chiede niente all'API di GitHub: si guarda solo la pagina della release. diff --git a/linux/appimage.sh b/linux/appimage.sh new file mode 100755 index 0000000..a4263cd --- /dev/null +++ b/linux/appimage.sh @@ -0,0 +1,38 @@ +#!/bin/sh +# Impacchetta l'app di Linux in un AppImage: un file solo, si scarica e si apre. +# Vuole gli attrezzi già scaricati (scripts/prendi-ffmpeg-linux.sh e prendi-7zip-linux.sh) e ui/dist. +set -eu +radice=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd) +cd "$radice" +appdir="$radice/AppDir" +rm -rf "$appdir" +mkdir -p "$appdir/usr/bin" +dotnet publish src/DaPConvertitore.Linux/DaPConvertitore.Linux.csproj -c Release -r linux-x64 --self-contained -o "$appdir/usr/bin" -nologo +cat > "$appdir/AppRun" << 'EOF' +#!/bin/sh +HERE=$(dirname "$(readlink -f "$0")") +export PATH="$HERE/usr/bin/motori/ffmpeg-linux:$HERE/usr/bin/motori/7zip-linux:$PATH" +exec "$HERE/usr/bin/DaPConvertitore" "$@" +EOF +chmod +x "$appdir/AppRun" +cp "$radice/risorse/icona-256.png" "$appdir/dap-convertitore.png" +cat > "$appdir/dap-convertitore.desktop" << 'EOF' +[Desktop Entry] +Type=Application +Name=DaP Convertitore +Exec=DaPConvertitore %F +Icon=dap-convertitore +Categories=AudioVideo;Utility; +Terminal=false +EOF +attrezzo="$radice/motori/appimagetool" +if [ ! -x "$attrezzo" ]; then + mkdir -p "$radice/motori" + curl -fsSL -o "$attrezzo" "https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-x86_64.AppImage" + chmod +x "$attrezzo" +fi +mkdir -p "$radice/Releases" +chmod -R a+rX "$appdir" +ARCH=x86_64 "$attrezzo" --appimage-extract-and-run "$appdir" "$radice/Releases/DaPConvertitore-linux.AppImage" +chmod +x "$radice/Releases/DaPConvertitore-linux.AppImage" +echo "AppImage pronto: $radice/Releases/DaPConvertitore-linux.AppImage" diff --git a/scripts/prendi-7zip-linux.sh b/scripts/prendi-7zip-linux.sh new file mode 100755 index 0000000..a6486d3 --- /dev/null +++ b/scripts/prendi-7zip-linux.sh @@ -0,0 +1,19 @@ +#!/bin/sh +# 7-Zip per Linux (il programma ufficiale, 7zz). Finisce in motori/7zip-linux. +set -eu +radice=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd) +dest="$radice/motori/7zip-linux" +if [ -x "$dest/7zz" ]; then + echo "7-Zip c'è già in $dest" + exit 0 +fi +url="https://www.7-zip.org/a/7z2501-linux-x64.tar.xz" +lavoro=$(mktemp -d) +trap 'rm -rf "$lavoro"' EXIT +echo "Scarico $url" +curl -fsSL -o "$lavoro/7z.tar.xz" "$url" +tar -xJf "$lavoro/7z.tar.xz" -C "$lavoro" +mkdir -p "$dest" +cp "$lavoro/7zz" "$dest/7zz" +chmod +x "$dest/7zz" +echo "7-Zip pronto in $dest" diff --git a/scripts/prendi-ffmpeg-linux.sh b/scripts/prendi-ffmpeg-linux.sh new file mode 100755 index 0000000..35bfca8 --- /dev/null +++ b/scripts/prendi-ffmpeg-linux.sh @@ -0,0 +1,21 @@ +#!/bin/sh +# FFmpeg per Linux (build GPL di BtbN, la stessa famiglia di quello di Windows). +# Finisce in motori/ffmpeg-linux, che git non vede. Se c'è già ffmpeg nel PATH, l'app lo usa lo stesso. +set -eu +radice=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd) +dest="$radice/motori/ffmpeg-linux" +if [ -x "$dest/ffmpeg" ] && [ -x "$dest/ffprobe" ]; then + echo "FFmpeg c'è già in $dest" + exit 0 +fi +nome="ffmpeg-n9.0-latest-linux64-gpl-9.0" +url="https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/$nome.tar.xz" +lavoro=$(mktemp -d) +trap 'rm -rf "$lavoro"' EXIT +echo "Scarico $url" +curl -fsSL -o "$lavoro/ffmpeg.tar.xz" "$url" +tar -xJf "$lavoro/ffmpeg.tar.xz" -C "$lavoro" +mkdir -p "$dest" +cp "$lavoro/$nome/bin/ffmpeg" "$lavoro/$nome/bin/ffprobe" "$dest/" +chmod +x "$dest/ffmpeg" "$dest/ffprobe" +echo "FFmpeg pronto in $dest" diff --git a/src/DaPConvertitore.Linux/DaPConvertitore.Linux.csproj b/src/DaPConvertitore.Linux/DaPConvertitore.Linux.csproj new file mode 100644 index 0000000..34eb661 --- /dev/null +++ b/src/DaPConvertitore.Linux/DaPConvertitore.Linux.csproj @@ -0,0 +1,29 @@ + + + + + WinExe + net10.0 + linux-x64 + DaPConvertitore + DaP.Convertitore.Linux + + enable + enable + + + + + + + + + + + + + + + + diff --git a/src/DaPConvertitore.Linux/PonteLinux.cs b/src/DaPConvertitore.Linux/PonteLinux.cs new file mode 100644 index 0000000..b8150f2 --- /dev/null +++ b/src/DaPConvertitore.Linux/PonteLinux.cs @@ -0,0 +1,371 @@ +using System.Text.Json; +using System.Text.Json.Nodes; +using Photino.NET; + +namespace DaP.Convertitore.Linux; + +/// +/// Le stesse domande dell'interfaccia di Windows ({id, cmd, args}), risposte nello stesso formato. +/// Quello che su Windows è il menu, l'avatar o l'OCR qui risponde in chiaro che non c'è. +/// +sealed class PonteLinux +{ + readonly string versione; + readonly Strumenti strumenti = Strumenti.Trova(); + readonly Impostazioni imp = Impostazioni.Comune; + readonly Analisi analisi; + readonly Coda coda; + readonly Dictionary file = new(StringComparer.Ordinal); + readonly List ordine = []; + readonly object lucchetto = new(); + PhotinoWindow? finestra; + InfoHardware? hardware; + readonly Task rilevazione; + string? aggiornamento; + + static readonly JsonSerializerOptions json = new(JsonSerializerDefaults.Web); + sealed class Voce(InfoFile info) { public InfoFile Info { get; } = info; public Dictionary? Dettagli { get; set; } } + + public PonteLinux(string versione, IReadOnlyList gia) + { + this.versione = versione; + analisi = new Analisi(strumenti); + rilevazione = Task.Run(() => Hardware.Rileva(strumenti)); + coda = new Coda(strumenti, () => hardware ?? rilevazione.GetAwaiter().GetResult(), () => new SenzaStampante(), () => imp.ScrittaPulita(), () => imp.CestinoDaSolo) + { QuandoFatto = Storico.Aggiungi }; + coda.Cambiato += l => Manda("lavoro", LavoroDto(l)); + _ = rilevazione.ContinueWith(t => + { + if (!t.IsCompletedSuccessfully) return; + hardware = t.Result; + Manda("hardware", HardwareDto()); + }); + foreach (var p in gia) Aggiungi(p); + _ = CercaAggiornamento(); + } + + public void Collega(PhotinoWindow w) => finestra = w; + + public async void Ricevi(string messaggio) + { + JsonNode? m; + try { m = JsonNode.Parse(messaggio); } + catch { return; } + if (m is null) return; + var cmd = (string?)m["cmd"] ?? ""; + var id = m["id"]?.GetValue(); + var args = m["args"] as JsonObject ?? []; + try + { + var dati = await Esegui(cmd, args); + if (id is not null) Rispondi(id.Value, true, dati, null); + } + catch (Exception ex) when (!EccezioniPonte.DaRegistro(ex)) + { + if (id is not null) Rispondi(id.Value, false, null, null); + } + catch (Exception ex) + { + Registro.Errore($"ponte {cmd}", ex); + if (id is not null) Rispondi(id.Value, false, null, ex is ErroreConversione ? ex.Message : "Qualcosa è andato storto."); + } + } + + async Task Esegui(string cmd, JsonObject a) + { + switch (cmd) + { + case "stato": + return new + { + versione, + hardware = HardwareDto(), + formati = Catalogo.Formati.Select(f => new { f.Id, categoria = Catalogo.Chiave(f.Categoria), f.Etichetta, f.Descrizione, f.Estensione, f.Unisce, f.Sostituisce, manca = Conversioni.Manca(f, strumenti) }), + categorie = Enum.GetValues().Select(c => new { id = Catalogo.Chiave(c), nome = Catalogo.NomeCategoria(c) }), + impostazioni = imp, + apriConGruppi = ApriCon.Elenco().Select(g => new { g.Id, g.Nome, g.Esempi }), + regolaPredefiniti = new { supportata = false, attiva = false, diAltri = false, impostati = 0, totale = 0, inAttesa = false }, + aggiornamento, + modo = "finestra", + file = Ordinati().Select(FileDto), + lavori = coda.Tutti.Select(LavoroDto), + office = new { libreOffice = strumenti.LibreOffice is not null, word = false, setteZip = strumenti.HaSetteZip }, + menu11 = new { supportato = false, registrato = false, fidato = false, chiesto = true, windows11 = false, classico = false }, + compatto = false, + scelta = (object?)null, + }; + case "pronto": + return true; + case "scegli": + foreach (var p in await ScegliFile()) Aggiungi(p); + return true; + case "storico": + { + var (recenti, totali) = Storico.Recenti(a["quanti"]?.GetValue() ?? 6); + return new { recenti = recenti.Select(v => new { v.Quando, v.Nome, v.Formato, v.Uscita, v.PesoPrima, v.PesoDopo, v.Categoria }), totali }; + } + case "svuota": + lock (lucchetto) { file.Clear(); ordine.Clear(); } + return true; + case "togli": + { + var id = (string?)a["id"]; + if (id is not null) lock (lucchetto) { file.Remove(id); ordine.Remove(id); } + return true; + } + case "piano": + { + var v = Prendi((string)a["id"]!); + var f = Catalogo.Trova((string)a["formato"]!) ?? throw new ErroreConversione("Formato sconosciuto."); + var o = Opzioni.Da(JsonSerializer.SerializeToElement(a["opzioni"])); + var info = await analisi.LeggiMedia(v.Info.Percorso) ?? throw new ErroreConversione("Il video non si legge."); + var hw = hardware ?? await rilevazione; + var p = PianoVideo.Calcola(info, v.Info.Peso, v.Info.Estensione, f.Estensione, o.Video, hw); + return new + { + p.Modo, p.Codec, p.Encoder, p.Hardware, p.Larghezza, p.Altezza, p.Fps, p.BitrateVideo, p.AudioKbps, + p.Punteggio, p.Giudizio, p.PesoStimato, p.PesoMin, p.PesoMax, p.PuoCopiare, p.Note, + codecAmmessi = PianoVideo.CodecPer(f.Estensione, hw), + }; + } + case "stimaImmagine": + { + var v = Prendi((string)a["id"]!); + var f = Catalogo.Trova((string)a["formato"]!) ?? throw new ErroreConversione("Formato sconosciuto."); + var lato = a["lato"]?.GetValue() ?? 0; + var qualita = a["qualita"]?.GetValue() ?? 88; + var pesoMax = a["pesoMax"]?.GetValue() ?? 0; + var s = await Immagini.Stima(v.Info.Percorso, f.Estensione, lato, qualita, pesoMax, CancellationToken.None); + return new { peso = s.Peso, qualita = s.Qualita, scala = 1.0, min = Math.Max(1, s.Peso / 4), max = Math.Max(s.Peso, s.Peso * 2), larghezza = s.Larghezza, altezza = s.Altezza, esatta = false }; + } + case "converti": + { + var ids = new List(); + foreach (var el in (a["elementi"] as JsonArray ?? []).OfType()) + { + var f = Catalogo.Trova((string?)el["formato"] ?? ""); + if (f is null) continue; + var o = Opzioni.Da(JsonSerializer.SerializeToElement(el["opzioni"])); + var voci = (el["ids"] as JsonArray ?? []).Select(x => (string?)x).Where(x => x is not null && Contiene(x)).Select(x => Prendi(x!)).ToList(); + if (voci.Count == 0) continue; + if (f.Unisce) ids.Add(coda.Aggiungi(voci.Select(v => v.Info.Percorso).ToList(), f, o, voci[0].Info.Id).Id); + else foreach (var v in voci) ids.Add(coda.Aggiungi([v.Info.Percorso], f, o, v.Info.Id).Id); + } + return ids; + } + case "annulla": + if ((string?)a["id"] is { } lid) coda.Annulla(lid); else coda.AnnullaTutto(); + return true; + case "pulisci": + coda.TogliFiniti(); + return true; + case "apri": + case "guarda": + Apri((string?)a["percorso"]); + return true; + case "mostra": + Mostra((string?)a["percorso"]); + return true; + case "finestra": + switch ((string?)a["azione"]) + { + case "chiudi": finestra?.Close(); break; + case "riduci": if (finestra is not null) finestra.Minimized = true; break; + case "massimizza": if (finestra is not null) finestra.Maximized = !finestra.Maximized; break; + } + return true; + case "impostazioni": + if (a["scritta"] is { } scritta) imp.Scritta = (string?)scritta ?? "convertito"; + if (a["alMassimo"] is { } am) { imp.AlMassimo = am.GetValue(); Processi.Priorita = imp.AlMassimo ? System.Diagnostics.ProcessPriorityClass.Normal : System.Diagnostics.ProcessPriorityClass.BelowNormal; } + if (a["suoniAccesi"] is { } su) imp.SuoniAccesi = su.GetValue(); + if (a["apriCartella"] is { } ac) imp.ApriCartella = ac.GetValue(); + if (a["cestinoDaSolo"] is { } ce) imp.CestinoDaSolo = ce.GetValue(); + if (a["formati"] is JsonObject fo) imp.Formati = fo.ToDictionary(kv => kv.Key, kv => (string?)kv.Value ?? ""); + if (a["scelte"] is JsonObject sc) imp.Scelte = (JsonObject)sc.DeepClone(); + imp.Salva(); + return true; + case "cestino": + { + var perche = coda.OriginaleNelCestino((string?)a["lavoro"] ?? ""); + return new { ok = perche is null, perche }; + } + case "anteprimaTesto": + { + var v = Prendi((string?)a["id"] ?? ""); + var t = Codifiche.Leggi(v.Info.Percorso, 6 * 1024 * 1024); + return new { testo = t.Testo, codifica = t.Codifica, bom = t.Bom, troncato = t.Troncato, peso = v.Info.Peso }; + } + case "novita": + { + var nuova = !string.IsNullOrEmpty(imp.NovitaVista) && imp.NovitaVista != versione; + if (imp.NovitaVista != versione) { imp.NovitaVista = versione; imp.Salva(); } + return new { versione, testo = Novita.Di(versione), nuova }; + } + case "aggiorna": + if (a["installa"]?.GetValue() == true) { await ScaricaAggiornamento(); return true; } + await CercaAggiornamento(); + return new { versione = aggiornamento }; + case "aggiustaTutto": + { + var exe = Ambiente.Eseguibile(); + var fatti = string.IsNullOrEmpty(exe) ? [] : MenuLinux.Installa(exe, Ambiente.Casa()); + return new + { + passi = new[] { new { nome = "Tasto destro (Nautilus, Nemo, Dolphin)", esito = fatti.Count > 0 ? "ok" : "errore", nota = fatti.Count > 0 ? "Riavvia il gestore dei file se la voce non c'è subito." : "Non trovo il programma." } }, + daRiavviare = false, + menu11 = new { supportato = false, registrato = false, fidato = false, chiesto = true, windows11 = false, classico = false }, + regola = new { supportata = false, attiva = false, diAltri = false, impostati = 0, totale = 0, inAttesa = false }, + impostazioni = imp, + }; + } + case "registro": + if (File.Exists(Registro.Percorso)) Apri(Registro.Percorso); + return true; + case "link": + { + var url = (string?)a["url"] ?? ""; + if (url.StartsWith("https://it.libreoffice.org/") || url.StartsWith("https://github.com/cammo22/DaP-Convertitore")) + Apri(url); + return true; + } + case "menu11" or "predefinite" or "predefiniteTogli" or "menu" or "classico" or "esplora" or "disconnetti" or "avatar": + throw new ErroreConversione("Questa cosa c'è solo su Windows."); + case "incolla" or "indietro": + return cmd == "incolla" ? 0 : new { ids = Array.Empty(), percorsi = Array.Empty() }; + default: + throw new ErroreConversione("Questo comando su Linux non c'è ancora."); + } + } + + void Aggiungi(string percorso) + { + lock (lucchetto) + { + if (file.Values.Any(v => string.Equals(v.Info.Percorso, percorso, StringComparison.Ordinal))) return; + } + var info = analisi.Primo(percorso); + var voce = new Voce(info); + lock (lucchetto) { file[info.Id] = voce; ordine.Add(info.Id); } + Manda("file", FileDto(voce)); + _ = Task.Run(async () => + { + try + { + voce.Dettagli = await analisi.Dettagli(info); + Manda("dettagli", new { id = info.Id, dettagli = voce.Dettagli }); + } + catch (Exception e) { Registro.Scrivi($"Dettagli di {info.Nome}: {e.Message}"); } + }); + } + + Voce Prendi(string id) + { + lock (lucchetto) return file.TryGetValue(id, out var v) ? v : throw new ErroreConversione("Il file non è più nella lista."); + } + + bool Contiene(string id) { lock (lucchetto) return file.ContainsKey(id); } + + IEnumerable Ordinati() { lock (lucchetto) return ordine.Where(file.ContainsKey).Select(i => file[i]).ToList(); } + + static async Task> ScegliFile() + { + foreach (var (programma, argomenti) in new[] { ("/usr/bin/zenity", new[] { "--file-selection", "--multiple", "--separator=|", "--title=Scegli i file da convertire" }), ("/usr/bin/kdialog", new[] { "--getopenfilename", "--multiple", "--title", "Scegli i file da convertire" }) }) + { + if (!File.Exists(programma)) continue; + var r = await Processi.Esegui(programma, argomenti, CancellationToken.None); + if (r.Codice != 0 || string.IsNullOrWhiteSpace(r.Uscita)) return []; + var sep = programma.EndsWith("zenity") ? '|' : ' '; + return r.Uscita.Split(sep, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Where(File.Exists).ToList(); + } + throw new ErroreConversione("Per scegliere i file serve zenity (GNOME) o kdialog (KDE). Puoi anche usare il tasto destro sul file."); + } + + static void Apri(string? percorso) + { + if (string.IsNullOrWhiteSpace(percorso)) return; + Processi.Esegui("xdg-open", [percorso], CancellationToken.None).GetAwaiter().GetResult(); + } + + static void Mostra(string? percorso) + { + if (string.IsNullOrWhiteSpace(percorso)) return; + var cartella = Directory.Exists(percorso) ? percorso : Path.GetDirectoryName(percorso); + if (cartella is not null) Apri(cartella); + } + + async Task CercaAggiornamento() + { + try + { + using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(12) }; + using var risposta = await http.GetAsync(FonteAggiornamenti.Repo + "/releases/latest", HttpCompletionOption.ResponseHeadersRead); + var tag = Versioni.DalLink(risposta.RequestMessage?.RequestUri?.AbsoluteUri); + if (tag is null || !Versioni.PiùNuova(versione, tag)) return; + aggiornamento = tag; + Manda("aggiornamento", new { versione = tag }); + } + catch (Exception e) { Registro.Scrivi($"Aggiornamenti: lo riprovo fra un po' ({e.Message})"); } + } + + async Task ScaricaAggiornamento() + { + var nome = "DaPConvertitore-linux.AppImage"; + var dest = Path.Combine(Ambiente.Casa(), "Scaricati", nome); + if (!Directory.Exists(Path.GetDirectoryName(dest)!)) dest = Path.Combine(Ambiente.Casa(), "Downloads", nome); + Directory.CreateDirectory(Path.GetDirectoryName(dest)!); + using var http = new HttpClient { Timeout = TimeSpan.FromMinutes(30) }; + using var risposta = await http.GetAsync(FonteAggiornamenti.Repo + "/releases/latest/download/" + nome); + if (!risposta.IsSuccessStatusCode) + throw new ErroreConversione("L'aggiornamento non è ancora scaricabile. Riprova fra un po'."); + await using (var ingresso = await risposta.Content.ReadAsStreamAsync()) + await using (var uscita = File.Create(dest)) + await ingresso.CopyToAsync(uscita); + try { File.SetUnixFileMode(dest, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute | UnixFileMode.GroupRead | UnixFileMode.GroupExecute | UnixFileMode.OtherRead | UnixFileMode.OtherExecute); } catch { } + Registro.Scrivi($"Aggiornamento scaricato in {dest}"); + var avvio = new System.Diagnostics.ProcessStartInfo(dest) { UseShellExecute = false }; + System.Diagnostics.Process.Start(avvio); + finestra?.Close(); + } + + void Manda(string evento, object? dati) + { + var testo = JsonSerializer.Serialize(new { evento, dati }, json); + try { finestra?.SendWebMessage(testo); } catch { /* la finestra è già chiusa */ } + } + + void Rispondi(int id, bool ok, object? dati, string? errore) + { + var testo = JsonSerializer.Serialize(new { id, ok, dati, errore }, json); + try { finestra?.SendWebMessage(testo); } catch { } + } + + static object FileDto(Voce v) => new + { + v.Info.Id, v.Info.Percorso, v.Info.Nome, v.Info.Cartella, v.Info.Estensione, v.Info.Categoria, v.Info.NomeCategoria, + v.Info.Peso, v.Info.EDirectory, v.Info.Formati, dettagli = v.Dettagli, anteprima = (string?)null, + }; + + static object LavoroDto(Lavoro l) => new + { + l.Id, l.FileId, l.Sorgenti, formato = l.Formato.Id, etichetta = l.Formato.Etichetta, + stato = l.Stato.ToString().ToLowerInvariant(), + frazione = double.IsFinite(l.Frazione) ? l.Frazione : 0, + l.Fase, l.Velocita, l.Fps, eta = l.Eta is { } e && double.IsFinite(e) ? e : (double?)null, + l.Uscita, l.PesoPrima, l.PesoDopo, l.Errore, l.Dettaglio, l.Secondi, l.NelCestino, l.NotaCestino, + }; + + object? HardwareDto() => hardware is null ? null : new + { + cpu = hardware.Cpu, thread = hardware.Thread, + gpu = hardware.Gpu.Select(g => new { g.Nome, g.Marca, g.Vram, g.Driver }), + encoder = hardware.Encoder, acceleratore = hardware.Acceleratore, + }; + + sealed class SenzaStampante : IStampante + { + public Task Stampa(string fileHtml, string pdf, CancellationToken ct) => + throw new ErroreConversione("Stampare una pagina web in PDF per ora c'è solo su Windows."); + public Task Testo(string fileHtml, CancellationToken ct) => + throw new ErroreConversione("Leggere una pagina web per ora c'è solo su Windows."); + } +} diff --git a/src/DaPConvertitore.Linux/Programma.cs b/src/DaPConvertitore.Linux/Programma.cs new file mode 100644 index 0000000..f60fece --- /dev/null +++ b/src/DaPConvertitore.Linux/Programma.cs @@ -0,0 +1,70 @@ +using Photino.NET; + +namespace DaP.Convertitore.Linux; + +/// DaP Convertitore su Linux: la stessa pagina del programma di Windows, dentro WebKit. +static class Programma +{ + public static string Versione + { + get + { + var v = typeof(Programma).Assembly.GetName().Version; + return v is null ? "0.0.0" : $"{v.Major}.{v.Minor}.{Math.Max(0, v.Build)}"; + } + } + + [STAThread] + static int Main(string[] args) + { + if (args.Contains("--versione")) { Console.WriteLine(Versione); return 0; } + if (args.Contains("--menu")) + { + var exe = Ambiente.Eseguibile(); + foreach (var p in MenuLinux.Installa(exe, Ambiente.Casa())) Console.WriteLine(p); + return 0; + } + + var file = args.Where(a => !a.StartsWith('-') && (File.Exists(a) || Directory.Exists(a))).Select(Path.GetFullPath).ToList(); + var ponte = new PonteLinux(Versione, file); + var pagina = TrovaPagina(); + var finestra = new PhotinoWindow() + .SetTitle("DaP Convertitore") + .SetChromeless(true) + .SetUseOsDefaultSize(false) + .SetSize(1180, 760) + .SetFileSystemAccessEnabled(true) + .SetMediaAutoplayEnabled(true) + .RegisterWebMessageReceivedHandler((_, messaggio) => ponte.Ricevi(messaggio)); + var icona = Path.Combine(AppContext.BaseDirectory, "icona.png"); + if (File.Exists(icona)) finestra.SetIconFile(icona); + ponte.Collega(finestra); + finestra.Load(pagina); + finestra.WaitForClose(); + return 0; + } + + static string TrovaPagina() + { + for (var d = new DirectoryInfo(AppContext.BaseDirectory); d is not null; d = d.Parent) + { + foreach (var relativo in new[] { Path.Combine("ui", "index.html"), Path.Combine("ui", "dist", "index.html") }) + { + var p = Path.Combine(d.FullName, relativo); + if (File.Exists(p)) return p; + } + } + throw new FileNotFoundException("Non trovo l'interfaccia (ui/index.html)."); + } +} + +static class Ambiente +{ + public static string Casa() => Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); + + /// L'AppImage, se ci siamo dentro: se no l'eseguibile vero. + public static string Eseguibile() => + Environment.GetEnvironmentVariable("APPIMAGE") is { Length: > 0 } app && File.Exists(app) + ? app + : Environment.ProcessPath ?? ""; +} diff --git a/src/DaPConvertitore.Motore/Cestino.cs b/src/DaPConvertitore.Motore/Cestino.cs index 26a1ae7..5d6ebfc 100644 --- a/src/DaPConvertitore.Motore/Cestino.cs +++ b/src/DaPConvertitore.Motore/Cestino.cs @@ -12,6 +12,7 @@ public static class Cestino /// null se è andato nel Cestino, se no il perché è rimasto. public static string? Sposta(string percorso) { + if (!OperatingSystem.IsWindows()) return SpostaLinux(percorso); try { var radice = Path.GetPathRoot(Path.GetFullPath(percorso)); @@ -32,6 +33,32 @@ public static class Cestino catch (Exception e) { return e.Message; } } + /// Il Cestino di Linux (la specifica FreeDesktop): il file si sposta, non si cancella. + static string? SpostaLinux(string percorso) + { + try + { + if (!File.Exists(percorso) && !Directory.Exists(percorso)) return "non c'è più"; + var casa = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); + var files = Path.Combine(casa, ".local", "share", "Trash", "files"); + var info = Path.Combine(casa, ".local", "share", "Trash", "info"); + Directory.CreateDirectory(files); + Directory.CreateDirectory(info); + var nome = Path.GetFileName(percorso.TrimEnd('/', '\\')); + var dest = Path.Combine(files, nome); + for (var n = 2; File.Exists(dest) || Directory.Exists(dest); n++) + dest = Path.Combine(files, Path.GetFileNameWithoutExtension(nome) + " " + n + Path.GetExtension(nome)); + var pieno = Path.GetFullPath(percorso); + if (Directory.Exists(pieno)) Directory.Move(pieno, dest); + else File.Move(pieno, dest); + var path = pieno.Replace("%", "%25").Replace(" ", "%20"); + File.WriteAllText(Path.Combine(info, Path.GetFileName(dest) + ".trashinfo"), + "[Trash Info]\nPath=" + path + "\nDeletionDate=" + DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss") + "\n"); + return null; + } + catch (Exception e) { return e.Message; } + } + const uint FO_DELETE = 3; const ushort FOF_SILENT = 0x4, FOF_NOCONFIRMATION = 0x10, FOF_ALLOWUNDO = 0x40, FOF_NOERRORUI = 0x400; diff --git a/src/DaPConvertitore.Motore/DaPConvertitore.Motore.csproj b/src/DaPConvertitore.Motore/DaPConvertitore.Motore.csproj index 9a5c60f..4de8182 100644 --- a/src/DaPConvertitore.Motore/DaPConvertitore.Motore.csproj +++ b/src/DaPConvertitore.Motore/DaPConvertitore.Motore.csproj @@ -5,8 +5,38 @@ DaP.Convertitore DaPConvertitore.Motore + + net10.0;net10.0-windows10.0.22621.0 + + 10.0.19041.0 + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/DaPConvertitore.Motore/Ffmpeg.cs b/src/DaPConvertitore.Motore/Ffmpeg.cs index 04d53c9..ec74b3c 100644 --- a/src/DaPConvertitore.Motore/Ffmpeg.cs +++ b/src/DaPConvertitore.Motore/Ffmpeg.cs @@ -43,7 +43,8 @@ public static string Spiega(string errori) { var e = errori.ToLowerInvariant(); if (e.Contains("no space left")) return "Il disco è pieno."; - if (e.Contains("permission denied") || e.Contains("access is denied")) return "Windows non mi lascia scrivere in quella cartella."; + if (e.Contains("permission denied") || e.Contains("access is denied")) + return OperatingSystem.IsWindows() ? "Windows non mi lascia scrivere in quella cartella." : "Non ho il permesso di scrivere in quella cartella."; if (e.Contains("invalid data found") || e.Contains("moov atom not found")) return "Il file è rovinato o incompleto."; if (e.Contains("openencodesessionex failed") || e.Contains("nvenc") && e.Contains("failed")) return "La scheda video non è riuscita a codificare."; if (e.Contains("subtitle") && (e.Contains("bitmap") || e.Contains("not supported"))) return "Questi sottotitoli sono immagini: non diventano testo."; diff --git a/src/DaPConvertitore.Motore/Lettore/Contenuti.cs b/src/DaPConvertitore.Motore/Lettore/Contenuti.cs index 4549d3c..7333811 100644 --- a/src/DaPConvertitore.Motore/Lettore/Contenuti.cs +++ b/src/DaPConvertitore.Motore/Lettore/Contenuti.cs @@ -9,9 +9,6 @@ namespace DaP.Convertitore.Lettore; -/// Una voce di un archivio, per l'albero del lettore. -public sealed record VoceArchivio(string Percorso, long Peso, bool Cartella, DateTime? Data); - /// /// Quello che c'è dentro i file che non sono né video né carta: testi, tabelle, archivi, foto (con i dati della /// macchina fotografica) e, per tutto il resto, i byte. diff --git a/src/DaPConvertitore.Motore/Lettore/VoceArchivio.cs b/src/DaPConvertitore.Motore/Lettore/VoceArchivio.cs new file mode 100644 index 0000000..2a9e9f5 --- /dev/null +++ b/src/DaPConvertitore.Motore/Lettore/VoceArchivio.cs @@ -0,0 +1,4 @@ +namespace DaP.Convertitore.Lettore; + +/// Una voce di un archivio, per l'albero del lettore. +public sealed record VoceArchivio(string Percorso, long Peso, bool Cartella, DateTime? Data); diff --git a/src/DaPConvertitore.Motore/Linux/Immagini.cs b/src/DaPConvertitore.Motore/Linux/Immagini.cs new file mode 100644 index 0000000..da462ff --- /dev/null +++ b/src/DaPConvertitore.Motore/Linux/Immagini.cs @@ -0,0 +1,80 @@ +namespace DaP.Convertitore; + +/// +/// Le immagini su Linux: le fa FFmpeg (su Windows le fa WIC, in Immagini.cs). Stesso nome di classe, +/// così il resto del motore non cambia. Questo file si compila solo per net10.0. +/// +public static class Immagini +{ + public static async Task<(int w, int h)?> Misure(string percorso) + { + try + { + var info = await Sonda.Leggi(Strumenti.Trova(), percorso, silenzioso: true); + return info.Video is { } v && v.Larghezza > 0 ? (v.Larghezza, v.Altezza) : null; + } + catch { return null; } + } + + public static async Task Converti(Lavoro l, Contesto ctx) + { + var o = l.Opzioni.Immagine; + var est = l.Formato.Estensione; + ctx.Fase("Converto l'immagine"); + var qualita = o.Qualita is > 0 and <= 100 ? o.Qualita : 88; + if (o.Modo == "peso" && o.PesoMaxByte > 0) + qualita = await QualitaPerPeso(l, ctx, est, o.Lato, o.PesoMaxByte, qualita); + await Scrivi(ctx, l.Sorgente, l.Bozza, est, o.Lato, qualita); + } + + /// Quanto pesa la foto a questa qualità: una codifica vera, per lo slider. + public static async Task<(long Peso, int Qualita, int Larghezza, int Altezza)> Stima(string percorso, string est, int lato, int qualita, long pesoMax, CancellationToken ct) + { + var ctx = new Contesto(Strumenti.Trova(), new InfoHardware("", 1, [], []), ct, _ => { }); + try + { + var q = qualita is > 0 and <= 100 ? qualita : 88; + if (pesoMax > 0) q = await QualitaPerPeso(null, ctx, est, lato, pesoMax, q, percorso); + var bozza = Path.Combine(ctx.Temporanea(), "stima" + est); + await Scrivi(ctx, percorso, bozza, est, lato, q); + var misure = await Misure(bozza); + return (new FileInfo(bozza).Length, q, misure?.w ?? 0, misure?.h ?? 0); + } + finally { ctx.Pulisci(); } + } + + static async Task QualitaPerPeso(Lavoro? l, Contesto ctx, string est, int lato, long pesoMax, int partenza, string? sorgente = null) + { + var ingresso = sorgente ?? l!.Sorgente; + var meglio = partenza; + foreach (var q in new[] { 90, 75, 60, 45, 30 }) + { + var bozza = Path.Combine(ctx.Temporanea(), $"peso-{q}{est}"); + await Scrivi(ctx, ingresso, bozza, est, lato, q); + if (new FileInfo(bozza).Length <= pesoMax) { meglio = q; break; } + meglio = q; + } + return meglio; + } + + static async Task Scrivi(Contesto ctx, string ingresso, string uscita, string est, int lato, int qualita) + { + var argomenti = new List { "-i", ingresso }; + if (lato > 0) { argomenti.Add("-vf"); argomenti.Add($"scale='min({lato},iw)':-2"); } + argomenti.AddRange(est switch + { + ".jpg" or ".jpeg" => new[] { "-q:v", Jpeg(qualita) }, + ".webp" => new[] { "-c:v", "libwebp", "-quality", qualita.ToString() }, + ".avif" => new[] { "-c:v", "libaom-av1", "-still-picture", "1", "-cpu-used", "6", "-crf", Avif(qualita) }, + ".gif" => new[] { "-loop", "0" }, + _ => Array.Empty(), + }); + argomenti.Add(uscita); + await Ffmpeg.Esegui(ctx, argomenti, 1, fase: "Converto l'immagine"); + } + + /// FFmpeg vuole 2 (bellissima) … 31 (brutta) per il JPEG. + static string Jpeg(int qualita) => Math.Clamp(31 - (qualita - 1) * 29 / 99, 2, 31).ToString(); + + static string Avif(int qualita) => Math.Clamp(63 - qualita * 63 / 100, 10, 63).ToString(); +} diff --git a/src/DaPConvertitore.Motore/Linux/MenuLinux.cs b/src/DaPConvertitore.Motore/Linux/MenuLinux.cs new file mode 100644 index 0000000..180aa2b --- /dev/null +++ b/src/DaPConvertitore.Motore/Linux/MenuLinux.cs @@ -0,0 +1,71 @@ +namespace DaP.Convertitore; + +/// +/// Il tasto destro sui file, su Linux: uno script per Nautilus e Nemo, una voce per Dolphin, +/// e l'icona nel menu delle applicazioni. Niente rete: sono file di testo nella cartella dell'utente. +/// +public static class MenuLinux +{ + /// Virgolette da shell: le singole, perché il percorso può avere spazi. + public static string Virgolette(string percorso) => "'" + percorso.Replace("'", "'\\''") + "'"; + + /// Virgolette da file .desktop: le doppie, come le vuole la specifica. + public static string Desktop(string percorso) => "\"" + percorso.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\""; + + public static string ScriptNautilus(string exe) => + "#!/bin/sh\n" + + "# DaP Convertitore: i file scelti in Nautilus o Nemo.\n" + + "APP=" + Virgolette(exe) + "\n" + + "IFS='\n'\n" + + "set --\n" + + "for f in $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS$NEMO_SCRIPT_SELECTED_FILE_PATHS; do\n" + + " [ -n \"$f\" ] && set -- \"$@\" \"$f\"\n" + + "done\n" + + "exec \"$APP\" \"$@\"\n"; + + public static string ServizioDolphin(string exe) => + "[Desktop Entry]\n" + + "Type=Service\n" + + "ServiceTypes=KonqPopupMenu/Plugin\n" + + "MimeType=all/all;\n" + + "Actions=DaP\n" + + "X-KDE-Priority=TopLevel\n" + + "\n" + + "[Desktop Action DaP]\n" + + "Name=DaP Convertitore\n" + + "Icon=dap-convertitore\n" + + "Exec=" + Desktop(exe) + " %F\n"; + + public static string Applicazione(string exe) => + "[Desktop Entry]\n" + + "Type=Application\n" + + "Name=DaP Convertitore\n" + + "Comment=Converti video, musica, foto e documenti\n" + + "Exec=" + Desktop(exe) + " %F\n" + + "Icon=dap-convertitore\n" + + "Terminal=false\n" + + "Categories=AudioVideo;Utility;\n" + + "MimeType=video/mp4;video/x-matroska;audio/mpeg;audio/flac;image/jpeg;image/png;application/pdf;\n"; + + /// Scrive i tre file e restituisce i percorsi. è la home dell'utente. + public static IReadOnlyList Installa(string exe, string casa) + { + var fatti = new List(); + void Scrivi(string percorso, string testo, bool eseguibile) + { + Directory.CreateDirectory(Path.GetDirectoryName(percorso)!); + File.WriteAllText(percorso, testo.Replace("\n", "\n")); + if (eseguibile) + { + try { File.SetUnixFileMode(percorso, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute | UnixFileMode.GroupRead | UnixFileMode.GroupExecute | UnixFileMode.OtherRead | UnixFileMode.OtherExecute); } + catch { /* su un disco senza i permessi Unix il file c'è lo stesso */ } + } + fatti.Add(percorso); + } + Scrivi(Path.Combine(casa, ".local", "share", "nautilus", "scripts", "DaP Convertitore"), ScriptNautilus(exe), true); + Scrivi(Path.Combine(casa, ".local", "share", "nemo", "scripts", "DaP Convertitore"), ScriptNautilus(exe), true); + Scrivi(Path.Combine(casa, ".local", "share", "kio", "servicemenus", "dap-convertitore.desktop"), ServizioDolphin(exe), false); + Scrivi(Path.Combine(casa, ".local", "share", "applications", "dap-convertitore.desktop"), Applicazione(exe), false); + return fatti; + } +} diff --git a/src/DaPConvertitore.Motore/Linux/Pdf.cs b/src/DaPConvertitore.Motore/Linux/Pdf.cs new file mode 100644 index 0000000..2f9e0dc --- /dev/null +++ b/src/DaPConvertitore.Motore/Linux/Pdf.cs @@ -0,0 +1,114 @@ +using System.Text; +using PdfSharp.Drawing; +using PdfSharp.Pdf.IO; +using UglyToad.PdfPig.DocumentLayoutAnalysis.TextExtractor; +using PdfNuovo = PdfSharp.Pdf.PdfDocument; +using PdfTesto = UglyToad.PdfPig.PdfDocument; + +namespace DaP.Convertitore; + +/// +/// I PDF su Linux. Il testo e l'unione li fanno PdfPig e PDFsharp (gli stessi di Windows, senza l'OCR +/// e senza il disegno pagine di Windows). Questo file si compila solo per net10.0. +/// +public static class Pdf +{ + public static Task Converti(Lavoro l, Contesto ctx) => l.Formato.Id switch + { + "pdf.txt" => Testo(l, ctx), + "pdf.unisci" => Unisci(l, ctx), + "img.pdf" => DaImmagini(l, ctx), + "pdf.jpg" or "pdf.png" => Pagine(l, ctx), + "img.txt" => throw new ErroreConversione("Leggere il testo dentro una foto (OCR) per ora c'è solo su Windows."), + _ => throw new ErroreConversione($"Non so fare {l.Formato.Etichetta} da un PDF."), + }; + + public static Task Pagine(string percorso) + { + try + { + using var doc = PdfTesto.Open(percorso); + return Task.FromResult(doc.NumberOfPages); + } + catch { return Task.FromResult(null); } + } + + static async Task Testo(Lavoro l, Contesto ctx) + { + ctx.Fase("Leggo il testo"); + var testo = new StringBuilder(); + try + { + using var doc = PdfTesto.Open(l.Sorgente); + foreach (var p in doc.GetPages()) + { + ctx.Ct.ThrowIfCancellationRequested(); + testo.AppendLine(ContentOrderTextExtractor.GetText(p).Trim()); + testo.AppendLine(); + } + } + catch (OperationCanceledException) { throw; } + catch (Exception e) + { + throw new ErroreConversione("Questo PDF non si riesce a leggere. Se è una scansione, l'OCR per ora c'è solo su Windows.", e.Message); + } + if (testo.ToString().Count(char.IsLetterOrDigit) < 20) + throw new ErroreConversione("In questo PDF non trovo testo. Se è una scansione, l'OCR per ora c'è solo su Windows."); + await File.WriteAllTextAsync(l.Bozza, testo.ToString().TrimEnd() + Environment.NewLine, new UTF8Encoding(true), ctx.Ct); + } + + static Task Unisci(Lavoro l, Contesto ctx) => Task.Run(() => + { + var nuovo = new PdfNuovo(); + for (var i = 0; i < l.Sorgenti.Count; i++) + { + ctx.Ct.ThrowIfCancellationRequested(); + ctx.Riporta(new Avanzamento(i / (double)l.Sorgenti.Count, $"Unisco {Path.GetFileName(l.Sorgenti[i])}")); + try + { + using var dentro = PdfReader.Open(l.Sorgenti[i], PdfDocumentOpenMode.Import); + foreach (var pagina in dentro.Pages) nuovo.AddPage(pagina); + } + catch (PdfReaderException e) + { + throw new ErroreConversione($"{Path.GetFileName(l.Sorgenti[i])} è protetto o rovinato: non si può unire.", e.Message); + } + } + nuovo.Save(l.Bozza); + }, ctx.Ct); + + static Task DaImmagini(Lavoro l, Contesto ctx) => Task.Run(() => + { + var nuovo = new PdfNuovo(); + nuovo.Info.Creator = "DaP Convertitore"; + for (var i = 0; i < l.Sorgenti.Count; i++) + { + ctx.Ct.ThrowIfCancellationRequested(); + ctx.Riporta(new Avanzamento(i / (double)l.Sorgenti.Count, $"Impagino {Path.GetFileName(l.Sorgenti[i])}")); + using var img = XImage.FromFile(l.Sorgenti[i]); + var pagina = nuovo.AddPage(); + var orizzontale = img.PixelWidth > img.PixelHeight; + pagina.Width = XUnit.FromMillimeter(orizzontale ? 297 : 210); + pagina.Height = XUnit.FromMillimeter(orizzontale ? 210 : 297); + const double margine = 18; + double lw = pagina.Width.Point - 2 * margine, lh = pagina.Height.Point - 2 * margine; + var scala = Math.Min(lw / img.PixelWidth, lh / img.PixelHeight); + double w = img.PixelWidth * scala, h = img.PixelHeight * scala; + using var g = XGraphics.FromPdfPage(pagina); + g.DrawImage(img, (pagina.Width.Point - w) / 2, (pagina.Height.Point - h) / 2, w, h); + } + nuovo.Save(l.Bozza); + }, ctx.Ct); + + static async Task Pagine(Lavoro l, Contesto ctx) + { + if (ctx.Strumenti.LibreOffice is null) + throw new ErroreConversione("Per tirare fuori le pagine come immagini serve LibreOffice (è gratis).", "libreoffice"); + var est = l.Formato.Estensione; + Directory.CreateDirectory(l.Bozza); + var uno = Path.Combine(ctx.Temporanea(), "pagina" + est); + await Office.ConLibreOffice(ctx, l.Sorgente, est, uno); + var nome = "pagina 1" + est; + File.Move(uno, Path.Combine(l.Bozza, nome), true); + } +} diff --git a/src/DaPConvertitore.Motore/Strumenti.cs b/src/DaPConvertitore.Motore/Strumenti.cs index a2b7707..8021acc 100644 --- a/src/DaPConvertitore.Motore/Strumenti.cs +++ b/src/DaPConvertitore.Motore/Strumenti.cs @@ -16,7 +16,7 @@ public sealed class Strumenti public bool PowerPoint { get; init; } /// 7z.exe (con 7z.dll accanto): il motore di tutti gli archivi. Viaggia con l'app. public string? SetteZip { get; init; } - public string Tar { get; init; } = Path.Combine(Environment.SystemDirectory, "tar.exe"); + public string Tar { get; init; } = OperatingSystem.IsWindows() ? Path.Combine(Environment.SystemDirectory, "tar.exe") : "tar"; /// %LocalAppData%\DaProd\Convertitore: impostazioni, cache dell'hardware, registro, profilo di LibreOffice. public static string CartellaDati @@ -48,7 +48,7 @@ public static Strumenti Trova() return new Strumenti { Ffmpeg = ffmpeg, - Ffprobe = Path.Combine(Path.GetDirectoryName(ffmpeg) ?? "", "ffprobe.exe"), + Ffprobe = Path.Combine(Path.GetDirectoryName(ffmpeg) ?? "", OperatingSystem.IsWindows() ? "ffprobe.exe" : "ffprobe"), SetteZip = CercaSetteZip(), LibreOffice = CercaLibreOffice(), Word = ComRegistrato("Word.Application"), @@ -60,22 +60,50 @@ public static Strumenti Trova() static string CercaFfmpeg() { // accanto all'exe (installato), poi su per le cartelle fino al repo (sviluppo e prove) + var nome = OperatingSystem.IsWindows() ? "ffmpeg.exe" : "ffmpeg"; var dir = new DirectoryInfo(AppContext.BaseDirectory); for (var d = dir; d is not null; d = d.Parent) { - var p = Path.Combine(d.FullName, "motori", "ffmpeg", "ffmpeg.exe"); - if (File.Exists(p)) return p; + foreach (var sotto in OperatingSystem.IsWindows() ? new[] { "ffmpeg" } : new[] { "ffmpeg-linux", "ffmpeg" }) + { + var p = Path.Combine(d.FullName, "motori", sotto, nome); + if (File.Exists(p)) return p; + } } - foreach (var cartella in (Environment.GetEnvironmentVariable("PATH") ?? "").Split(';', StringSplitOptions.RemoveEmptyEntries)) + var sep = OperatingSystem.IsWindows() ? ';' : Path.PathSeparator; + foreach (var cartella in (Environment.GetEnvironmentVariable("PATH") ?? "").Split(sep, StringSplitOptions.RemoveEmptyEntries)) { - var p = Path.Combine(cartella.Trim(), "ffmpeg.exe"); + var p = Path.Combine(cartella.Trim(), nome); if (File.Exists(p)) return p; } - return Path.Combine(AppContext.BaseDirectory, "motori", "ffmpeg", "ffmpeg.exe"); + var cartellaMotori = OperatingSystem.IsWindows() ? "ffmpeg" : "ffmpeg-linux"; + return Path.Combine(AppContext.BaseDirectory, "motori", cartellaMotori, nome); } static string? CercaSetteZip() { + if (!OperatingSystem.IsWindows()) + { + for (var d = new DirectoryInfo(AppContext.BaseDirectory); d is not null; d = d.Parent) + { + foreach (var nome in new[] { "7zz", "7z" }) + { + var p = Path.Combine(d.FullName, "motori", "7zip-linux", nome); + if (File.Exists(p)) return p; + var accanto = Path.Combine(d.FullName, "motori", "7zip", nome); + if (File.Exists(accanto)) return accanto; + } + } + foreach (var cartella in (Environment.GetEnvironmentVariable("PATH") ?? "").Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries)) + { + foreach (var nome in new[] { "7zz", "7z" }) + { + var p = Path.Combine(cartella.Trim(), nome); + if (File.Exists(p)) return p; + } + } + return null; + } // accanto all'exe (installato), poi su per le cartelle fino al repo (sviluppo e prove) for (var d = new DirectoryInfo(AppContext.BaseDirectory); d is not null; d = d.Parent) { @@ -108,6 +136,16 @@ static string CercaFfmpeg() var p = Path.Combine(pf, "LibreOffice", "program", "soffice.exe"); if (File.Exists(p)) return p; } + if (!OperatingSystem.IsWindows()) + { + foreach (var p in new[] { "/usr/bin/soffice", "/usr/lib/libreoffice/program/soffice" }) + if (File.Exists(p)) return p; + foreach (var cartella in (Environment.GetEnvironmentVariable("PATH") ?? "").Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries)) + { + var p = Path.Combine(cartella.Trim(), "soffice"); + if (File.Exists(p)) return p; + } + } return null; } diff --git a/src/DaPConvertitore.Motore/Versioni.cs b/src/DaPConvertitore.Motore/Versioni.cs new file mode 100644 index 0000000..73450a3 --- /dev/null +++ b/src/DaPConvertitore.Motore/Versioni.cs @@ -0,0 +1,39 @@ +namespace DaP.Convertitore; + +/// Confronta due numeri di versione (2.3.0 e v2.3.1). Lo usa Linux per l'avviso di aggiornamento, senza API. +public static class Versioni +{ + public static int[]? Parti(string? testo) + { + if (string.IsNullOrWhiteSpace(testo)) return null; + var v = testo.Trim().TrimStart('v', 'V'); + var i = v.IndexOfAny(['/', '?', '#', ' ']); + if (i >= 0) v = v[..i]; + var pezzi = v.Split('.'); + if (pezzi.Length < 3) return null; + if (!int.TryParse(pezzi[0], out var a) || !int.TryParse(pezzi[1], out var b) || !int.TryParse(pezzi[2], out var c)) return null; + return [a, b, c]; + } + + /// Vero se è più nuova di . + public static bool PiùNuova(string attuale, string trovata) + { + var a = Parti(attuale); + var b = Parti(trovata); + if (a is null || b is null) return false; + for (var i = 0; i < 3; i++) + if (b[i] != a[i]) return b[i] > a[i]; + return false; + } + + /// Dal link finale di /releases/latest (…/releases/tag/v2.3.0) tira fuori la versione. + public static string? DalLink(string? url) + { + if (string.IsNullOrWhiteSpace(url)) return null; + const string segno = "/tag/"; + var i = url.LastIndexOf(segno, StringComparison.OrdinalIgnoreCase); + if (i < 0) return null; + var tag = url[(i + segno.Length)..].Trim().Trim('/'); + return Parti(tag) is null ? null : tag.TrimStart('v', 'V'); + } +} diff --git a/src/DaPConvertitore/DaPConvertitore.csproj b/src/DaPConvertitore/DaPConvertitore.csproj index 4eb8f79..4653b6c 100644 --- a/src/DaPConvertitore/DaPConvertitore.csproj +++ b/src/DaPConvertitore/DaPConvertitore.csproj @@ -4,6 +4,8 @@ WinExe true + win-x64 + 10.0.19041.0 DaPConvertitore DaP.Convertitore.App ..\..\risorse\icona.ico diff --git a/test/DaPConvertitore.Prove.Linux/DaPConvertitore.Prove.Linux.csproj b/test/DaPConvertitore.Prove.Linux/DaPConvertitore.Prove.Linux.csproj new file mode 100644 index 0000000..aa7d2ac --- /dev/null +++ b/test/DaPConvertitore.Prove.Linux/DaPConvertitore.Prove.Linux.csproj @@ -0,0 +1,26 @@ + + + + net10.0 + + false + true + enable + + + + + + + + + + + + + + + + + + diff --git a/test/DaPConvertitore.Prove.Linux/ProveLinux.cs b/test/DaPConvertitore.Prove.Linux/ProveLinux.cs new file mode 100644 index 0000000..74864fb --- /dev/null +++ b/test/DaPConvertitore.Prove.Linux/ProveLinux.cs @@ -0,0 +1,81 @@ +using PdfSharp.Pdf; + +namespace DaP.Convertitore.Prove.Linux; + +/// Quello che la versione Linux deve saper fare senza Windows: versioni, menu, PDF, Cestino, una foto con FFmpeg. +public class ProveLinux +{ + [Fact] + public void UnaVersionePiùNuovaSiRiconosceDalLink() + { + Assert.False(Versioni.PiùNuova("2.3.0", "2.3.0")); + Assert.False(Versioni.PiùNuova("2.3.0", "v2.2.9")); + Assert.True(Versioni.PiùNuova("2.3.0", "v2.3.1")); + Assert.True(Versioni.PiùNuova("2.3.0", "2.4.0")); + Assert.Equal("2.3.1", Versioni.DalLink("https://github.com/cammo22/DaP-Convertitore/releases/tag/v2.3.1")); + Assert.Null(Versioni.DalLink("https://github.com/cammo22/DaP-Convertitore/releases")); + } + + [Fact] + public void IlMenuNominaIlProgramma() + { + var exe = "/home/cammo/DaP Convertitore.AppImage"; + var script = MenuLinux.ScriptNautilus(exe); + Assert.Contains("'/home/cammo/DaP Convertitore.AppImage'", script); + Assert.Contains("NAUTILUS_SCRIPT_SELECTED_FILE_PATHS", script); + Assert.Contains("NEMO_SCRIPT_SELECTED_FILE_PATHS", script); + var dolphin = MenuLinux.ServizioDolphin(exe); + Assert.Contains("Name=DaP Convertitore", dolphin); + Assert.Contains("%F", dolphin); + var casa = Directory.CreateTempSubdirectory("dap-menu").FullName; + var fatti = MenuLinux.Installa(exe, casa); + Assert.Equal(4, fatti.Count); + Assert.Contains("DaP Convertitore", File.ReadAllText(fatti[0])); + Assert.Contains("dap-convertitore.desktop", fatti[2]); + } + + [Fact] + public void IlCestinoLinuxNonCancella() + { + var origine = Path.Combine(Path.GetTempPath(), "dap-cestino-" + Guid.NewGuid().ToString("N") + ".txt"); + File.WriteAllText(origine, "ciao"); + Assert.Null(Cestino.Sposta(origine)); + Assert.False(File.Exists(origine)); + var nome = Path.GetFileName(origine); + var nelCestino = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".local", "share", "Trash", "files", nome); + var info = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".local", "share", "Trash", "info", nome + ".trashinfo"); + Assert.True(File.Exists(nelCestino)); + Assert.Contains("Path=", File.ReadAllText(info)); + File.Delete(nelCestino); + File.Delete(info); + } + + [Fact] + public async Task UnPdfSiConta() + { + var p = Path.Combine(Path.GetTempPath(), "dap-" + Guid.NewGuid().ToString("N") + ".pdf"); + var doc = new PdfDocument(); + doc.AddPage(); + doc.AddPage(); + doc.Save(p); + Assert.Equal(2, await Pdf.Pagine(p)); + File.Delete(p); + } + + [Fact] + public async Task UnaFotoJpgEsceDaFfmpeg() + { + var s = Strumenti.Trova(); + if (!s.HaFfmpeg) return; + var cartella = Directory.CreateTempSubdirectory("dap-foto").FullName; + var png = Path.Combine(cartella, "rossa.png"); + var fatto = await Processi.Esegui(s.Ffmpeg, ["-y", "-f", "lavfi", "-i", "color=c=red:s=64x48", "-frames:v", "1", png], CancellationToken.None); + Assert.Equal(0, fatto.Codice); + var formato = Catalogo.Trova("img.jpg")!; + var lavoro = new Lavoro { Id = "t", Sorgenti = [png], Formato = formato, Opzioni = new Opzioni { Immagine = { Modo = "qualita", Qualita = 80 } } }; + lavoro.Bozza = Path.Combine(cartella, "rossa.jpg"); + var ctx = new Contesto(s, new InfoHardware("cpu", 1, [], []), CancellationToken.None, _ => { }); + await Immagini.Converti(lavoro, ctx); + Assert.True(new FileInfo(lavoro.Bozza).Length > 100); + } +} diff --git a/test/DaPConvertitore.Prove/DaPConvertitore.Prove.csproj b/test/DaPConvertitore.Prove/DaPConvertitore.Prove.csproj index d45f888..4d316a5 100644 --- a/test/DaPConvertitore.Prove/DaPConvertitore.Prove.csproj +++ b/test/DaPConvertitore.Prove/DaPConvertitore.Prove.csproj @@ -3,6 +3,9 @@ false true + + win-x64 + 10.0.19041.0 diff --git a/ui/src/ponte.ts b/ui/src/ponte.ts index 5014aeb..48c4505 100644 --- a/ui/src/ponte.ts +++ b/ui/src/ponte.ts @@ -202,7 +202,19 @@ type Ascoltatore = (dati: any) => void; interface WebView { postMessage(m: unknown): void; addEventListener(t: 'message', f: (e: { data: any }) => void): void } const webview: WebView | undefined = (window as any).chrome?.webview; -export const dentroApp = !!webview; +/** Su Linux la finestra è Photino (WebKit): parla con sendMessage, non con chrome.webview. Su Windows non si usa. */ +function photino(): WebView | undefined { + if (webview) return undefined; + const ext = (window as any).external; + if (!ext || typeof ext.sendMessage !== 'function' || typeof ext.receiveMessage !== 'function') return undefined; + ext.receiveMessage((dati: string) => { + try { arriva(typeof dati === 'string' ? JSON.parse(dati) : dati); } catch { /* un messaggio storto si ignora */ } + }); + return { postMessage: (m) => ext.sendMessage(JSON.stringify(m)), addEventListener: () => {} }; +} +const finestraLinux = photino(); + +export const dentroApp = !!webview || !!finestraLinux; let contatore = 0; const attese = new Map void; no: (e: Error) => void }>(); @@ -224,7 +236,7 @@ let finto: ((cmd: string, args: any, emetti: (e: string, d: any) => void) => Pro if (webview) webview.addEventListener('message', (e) => arriva(e.data)); export async function avviaFinto() { - if (webview) return; + if (dentroApp) return; const m = await import('./finto'); finto = m.rispondi; } @@ -232,11 +244,12 @@ export async function avviaFinto() { /** Una domanda all'app; la risposta arriva come promessa. */ export function chiedi(cmd: string, args: Record = {}): Promise { if (finto) return finto(cmd, args, (evento, dati) => arriva({ evento, dati })); - if (!webview) return Promise.reject(new Error('fuori dall\'app')); + const ponte = webview ?? finestraLinux; + if (!ponte) return Promise.reject(new Error('fuori dall\'app')); const id = ++contatore; return new Promise((ok, no) => { attese.set(id, { ok, no }); - webview.postMessage({ id, cmd, args }); + ponte.postMessage({ id, cmd, args }); }); }