diff --git a/AGENTS.md b/AGENTS.md index 2efa67a..9be60c8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -77,8 +77,30 @@ Cosa fa e come si usa: `README.md` (corto, per l'utente) e `docs/GUIDA.md` (comp codifica (`FormatoDi`: BOM UTF-8/UTF-16, CRLF se il file lo ha, Latin-1 → UTF-8 e lo si dice) con bozza e `Sposta`. Le voci scelte dentro un archivio escono con 7-Zip (`SetteZip.Estrai`, vedi sotto): il percorso di una cartella (`foto/`) porta con sé anche quello che c'è dentro (provato in `ProveScrittura`). -- **La barra bianca**: `.testa` (convertitore) e `.l-barra` (lettore) hanno uno sfondo chiaro apposta, il resto è - scuro. Non è la barra di Windows (la finestra è senza cornice): è disegnata dalla pagina. +- **La barra bianca**: `.testa` (convertitore) e `.l-barra` (lettore) hanno **sempre** uno sfondo bianco, il resto è + scuro. Non è la barra di Windows (la finestra è senza cornice): è disegnata dalla pagina. Le icone e le scritte + della barra vanno scure, che si leggano sul bianco: un'icona oro o chiara lì sopra sparisce (è successo al tasto Novità). +- **Con cosa si codifica**: in alto c'è una bolla. Il clic apre il menu delle schede che hanno un encoder + (nvidia, amd, intel) e del processore, e segna quella in uso. La scelta sta in `Impostazioni.CodificaCon` + (`gpu` / `cpu`) e in `video.motore`. Due schede della stessa marca condividono lo stesso encoder. La scritta + della bolla è l'unità scelta, non sempre la prima NVIDIA. +- **La scheda del file** sta nella colonna di mezzo, sezione richiudibile «Info del file», e si scrive **nel file + convertito** (l'originale non si tocca). Musica: titolo, artista, album, anno, traccia e, su MP3, M4A e FLAC, la + copertina. OGG, OPUS e WMA tengono i testi, non la copertina. Video MP4, MOV e MKV: titolo e commento. JPG e TIFF: + data dello scatto, descrizione, autore. Se il formato non le tiene, la sezione lo dice e non inventa campi. + La copertina del brano che stai ascoltando, e quella di un video MP4, MOV o MKV, si cambia sul file vero + (lettore e player dell'avatar): bozza accanto e poi si sostituisce, come la rotazione (`Copertine.cs`). + Nel video è un fotogramma allegato (`-disposition attached_pic`, flusso `0:V` per non copiare quello vecchio): + `Sonda.IndiceCopertina` lo trova e le miniature (`Anteprime`, `Multimedia.Video`) usano quello, non un fotogramma + a caso. Download la salva nella cartella del brano, senza chiedere dove e senza sovrascrivere. +- **I tagli del video** (`Modifiche.TagliaPezzi`): nel lettore restano Z e X (un pezzo solo, file «(tagliato)» accanto, + originale intatto). La striscia gialla 1/2/Q/W non c'è più. Il comando `taglia` accetta ancora `pezzi`; un pezzo solo + è `TagliaVideo`. Senza fotogrammi chiave vicini la copia può fallire: si dice, e il file resta. + L'anteprima nella piastra non ha la colonna a destra: play, barra (clic e trascinamento), frecce di un fotogramma, J/K/L. + «Fotogramma» salva il PNG in `CartellaLavori` (`salvaPng` se la pagina ha il quadro, altrimenti `salvaQuadro` con FFmpeg). + Nel lettore intero S salva ancora accanto al video. Il clic sull'onda di un brano sposta il punto e non lo fa sentire. +- **Dal lettore alla modifica** (`Regia.Converti`): il lettore si chiude. `PercorsoIndietro` mette «Indietro» sulla barra + bianca del convertitore (icona scura); `TornaAlLettore` riapre il lettore e chiude la piastra. - **Ritocco delle foto** (dalla 1.5.0): `ui/src/lettore/ritocco.ts` disegna su due fogli canvas (`base` = segni fissati, `viva` = segno in corso) grandi quanto la foto, dentro un wrapper che prende lo stesso `transform` della foto (`rit.segui`). Si salva componendo foto + segni in un canvas, codificato **dalla pagina** (JPG 0.97, PNG, WEBP) e @@ -130,5 +152,30 @@ Cosa fa e come si usa: `README.md` (corto, per l'utente) e `docs/GUIDA.md` (comp `1.45/scala` (quel conto a 32 pixel gonfiava il segno). La miniatura audio (`Multimedia.Audio`) mette la copertina a sinistra — `Media.Copertina`, dentro il file o `cover.jpg` / `folder.jpg`, in silenzio — e l'onda vera a destra (`Onde.Barre`). Sotto i 48 la copertina sta sopra e l'onda è una striscia; a 16–24 senza copertina si torna null e - resta il .ico. Il nome del file .ico porta la versione: al cambio si buttano i vecchi. Cosa non si fa ora (scheda - del file, tagli piccoli, niente montaggio: quello è DaProd Editor Video) sta in `docs/ROADMAP.md`. + resta il .ico. Il nome del file .ico porta la versione: al cambio si buttano i vecchi. Se il video ha una + copertina allegata, la miniatura è quella. Il montaggio vero resta DaProd Editor Video (`docs/ROADMAP.md`). +- **Quello che l'app produce** (screenshot, registrazioni) va in Immagini\DaPConvertitore (`CartellaLavori`). + Si crea all'avvio e nel hook di Velopack. `Impostazioni.CartellaMia` la sposta. Dalle Impostazioni si apre e si vedono gli ultimi file. +- **Il vassoio** (`Vassoio.cs`) c'è finché l'app è aperta e non la tiene in vita da solo. Menu: apri, screenshot, + Registra… (il menu dei dispositivi, o la barra se si sta già registrando), Avatar acceso/spento, impostazioni, esci. +- **Lo screenshot** (`Schermata.cs`): scorciatoia globale (`Impostazioni.ScorciatoiaSchermo`, di partenza Ctrl+Maiusc+S). + Il campo nelle Impostazioni è chiaro, alto come gli altri tasti, e in ascolto dice «Premi i tasti…» in oro. Lo schermo fermo resta luminoso + (l'immagine sotto è a opacità 0.72); la zona scelta è a piena luce. Tasto destro o Esc annullano. Misure, lente, + PNG nella cartella e negli appunti, anteprima in basso a destra. Lo schermo si fotografa prima dell'oscuramento. + Su più monitor con DPI diversi il ritaglio può slittare di un pixel. +- **La registrazione** (`Registrazione.cs`, `MenuRegistrazione`, `BarraRegistrazione`, `PosizioneFinestre`, + `Ancoraggio`, `AnteprimaSchermo`, `ComandiRegistrazione.cs`): vassoio, tasto destro dell'avatar e comando `registra` + passano da `Registrazione.Chiedi`. La finestra si apre a menu del clic già chiuso, è opaca (niente + `AllowsTransparency`: su Windows 11 una finestra trasparente con `WDA_EXCLUDEFROMCAPTURE` sparisce anche dallo + schermo) ed è esclusa dalla cattura. Sta accanto all'avatar, nell'area di lavoro del monitor dove sta lui, in pixel + veri (`Ancoraggio` + `SetWindowPos`): se l'avatar si sposta, lo segue. Avatar spento: centro del monitor principale. + Dentro c'è l'anteprima dal vivo (BitBlt, 8 fps, rimpicciolita) del monitor o della zona che si sta per registrare, + anche prima di Avvia e durante. Impostazioni: monitor, intero/zona/finestra, 30 o 60 fps, qualità (CRF 28/23/18), + microfono, audio del PC, cursore, conto alla rovescia, solo audio. La scelta si ricorda. «Riduci» lascia la barra + (tempo, Pausa, Salva, Annulla), anch'essa accanto all'avatar. gdigrab con offset del monitor o della zona, oppure + `title=` per una finestra; microfono DirectShow (`audio=nome`, senza virgolette aggiunte) e audio del PC in loopback + WASAPI. I livelli sono il misuratore di Windows, non un secondo FFmpeg. Screenshot e registrazioni entrano in + `storico.json` (`Storico.AggiungiFile`) e nei recenti della home, con miniatura; il clic li apre nel lettore. + Nel registro: clic, apertura, posizione in pixel, avvio, pausa, il comando ffmpeg, gli errori. Se si rilancia l'exe + mentre uno è già aperto, il registro dice «non parto». Su questa macchina ffmpeg non ha dshow né wasapi. + Il video sull'avatar è un `MediaElement`: se Windows non lo sa suonare, lo apre il lettore. diff --git a/CHANGELOG.md b/CHANGELOG.md index 795d1d6..2c837f3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,45 @@ Le novità di ogni versione, dette come stanno. La più nuova sta in alto. +## In lavorazione + +## 2.2.9 — 10 novembre 2026 + +### Registrare lo schermo + +- **Registra si apre accanto all'avatar.** Dal vassoio o dal tasto destro sull'avatar. Se l'avatar è su un altro monitor, la finestra sta su quello, dentro lo schermo, e se sposti l'avatar lei lo segue. Se l'avatar è spento, la finestra sta al centro del monitor principale. +- **Si vede lo schermo, dal vivo**, dentro la finestra, prima di partire e mentre registra. La finestra non entra nel video: nell'anteprima, nel punto dove sta lei, c'è un buco. Non è uno specchio. +- **Si sceglie come registrare.** Il monitor, se ne hai più di uno. Tutto lo schermo, una zona che trascini, oppure una finestra. 30 o 60 fotogrammi al secondo. Qualità leggera, buona o alta. Il microfono e l'audio del PC (quello che esce dalle casse), oppure Nessuno, con una tacca che si muove se il suono c'è. Il cursore si può lasciare fuori. Si può aspettare un conto alla rovescia di tre secondi. Si può registrare solo l'audio. La scelta resta per la prossima volta. +- **I tasti** sono Avvia, Pausa, Riprendi, Salva e Annulla, con il tempo. «Riduci» lascia una barra piccola, sempre accanto all'avatar, con gli stessi tasti. La pausa chiude un pezzo e la ripresa ne apre un altro; Salva li unisce in un file solo. Annulla non lascia niente. Il file è un MP4, oppure un M4A se è solo audio, in Immagini\DaPConvertitore. +- **Se lanci la build mentre DaP è già aperto**, non parte la copia nuova. Nel registro c'è scritto «non parto»: chiudi l'icona vicino all'orologio e rilancia. Nel registro si leggono anche il clic, dove si è aperta la finestra, il comando e gli errori. + +### Screenshot, vassoio e cartella + +- **Lo screenshot** (Ctrl+Maiusc+S, e si cambia dalle Impostazioni). Il riquadro della scorciatoia è alto come gli altri tasti. Cliccato, dice «Premi i tasti…» in oro. Lo schermo si scurisce appena, la zona scelta resta chiara, si vedono misure e lente. Il PNG va nella cartella, negli appunti e in un'anteprima in basso a destra. Esc o il tasto destro annullano. +- **Screenshot e registrazioni compaiono nei Recenti** della home, con la miniatura. Un clic li apre nel lettore. +- **La cartella DaPConvertitore** sta in Immagini. Ci finiscono screenshot, registrazioni e il fotogramma salvato da un video. Si crea da sola. Dalle Impostazioni si vede, si apre e si può cambiare. +- **L'icona vicino all'orologio**, finché l'app è aperta: Apri, Screenshot, Registra…, Avatar (acceso o spento), Impostazioni, Esci. Il doppio clic apre il convertitore. L'icona non tiene l'app in vita da sola. + +### Musica, copertina e scheda del file + +- **La copertina si vede sul player dell'avatar** e nel lettore. Passandoci sopra escono Modifica e Download. Download la salva nella cartella del brano, senza chiedere dove; se il nome c'è già ne fa un altro. Modifica la estrae, ne carica una, oppure ne sceglie una disegnata (viola, oro, magenta, dal titolo). Su MP3, M4A e FLAC entra nel file. Gli altri formati non la tengono dentro: viene salvata accanto e te lo dice. +- **Un video sull'avatar** parte come la musica. Se Windows non lo sa suonare, lo apre il lettore. La copertina di un MP4, MOV o MKV entra nel file ed è la miniatura, anche in Esplora file. Il film non si ricodifica. +- **Info del file**, nella colonna di mezzo. Musica: titolo, artista, album, anno, traccia, copertina. Video (MP4, MOV, MKV): titolo e commento. Foto (JPG e TIFF): data dello scatto, descrizione, autore. Quello che scrivi finisce nel file convertito. L'originale resta com'è. Se il formato non le tiene, la sezione lo dice. +- **«Di seguito» si chiama «Riproduci coda».** Il fulmine non sta più nella barra del lettore: le conversioni rapide restano col tasto U. Chiudi, nel menu della copertina, è un tasto come gli altri. + +### Anteprima, tagli e modifica + +- **L'anteprima di un brano** ha play, il volume e la timeline sotto la copertina e l'onda. Il clic sull'onda sposta il punto e non lo fa sentire. Il play parte anche se la durata letta è zero. Il peso finale dell'audio si vede sempre, con lo slider. +- **L'anteprima di un video** non ha più la colonna di fotogrammi a destra. Sotto: play, il tempo, Fotogramma, il volume, e una barra che si clicca e si trascina. Con l'anteprima selezionata, le frecce vanno di un fotogramma, J e L di dieci secondi, K mette in pausa. Fotogramma salva il PNG nella cartella. Nel lettore intero, S salva ancora accanto al video. +- **I tagli del video** nel lettore restano Z e X, per un pezzo solo, salvato accanto come «(tagliato)». L'originale resta. La striscia gialla (1, 2, Q, W) non c'è più: 1 e 2 tornano a saltare nel film. +- **Dal lettore alla modifica**: Converti chiude il lettore e apre la piastra su quel file. Sulla barra bianca, Indietro (icona scura) riapre il lettore e chiude la modifica. + +### La piastra + +- **La bolla in alto** apre il menu delle schede che sanno codificare e del processore, segna quella in uso e la ricorda, anche se non fai partire una conversione. +- **Novità**, sulla barra bianca, è scura e si legge. La testata resta ferma e il testo scorre sotto. Un link scritto come in markdown (per esempio DaProd Editor Video) è un link vero. +- **Impostazioni** è larga, su due colonne, con la testata ferma. Le carte dei formati e la colonna Sorgente sono più piccole, così entra più schermo. + ## 2.2.8 — 9 novembre 2026 - **Le icone dei file sono rifatte, e quelle piccole si leggono.** A 16, 20 e 24 pixel non c'è più il foglio piegato (diventava una macchia): c'è una mattonella tonda, viola notte, col bordo del colore del tipo e una sagoma piena. Video, musica, foto, PDF, documenti, fogli, presentazioni, codice, sottotitoli, archivi, caratteri e modelli hanno ognuno il suo segno. Dalle 32 pixel in su resta il foglio, col disegnino più nitido. diff --git a/Directory.Build.props b/Directory.Build.props index 979bf53..39e3d49 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -2,7 +2,7 @@ - 2.2.8 + 2.2.9 DaProd DaProdProduzioni DaP Convertitore diff --git a/src/DaPConvertitore.Motore/Ancoraggio.cs b/src/DaPConvertitore.Motore/Ancoraggio.cs new file mode 100644 index 0000000..495f964 --- /dev/null +++ b/src/DaPConvertitore.Motore/Ancoraggio.cs @@ -0,0 +1,94 @@ +using System.Globalization; + +namespace DaP.Convertitore; + +/// +/// Dove mettere una finestra accanto all'avatar, dentro l'area di lavoro del monitor dove sta lui. +/// Le coordinate sono tutte nello stesso sistema (pixel veri dello schermo, anche negativi): +/// chi chiama converte i DPI. Così una finestra non finisce sul monitor sbagliato né fuori. +/// +public static class Ancoraggio +{ + public const int Spazio = 12; + + /// Un rettangolo in pixel. X e Y possono essere negativi (monitor a sinistra del principale). + public readonly record struct Riquadro(int X, int Y, int L, int A) + { + public int Destra => X + L; + public int Fondo => Y + A; + } + + /// Accanto all'ancora, sul lato dove ci sta meglio, poi bloccata dentro l'area di lavoro. + public static Riquadro Accanto(Riquadro ancora, int larghezza, int altezza, Riquadro area) + { + if (area.L < 2 || area.A < 2) return new Riquadro(area.X, area.Y, Math.Max(1, larghezza), Math.Max(1, altezza)); + var l = Math.Clamp(larghezza, 1, area.L); + var a = Math.Clamp(altezza, 1, area.A); + var lati = new[] + { + new Riquadro(ancora.Destra + Spazio, Centra(ancora.Y, ancora.A, a), l, a), + new Riquadro(ancora.X - Spazio - l, Centra(ancora.Y, ancora.A, a), l, a), + new Riquadro(Centra(ancora.X, ancora.L, l), ancora.Y - Spazio - a, l, a), + new Riquadro(Centra(ancora.X, ancora.L, l), ancora.Fondo + Spazio, l, a), + }; + var scelta = lati[0]; + var meglio = -1; + foreach (var c in lati) + { + var visibile = Sovrapposizione(c, area); + if (visibile > meglio) { meglio = visibile; scelta = c; } + } + return Blocca(scelta, area); + } + + /// Al centro dell'area. Serve quando l'avatar è spento: il monitor principale. + public static Riquadro Centro(int larghezza, int altezza, Riquadro area) + { + if (area.L < 2 || area.A < 2) return new Riquadro(area.X, area.Y, Math.Max(1, larghezza), Math.Max(1, altezza)); + var l = Math.Clamp(larghezza, 1, area.L); + var a = Math.Clamp(altezza, 1, area.A); + return new Riquadro(area.X + (area.L - l) / 2, area.Y + (area.A - a) / 2, l, a); + } + + public static Riquadro Blocca(Riquadro r, Riquadro area) + { + var l = Math.Clamp(r.L, 1, Math.Max(1, area.L)); + var a = Math.Clamp(r.A, 1, Math.Max(1, area.A)); + var x = Math.Clamp(r.X, area.X, Math.Max(area.X, area.Destra - l)); + var y = Math.Clamp(r.Y, area.Y, Math.Max(area.Y, area.Fondo - a)); + return new Riquadro(x, y, l, a); + } + + public static bool Dentro(Riquadro r, Riquadro area) => + r.L > 0 && r.A > 0 && r.X >= area.X && r.Y >= area.Y && r.Destra <= area.Destra && r.Fondo <= area.Fondo; + + public static bool Tocca(Riquadro a, Riquadro b) => + a.L > 0 && a.A > 0 && a.X < b.Destra && a.Destra > b.X && a.Y < b.Fondo && a.Fondo > b.Y; + + public static string Chiave(Riquadro r) => + string.Create(CultureInfo.InvariantCulture, $"{r.X},{r.Y},{r.L},{r.A}"); + + public static bool ProvaChiave(string? testo, out Riquadro r) + { + r = default; + if (string.IsNullOrWhiteSpace(testo)) return false; + var p = testo.Split(','); + if (p.Length != 4) return false; + if (!int.TryParse(p[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out var x)) return false; + if (!int.TryParse(p[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out var y)) return false; + if (!int.TryParse(p[2], NumberStyles.Integer, CultureInfo.InvariantCulture, out var l)) return false; + if (!int.TryParse(p[3], NumberStyles.Integer, CultureInfo.InvariantCulture, out var a)) return false; + if (l < 2 || a < 2) return false; + r = new Riquadro(x, y, l, a); + return true; + } + + static int Centra(int inizio, int misuraAncora, int misura) => inizio + misuraAncora / 2 - misura / 2; + + static int Sovrapposizione(Riquadro a, Riquadro b) + { + var x = Math.Max(0, Math.Min(a.Destra, b.Destra) - Math.Max(a.X, b.X)); + var y = Math.Max(0, Math.Min(a.Fondo, b.Fondo) - Math.Max(a.Y, b.Y)); + return x * y; + } +} diff --git a/src/DaPConvertitore.Motore/Anteprime.cs b/src/DaPConvertitore.Motore/Anteprime.cs index 8daa4f8..ff8f7a1 100644 --- a/src/DaPConvertitore.Motore/Anteprime.cs +++ b/src/DaPConvertitore.Motore/Anteprime.cs @@ -1,5 +1,6 @@ using System.Runtime.InteropServices; using System.Runtime.InteropServices.WindowsRuntime; +using DaP.Convertitore.Lettore; using Windows.Graphics.Imaging; namespace DaP.Convertitore; @@ -23,6 +24,8 @@ public static class Anteprime { case Categoria.Video: { + var cover = await Copertine.ProvaAllegata(s, percorso, (int)lato); + if (cover is not null) return new Anteprima(cover, "image/jpeg"); var jpg = Path.Combine(Strumenti.CartellaTemporanea, $"anteprima-{Guid.NewGuid():N}.jpg"); try { diff --git a/src/DaPConvertitore.Motore/Audio.cs b/src/DaPConvertitore.Motore/Audio.cs index cf1c4fa..ccfed8e 100644 --- a/src/DaPConvertitore.Motore/Audio.cs +++ b/src/DaPConvertitore.Motore/Audio.cs @@ -1,3 +1,5 @@ +using DaP.Convertitore.Lettore; + namespace DaP.Convertitore; /// @@ -26,11 +28,35 @@ public static async Task Converti(Lavoro l, Contesto ctx) var info = await Sonda.Leggi(ctx.Strumenti, l.Sorgente, ctx.Ct); if (info.Audio.Count == 0) throw new ErroreConversione("In questo file non c'è audio."); - var a = new List { "-i", l.Sorgente, "-map", "0:a:0" }; - var copertina = info.Copertina && est is ".mp3" or ".m4a" or ".flac"; - if (copertina) a.AddRange(["-map", "0:v:0", "-c:v", "copy", "-disposition:v:0", "attached_pic"]); + // la copertina nuova (un disegno o un file scelto) sostituisce quella del brano; «nessuna» la toglie + var tieneCover = est is ".mp3" or ".m4a" or ".flac"; + string? nuova = null; + var togliCover = false; + var scheda = l.Opzioni.Scheda; + if (scheda is { Scrivi: true } && tieneCover && scheda.Copertina is { Length: > 0 } scelta) + { + if (scelta == "nessuna") togliCover = true; + else if (scelta.StartsWith("generata:", StringComparison.Ordinal)) + { + var n = int.TryParse(scelta["generata:".Length..], out var v) ? v : 0; + var png = Path.Combine(ctx.Temporanea(), "copertina.png"); + await File.WriteAllBytesAsync(png, Copertine.Genera(scheda.Titolo ?? "", n, null), ctx.Ct); + nuova = png; + } + else if (File.Exists(scelta)) nuova = scelta; + } + + var a = new List { "-i", l.Sorgente }; + if (nuova is not null) a.AddRange(["-i", nuova]); + a.AddRange(["-map", "0:a:0"]); + if (nuova is not null) + a.AddRange(["-map", "1:0", "-frames:v", "1", "-c:v", est == ".flac" ? "png" : "mjpeg", "-disposition:v:0", "attached_pic", + "-metadata:s:v", "title=Album cover", "-metadata:s:v", "comment=Cover (front)"]); + else if (!togliCover && info.Copertina && tieneCover) + a.AddRange(["-map", "0:v:0", "-c:v", "copy", "-disposition:v:0", "attached_pic"]); else a.Add("-vn"); a.AddRange(["-map_metadata", "0", "-sn", "-dn"]); + Metadati.SulComando(a, scheda, est); var filtri = new List(); if (o.Normalizza) filtri.Add("loudnorm=I=-14:TP=-1:LRA=11"); diff --git a/src/DaPConvertitore.Motore/CartellaLavori.cs b/src/DaPConvertitore.Motore/CartellaLavori.cs new file mode 100644 index 0000000..16d2b55 --- /dev/null +++ b/src/DaPConvertitore.Motore/CartellaLavori.cs @@ -0,0 +1,48 @@ +namespace DaP.Convertitore; + +/// +/// Dove finisce quello che l'app produce da sé: screenshot, registrazioni, copertine salvate da lì. +/// Di partenza è Immagini\DaPConvertitore. Si crea all'avvio se manca, e all'installazione. +/// +public static class CartellaLavori +{ + public const string Nome = "DaPConvertitore"; + + /// Immagini\DaPConvertitore, anche se Pictures ha un altro nome nella lingua di Windows. + public static string DiSistema() + { + var foto = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures); + if (string.IsNullOrWhiteSpace(foto)) + foto = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Pictures"); + return Path.Combine(foto, Nome); + } + + /// La cartella scelta, o quella di sistema. La crea se non c'è. + public static string Percorso(string? scelta = null) + { + var p = string.IsNullOrWhiteSpace(scelta) ? DiSistema() : scelta.Trim(); + Directory.CreateDirectory(p); + return p; + } + + /// Quella ricordata nelle impostazioni. + public static string Assicura() => Percorso(Impostazioni.Comune.CartellaMia); + + public sealed record Voce(string Nome, long Peso, string Percorso); + + /// Gli ultimi file, i più nuovi prima. + public static IReadOnlyList Recenti(string? percorso = null, int quanti = 8) + { + var dir = percorso ?? Assicura(); + if (!Directory.Exists(dir)) return []; + try + { + return new DirectoryInfo(dir).EnumerateFiles() + .OrderByDescending(f => f.LastWriteTimeUtc) + .Take(quanti) + .Select(f => new Voce(f.Name, f.Length, f.FullName)) + .ToList(); + } + catch { return []; } + } +} diff --git a/src/DaPConvertitore.Motore/ComandiRegistrazione.cs b/src/DaPConvertitore.Motore/ComandiRegistrazione.cs new file mode 100644 index 0000000..caba524 --- /dev/null +++ b/src/DaPConvertitore.Motore/ComandiRegistrazione.cs @@ -0,0 +1,219 @@ +using System.Globalization; + +namespace DaP.Convertitore; + +/// +/// Il comando di FFmpeg della registrazione, e cosa deve fare «Registra» dal vassoio, dall'avatar o dal ponte. +/// Niente finestre: le prove lo chiamano così com'è. +/// Lo schermo è gdigrab: un monitor, una zona, oppure una finestra per titolo. Il microfono è DirectShow (audio=nome), +/// l'audio del PC è WASAPI in loopback. I tempi sono quelli dell'orologio, così video e audio restano +/// allineati anche quando una sorgente tace un attimo: è la stessa idea della registrazione di DaProd +/// Editor Video, che riempie di silenzio i buchi del loopback. I nomi dei dispositivi sono un argomento +/// solo, senza virgolette aggiunte: con ArgumentList non c'è una shell, e il parser di dshow (spezza su +/// «=» e «:», e non toglie le virgolette) le terrebbe come parte del nome. +/// +public static class ComandiRegistrazione +{ + public const string ApriMenu = "menu"; + public const string PortaBarra = "barra"; + + /// Da dove arriva «Registra»: il vassoio, il tasto destro dell'avatar, il comando del ponte. Stessa risposta. + public static readonly string[] Origini = ["vassoio", "avatar", "ponte"]; + + /// Il monitor da catturare, in pixel veri (come li vuole gdigrab). X e Y possono essere negativi. + public sealed record Schermo(int X, int Y, int Larghezza, int Altezza); + + /// Menu se non si sta registrando, barra se la registrazione è già partita. + public static string CosaFa(string origine, bool inCorso) + { + _ = origine; + return inCorso ? PortaBarra : ApriMenu; + } + + /// Solo audio senza ingressi, una zona non scelta o una finestra non scelta: non si parte. + public static string? MotivoRifiuto(string modo, string? mic, string? audioPc, bool zonaSenzaRettangolo = false, bool finestraSenzaTitolo = false) + { + if (modo == "audio" && string.IsNullOrWhiteSpace(mic) && string.IsNullOrWhiteSpace(audioPc)) + return "Per registrare solo l'audio serve il microfono o l'audio del PC."; + if (modo == "zona" && zonaSenzaRettangolo) return "Scegli la zona da registrare."; + if (modo == "finestra" && finestraSenzaTitolo) return "Scegli la finestra da registrare."; + return null; + } + + /// 30 oppure 60. Un numero in mezzo va a 30, uno alto a 60. + public static int FpsDi(int fps) => fps >= 45 ? 60 : 30; + + /// Alta, buona, leggera: il CRF di libx264. Il resto è «buona». + public static int CrfDi(string? qualita) => qualita switch + { + "alta" => 18, + "leggera" => 28, + _ => 23, + }; + + /// Un argomento solo: audio=Microphone (Realtek Audio), senza virgolette intorno. + public static string ArgomentoDshow(string nome) => "audio=" + Pulisci(nome); + + /// Il nome che WASAPI elenca, tale e quale, un argomento solo. + public static string ArgomentoWasapi(string nome) => Pulisci(nome); + + public static IReadOnlyList Argomenti(string modo, string? mic, string? audioPc, string uscita, Schermo? schermo, int fps = 30, int crf = 23, bool cursore = true, string? titoloFinestra = null) + { + var soloAudio = modo == "audio"; + var finestra = modo == "finestra" && !string.IsNullOrWhiteSpace(titoloFinestra); + var fotogrammi = FpsDi(fps); + var qualita = Math.Clamp(crf, 16, 32); + var a = new List { "-hide_banner", "-y" }; + if (!soloAudio) + { + Ingresso(a); + a.Add("-f"); a.Add("gdigrab"); + a.Add("-framerate"); a.Add(fotogrammi.ToString(CultureInfo.InvariantCulture)); + a.Add("-draw_mouse"); a.Add(cursore ? "1" : "0"); + // una finestra si prende per titolo: offset e misura non c'entrano (gdigrab segue quella finestra) + if (!finestra && schermo is { Larghezza: > 1, Altezza: > 1 }) + { + a.Add("-offset_x"); a.Add(schermo.X.ToString(CultureInfo.InvariantCulture)); + a.Add("-offset_y"); a.Add(schermo.Y.ToString(CultureInfo.InvariantCulture)); + a.Add("-video_size"); a.Add($"{Pari(schermo.Larghezza)}x{Pari(schermo.Altezza)}"); + } + a.Add("-i"); a.Add(finestra ? "title=" + Pulisci(titoloFinestra!) : "desktop"); + } + var micOk = !string.IsNullOrWhiteSpace(mic); + var pcOk = !string.IsNullOrWhiteSpace(audioPc); + if (micOk) + { + Ingresso(a); + a.Add("-f"); a.Add("dshow"); + a.Add("-i"); a.Add(ArgomentoDshow(mic!)); + } + if (pcOk) + { + Ingresso(a); + a.Add("-f"); a.Add("wasapi"); + a.Add("-loopback"); a.Add("1"); + a.Add("-i"); a.Add(ArgomentoWasapi(audioPc!)); + } + var nAudio = (micOk ? 1 : 0) + (pcOk ? 1 : 0); + if (!soloAudio) + { + // -vf e -filter_complex insieme FFmpeg li rifiuta: con due audio la scala sta nel filtro + if (nAudio == 2) + { + a.Add("-filter_complex"); + a.Add("[0:v]scale=trunc(iw/2)*2:trunc(ih/2)*2[v];[1:a][2:a]amix=inputs=2:duration=longest:dropout_transition=0[a]"); + a.Add("-map"); a.Add("[v]"); + a.Add("-map"); a.Add("[a]"); + } + else + { + a.Add("-vf"); a.Add("scale=trunc(iw/2)*2:trunc(ih/2)*2"); + if (nAudio == 1) + { + a.Add("-map"); a.Add("0:v"); + a.Add("-map"); a.Add("1:a"); + } + } + a.Add("-c:v"); a.Add("libx264"); + a.Add("-preset"); a.Add("veryfast"); + a.Add("-crf"); a.Add(qualita.ToString(CultureInfo.InvariantCulture)); + a.Add("-pix_fmt"); a.Add("yuv420p"); + if (nAudio > 0) { a.Add("-c:a"); a.Add("aac"); a.Add("-b:a"); a.Add("160k"); } + } + else + { + if (nAudio == 2) + { + a.Add("-filter_complex"); + a.Add("[0:a][1:a]amix=inputs=2:duration=longest:dropout_transition=0[a]"); + a.Add("-map"); a.Add("[a]"); + } + a.Add("-c:a"); a.Add("aac"); + a.Add("-b:a"); a.Add("192k"); + } + a.Add(uscita); + return a; + } + + /// La riga che finisce nel registro. Gli argomenti con spazi prendono le virgolette solo qui, per leggerli. + public static string Riga(IEnumerable argomenti) => + string.Join(' ', argomenti.Select(x => x.Any(char.IsWhiteSpace) ? "\"" + x.Replace("\"", "\\\"") + "\"" : x)); + + /// I microfoni dall'elenco di ffmpeg -f dshow -list_devices true (esce su stderr). + public static IReadOnlyList MicrofoniDaElenco(string testo) + { + var audio = false; + var nomi = new List(); + foreach (var riga in testo.Split('\n')) + { + if (riga.Contains("DirectShow audio", StringComparison.OrdinalIgnoreCase)) { audio = true; continue; } + if (riga.Contains("DirectShow video", StringComparison.OrdinalIgnoreCase)) { audio = false; continue; } + if (!audio || riga.Contains("Alternative name", StringComparison.OrdinalIgnoreCase)) continue; + if (NomeFraVirgolette(riga) is { } n && !nomi.Contains(n)) nomi.Add(n); + } + return nomi; + } + + /// Le uscite del PC (playback) dall'elenco WASAPI. I microfoni, segnati capture, non ci vanno. + public static IReadOnlyList UsciteDaElenco(string testo) + { + var tutti = new List(); + var playback = new List(); + foreach (var riga in testo.Split('\n')) + { + if (riga.Contains("(capture)", StringComparison.OrdinalIgnoreCase)) continue; + if (NomeFraVirgolette(riga) is not { } n) continue; + if (!tutti.Contains(n)) tutti.Add(n); + if (riga.Contains("playback", StringComparison.OrdinalIgnoreCase) && !playback.Contains(n)) playback.Add(n); + } + return playback.Count > 0 ? playback : tutti; + } + + static void Ingresso(List a) + { + a.Add("-thread_queue_size"); a.Add("1024"); + a.Add("-use_wallclock_as_timestamps"); a.Add("1"); + } + + /// libx264 con yuv420p vuole larghezza e altezza pari. 1921 diventa 1920. + public static int Pari(int n) => Math.Max(2, n - (n & 1)); + + /// I titoli da proporre per «una finestra». Si saltano quelli vuoti e le finestre nostre di registrazione. + public static IReadOnlyList TitoliUtili(IEnumerable titoli) + { + var visti = new HashSet(StringComparer.OrdinalIgnoreCase); + var lista = new List(); + foreach (var t in titoli) + { + var n = t.Trim(); + if (n.Length < 2) continue; + if (n.Equals("Registra", StringComparison.OrdinalIgnoreCase) || n.Equals("Registrazione", StringComparison.OrdinalIgnoreCase)) continue; + if (n.Equals("Program Manager", StringComparison.OrdinalIgnoreCase)) continue; + if (visti.Add(n)) lista.Add(n); + } + return lista; + } + + /// Un fotogramma piccolo, per la miniatura nei recenti. Esce su stdout in PNG. + public static IReadOnlyList ArgomentiFotogramma(string percorso) => + [ + "-hide_banner", "-loglevel", "error", "-ss", "0.4", "-i", percorso, + "-frames:v", "1", "-vf", "scale=160:-2", "-f", "image2pipe", "-vcodec", "png", "-", + ]; + + static string Pulisci(string nome) + { + var n = nome.Trim(); + if (n.Length >= 2 && n[0] == '"' && n[^1] == '"') n = n[1..^1].Trim(); + return n.Replace("\"", ""); + } + + static string? NomeFraVirgolette(string riga) + { + var a = riga.IndexOf('"'); + var b = a >= 0 ? riga.IndexOf('"', a + 1) : -1; + if (a < 0 || b <= a) return null; + var n = riga[(a + 1)..b].Trim(); + return n.Length == 0 ? null : n; + } +} diff --git a/src/DaPConvertitore.Motore/Immagini.cs b/src/DaPConvertitore.Motore/Immagini.cs index bee8090..a2cb97f 100644 --- a/src/DaPConvertitore.Motore/Immagini.cs +++ b/src/DaPConvertitore.Motore/Immagini.cs @@ -5,6 +5,9 @@ namespace DaP.Convertitore; +/// Autore, descrizione e data letti da una foto. +public sealed record TestiFoto(string? Autore, string? Descrizione, DateTimeOffset? Data); + /// /// Le immagini passano da WIC, il motore di Windows: legge HEIC, RAW delle fotocamere, WEBP, AVIF con le estensioni /// di Windows, e gira la foto come la vede il telefono (orientamento EXIF). Quello che WIC non legge (TGA, EXR, PSD, @@ -22,6 +25,8 @@ public static async Task Converti(Lavoro l, Contesto ctx) var foto = await Apri(l.Sorgente, ctx, (uint)Math.Max(0, o.Lato)); ctx.Fase("Scrivo", 0.5); await Scrivi(foto, est, l.Bozza, o, ctx); + if (l.Opzioni.Scheda is { Scrivi: true } sc && Metadati.FotoTiene(est)) + await ApplicaScheda(l.Bozza, sc); } /// Apre un'immagine qualsiasi in BGRA, già girata per il verso giusto e, se serve, rimpicciolita. @@ -290,6 +295,76 @@ static async Task Quadrata(SoftwareBitmap foto, int lato) return SoftwareBitmap.CreateCopyFromBuffer(dest.AsBuffer(), BitmapPixelFormat.Bgra8, lato, lato, BitmapAlphaMode.Straight); } + /// Autore, descrizione e data dello scatto, come li tiene il file (JPG e TIFF). + public static async Task LeggiTesti(string percorso) + { + var file = await StorageFile.GetFileFromPathAsync(Path.GetFullPath(percorso)); + string[] chiavi = ["System.Author", "System.Title", "System.Comment", "System.Subject", "System.Photo.DateTaken"]; + var props = await file.Properties.RetrievePropertiesAsync(chiavi); + static string? Testo(object? v) => v switch + { + null => null, + string s => string.IsNullOrWhiteSpace(s) ? null : s.Trim(), + string[] a => string.Join(", ", a.Where(x => !string.IsNullOrWhiteSpace(x))), + IEnumerable e => string.Join(", ", e.Where(x => !string.IsNullOrWhiteSpace(x))), + _ => v.ToString(), + }; + string? Di(string k) => props.TryGetValue(k, out var v) ? Testo(v) : null; + DateTimeOffset? data = props.TryGetValue("System.Photo.DateTaken", out var d) && d is DateTimeOffset dto ? dto : null; + var descrizione = Di("System.Subject") ?? Di("System.Title") ?? Di("System.Comment"); + var autore = Di("System.Author"); + if (string.IsNullOrWhiteSpace(autore)) autore = null; + if (string.IsNullOrWhiteSpace(descrizione)) descrizione = null; + return new TestiFoto(autore, descrizione, data); + } + + /// + /// Scrive autore, descrizione e data sulla foto già scritta, senza ricodificarla (la stessa trascrizione della rotazione). + /// Se l'elenco dell'autore non passa, si riprova senza: il resto resta. + /// + public static async Task ApplicaScheda(string percorso, OpzioniScheda s) + { + var set = new BitmapPropertySet(); + if (s.Descrizione is not null) + { + set.Add("System.Title", new BitmapTypedValue(s.Descrizione, Windows.Foundation.PropertyType.String)); + set.Add("System.Comment", new BitmapTypedValue(s.Descrizione, Windows.Foundation.PropertyType.String)); + } + if (!string.IsNullOrWhiteSpace(s.Autore)) + set.Add("System.Author", new BitmapTypedValue(new[] { s.Autore }, Windows.Foundation.PropertyType.StringArray)); + if (Metadati.DataDi(s.DataScatto) is { } data) + set.Add("System.Photo.DateTaken", new BitmapTypedValue(data, Windows.Foundation.PropertyType.DateTime)); + if (set.Count == 0) return; + + var bytes = await File.ReadAllBytesAsync(percorso); + async Task Trascrivi(BitmapPropertySet proprieta) + { + using var dentro = new InMemoryRandomAccessStream(); + await dentro.WriteAsync(bytes.AsBuffer()); + dentro.Seek(0); + var dec = await BitmapDecoder.CreateAsync(dentro); + using var mem = new InMemoryRandomAccessStream(); + var enc = await BitmapEncoder.CreateForTranscodingAsync(mem, dec); + await enc.BitmapProperties.SetPropertiesAsync(proprieta); + await enc.FlushAsync(); + var dati = new byte[mem.Size]; + mem.Seek(0); + await mem.ReadAsync(dati.AsBuffer(), (uint)dati.Length, InputStreamOptions.None); + return dati; + } + + byte[] uscita; + try { uscita = await Trascrivi(set); } + catch (Exception e) + { + Registro.Scrivi($"scheda foto, riprovo senza autore ({e.Message})"); + set.Remove("System.Author"); + if (set.Count == 0) throw new ErroreConversione("Queste info non si scrivono su questa foto.", e.Message); + uscita = await Trascrivi(set); + } + await File.WriteAllBytesAsync(percorso, uscita); + } + /// Le misure di un'immagine, già girate, senza decodificarla tutta. public static async Task<(int w, int h)?> Misure(string percorso) { diff --git a/src/DaPConvertitore.Motore/Impostazioni.cs b/src/DaPConvertitore.Motore/Impostazioni.cs index cfe0cb2..8082235 100644 --- a/src/DaPConvertitore.Motore/Impostazioni.cs +++ b/src/DaPConvertitore.Motore/Impostazioni.cs @@ -44,6 +44,32 @@ public sealed class Impostazioni public string? NovitaVista { get; set; } /// L'invito a mettere il convertitore nel menu di Windows 11 è già stato mostrato (e chiuso). public bool Menu11Chiesto { get; set; } + /// Con cosa codificare i video: "gpu" o "cpu". Vuoto = la scheda video se c'è, se no il processore. + public string? CodificaCon { get; set; } + /// Dove finiscono screenshot, registrazioni e il resto che fa l'app. Vuoto = Immagini\DaPConvertitore. + public string? CartellaMia { get; set; } + /// La scorciatoia globale dello screenshot. Vuota = Ctrl+Maiusc+S. + public string? ScorciatoiaSchermo { get; set; } + /// Microfono della registrazione. Vuoto = non usarlo. Null = il primo che trova. + public string? RegistrazioneMic { get; set; } + /// Uscita del PC (l'audio che senti) da registrare in loopback. Vuoto = non usarla. Null = la prima. + public string? RegistrazionePc { get; set; } + /// Il monitor da registrare, come «x,y,larghezza,altezza» in pixel veri. Vuoto = il principale. + public string? RegistrazioneMonitor { get; set; } + /// intero, zona o finestra. Vuoto = lo schermo intero. + public string? RegistrazioneArea { get; set; } + /// La zona scelta, negli stessi pixel del monitor. Vale se l'area è «zona». + public string? RegistrazioneZona { get; set; } + /// Il titolo della finestra da registrare, se l'area è «finestra». + public string? RegistrazioneFinestra { get; set; } + /// 30 o 60. Vuoto = 30. + public int? RegistrazioneFps { get; set; } + /// leggera, buona o alta. Vuoto = buona. + public string? RegistrazioneQualita { get; set; } + /// Il cursore del mouse entra nel video. Di partenza sì. + public bool RegistrazioneCursore { get; set; } = true; + /// Tre secondi di conto alla rovescia prima di partire. Di partenza sì. + public bool RegistrazioneConto { get; set; } = true; /// L'ultimo formato scelto per ogni categoria ("video" → "video.mp4"). public Dictionary Formati { get; set; } = []; /// Le ultime scelte dell'interfaccia (codec, qualità, motore…), tali e quali. diff --git a/src/DaPConvertitore.Motore/Lettore/Copertine.cs b/src/DaPConvertitore.Motore/Lettore/Copertine.cs new file mode 100644 index 0000000..0c04c55 --- /dev/null +++ b/src/DaPConvertitore.Motore/Lettore/Copertine.cs @@ -0,0 +1,598 @@ +using System.Globalization; +using System.IO.Compression; +using System.Text; + +namespace DaP.Convertitore.Lettore; + +/// Quello che torna dopo aver messo una copertina: i byte da mostrare, dove è finita accanto, se è entrata nel file. +public sealed record EsitoCopertina(byte[]? Immagine, string? Accanto, bool Dentro, string? Nota) +{ + /// Per la pagina: JPEG o PNG, si capisce dai primi byte. + public string? ComeDataUrl() + { + if (Immagine is not { Length: > 8 }) return null; + var png = Immagine[0] == 137 && Immagine[1] == 80; + return "data:" + (png ? "image/png" : "image/jpeg") + ";base64," + Convert.ToBase64String(Immagine); + } +} + +/// +/// La copertina di un brano. Si salva accanto al file (mai sopra un file che c'è già) e, per MP3, M4A e FLAC, +/// si scrive dentro: una bozza accanto, poi prende il posto dell'originale. Se qualcosa va storto l'originale resta. +/// Le varianti disegnate sono sempre le stesse per lo stesso titolo: l'anteprima e il file usano lo stesso disegno. +/// +public static class Copertine +{ + public const int Lato = 480; + public const int Quante = 6; + + static readonly Dictionary glifi = new() + { + ['A'] = G("01110", "10001", "10001", "11111", "10001", "10001", "10001"), + ['B'] = G("11110", "10001", "10001", "11110", "10001", "10001", "11110"), + ['C'] = G("01111", "10000", "10000", "10000", "10000", "10000", "01111"), + ['D'] = G("11110", "10001", "10001", "10001", "10001", "10001", "11110"), + ['E'] = G("11111", "10000", "10000", "11110", "10000", "10000", "11111"), + ['F'] = G("11111", "10000", "10000", "11110", "10000", "10000", "10000"), + ['G'] = G("01111", "10000", "10000", "10011", "10001", "10001", "01111"), + ['H'] = G("10001", "10001", "10001", "11111", "10001", "10001", "10001"), + ['I'] = G("11111", "00100", "00100", "00100", "00100", "00100", "11111"), + ['J'] = G("00111", "00010", "00010", "00010", "10010", "10010", "01100"), + ['K'] = G("10001", "10010", "10100", "11000", "10100", "10010", "10001"), + ['L'] = G("10000", "10000", "10000", "10000", "10000", "10000", "11111"), + ['M'] = G("10001", "11011", "10101", "10101", "10001", "10001", "10001"), + ['N'] = G("10001", "11001", "10101", "10011", "10001", "10001", "10001"), + ['O'] = G("01110", "10001", "10001", "10001", "10001", "10001", "01110"), + ['P'] = G("11110", "10001", "10001", "11110", "10000", "10000", "10000"), + ['Q'] = G("01110", "10001", "10001", "10001", "10101", "10010", "01101"), + ['R'] = G("11110", "10001", "10001", "11110", "10100", "10010", "10001"), + ['S'] = G("01111", "10000", "10000", "01110", "00001", "00001", "11110"), + ['T'] = G("11111", "00100", "00100", "00100", "00100", "00100", "00100"), + ['U'] = G("10001", "10001", "10001", "10001", "10001", "10001", "01110"), + ['V'] = G("10001", "10001", "10001", "10001", "10001", "01010", "00100"), + ['W'] = G("10001", "10001", "10001", "10101", "10101", "10101", "01010"), + ['X'] = G("10001", "10001", "01010", "00100", "01010", "10001", "10001"), + ['Y'] = G("10001", "10001", "01010", "00100", "00100", "00100", "00100"), + ['Z'] = G("11111", "00001", "00010", "00100", "01000", "10000", "11111"), + ['0'] = G("01110", "10001", "10011", "10101", "11001", "10001", "01110"), + ['1'] = G("00100", "01100", "00100", "00100", "00100", "00100", "01110"), + ['2'] = G("01110", "10001", "00001", "00010", "00100", "01000", "11111"), + ['3'] = G("11110", "00001", "00001", "01110", "00001", "00001", "11110"), + ['4'] = G("10010", "10010", "10010", "11111", "00010", "00010", "00010"), + ['5'] = G("11111", "10000", "10000", "11110", "00001", "00001", "11110"), + ['6'] = G("01110", "10000", "10000", "11110", "10001", "10001", "01110"), + ['7'] = G("11111", "00001", "00010", "00100", "01000", "01000", "01000"), + ['8'] = G("01110", "10001", "10001", "01110", "10001", "10001", "01110"), + ['9'] = G("01110", "10001", "10001", "01111", "00001", "00001", "01110"), + }; + + static Copertine() + { + foreach (var (k, v) in glifi) + if (v.Length != 35) throw new InvalidOperationException($"Glifo {k} lungo {v.Length}."); + } + + static string G(params string[] righe) => string.Concat(righe); + + static string Est(string percorso) => Path.GetExtension(percorso).ToLowerInvariant(); + + /// MP3, M4A e FLAC tengono la copertina dentro, come un video MP4, MOV o MKV (attached_pic). + public static bool AudioNelFile(string percorso) => Est(percorso) is ".mp3" or ".m4a" or ".flac"; + + /// MP4, MOV e MKV: la copertina è un fotogramma allegato, quello che Esplora file e i lettori usano come miniatura. + public static bool VideoNelFile(string percorso) => Est(percorso) is ".mp4" or ".m4v" or ".mov" or ".mkv"; + + public static bool DentroIlFile(string percorso) => AudioNelFile(percorso) || VideoNelFile(percorso); + + /// «Brano (copertina).jpg», poi «(copertina 2)», «(copertina 3)»… non si scrive mai sopra un file che c'è già. + public static string NomeLibero(string cartella, string radice, string estensione) + { + if (!estensione.StartsWith('.')) estensione = "." + estensione; + var base_ = string.IsNullOrWhiteSpace(radice) ? "copertina" : radice.Trim(); + for (var n = 1; ; n++) + { + var etichetta = n == 1 ? "copertina" : $"copertina {n}"; + var candidato = Path.Combine(cartella, $"{base_} ({etichetta}){estensione}"); + if (!File.Exists(candidato) && !Directory.Exists(candidato)) return candidato; + } + } + + /// Tira fuori la copertina e la mette nella cartella del brano. + public static async Task SalvaAccanto(Strumenti s, string audio) + { + var jpg = await Media.Copertina(s, audio, true) ?? throw new ErroreConversione("Questo brano non ha una copertina."); + var dest = NomeLibero(Path.GetDirectoryName(Path.GetFullPath(audio))!, Nomi.Radice(audio), ".jpg"); + await File.WriteAllBytesAsync(dest, jpg); + return dest; + } + + /// + /// Mette l'immagine dentro il brano. Si scrive una bozza accanto e solo alla fine prende il posto del file: + /// se FFmpeg si ferma, l'originale resta com'era. + /// + public static async Task ScriviNelFile(Strumenti s, string audio, string immagine, CancellationToken ct = default) + { + if (!DentroIlFile(audio)) throw new ErroreConversione("Questo formato non tiene la copertina dentro il file."); + if (!File.Exists(immagine)) throw new ErroreConversione("L'immagine non c'è."); + if (VideoNelFile(audio)) { await ScriviNelVideo(s, audio, immagine, ct); return; } + var est = Est(audio); + var bozza = Nomi.Bozza(audio); + try + { + var a = new List + { + "-hide_banner", "-loglevel", "error", "-y", "-i", audio, "-i", immagine, + "-map", "0:a:0", "-map", "1:0", "-frames:v", "1", "-c:a", "copy", + "-c:v", est == ".flac" ? "png" : "mjpeg", + "-disposition:v:0", "attached_pic", + "-metadata:s:v", "title=Album cover", "-metadata:s:v", "comment=Cover (front)", + "-map_metadata", "0", + }; + if (est == ".mp3") a.AddRange(["-id3v2_version", "3"]); + a.AddRange(["-f", Ffmpeg.Muxer(est), bozza]); + var r = await Processi.Esegui(s.Ffmpeg, a, ct, tieniUscita: false); + if (r.Codice != 0 || !File.Exists(bozza) || new FileInfo(bozza).Length == 0) + throw new ErroreConversione("Non sono riuscito a mettere la copertina.", r.Errori); + var creato = File.GetCreationTime(audio); + Modifiche.Sposta(bozza, audio); + try { File.SetCreationTime(audio, creato); } catch { /* la data di creazione non è il punto */ } + } + finally { try { if (File.Exists(bozza)) File.Delete(bozza); } catch { } } + } + + /// + /// La copertina di un video: un fotogramma allegato (attached_pic), copiando il film così com'è. + /// Esplora file e i lettori la usano come miniatura. La bozza prende il posto del file solo alla fine. + /// + static async Task ScriviNelVideo(Strumenti s, string video, string immagine, CancellationToken ct) + { + var info = await Sonda.Leggi(s, video, ct); + if (info.Video is null || info.VideoVeri < 1) throw new ErroreConversione("In questo file non c'è un video."); + var veri = info.VideoVeri; + var est = Est(video); + var bozza = Nomi.Bozza(video); + try + { + var a = new List + { + "-hide_banner", "-loglevel", "error", "-y", "-i", video, "-i", immagine, + "-map", "0:V", "-map", "1:0", + }; + if (info.Audio.Count > 0) a.AddRange(["-map", "0:a?"]); + if (info.Sottotitoli.Count > 0) a.AddRange(["-map", "0:s?"]); + // niente «-frames» sul video copiato: con +faststart FFmpeg 6 si teneva solo la copertina e perdeva il film + for (var i = 0; i < veri; i++) a.AddRange(["-c:v:" + i, "copy", "-disposition:v:" + i, "default"]); + a.AddRange(["-c:v:" + veri, "mjpeg", "-disposition:v:" + veri, "attached_pic"]); + a.AddRange(["-metadata:s:v:" + veri, "title=Cover", "-metadata:s:v:" + veri, "comment=Cover (front)"]); + if (info.Audio.Count > 0) a.AddRange(["-c:a", "copy"]); + if (info.Sottotitoli.Count > 0) a.AddRange(["-c:s", "copy"]); + a.AddRange(["-map_metadata", "0", "-map_chapters", "0"]); + if (est is ".mp4" or ".m4v" or ".mov") a.AddRange(["-movflags", "+faststart"]); + a.AddRange(["-f", est == ".mkv" ? "matroska" : est == ".mov" ? "mov" : "mp4", bozza]); + var r = await Processi.Esegui(s.Ffmpeg, a, ct, tieniUscita: false); + if (r.Codice != 0 || !File.Exists(bozza) || new FileInfo(bozza).Length == 0) + throw new ErroreConversione("Non sono riuscito a mettere la copertina nel video.", r.Errori); + var creato = File.GetCreationTime(video); + Modifiche.Sposta(bozza, video); + try { File.SetCreationTime(video, creato); } catch { /* la data non è il punto */ } + } + finally { try { if (File.Exists(bozza)) File.Delete(bozza); } catch { } } + } + + /// Il fotogramma allegato, se c'è. È la miniatura, non un fotogramma a caso del film. + public static async Task EstraiAllegata(Strumenti s, string percorso, int indice, int lato = 480, bool silenzioso = false) + { + if (indice < 0) return null; + var jpg = Path.Combine(Strumenti.CartellaTemporanea, $"allegata-{Guid.NewGuid():N}.jpg"); + try + { + var scala = $"scale='min({Math.Clamp(lato, 32, 800)},iw)':-2"; + var r = await Processi.Esegui(s.Ffmpeg, ["-hide_banner", "-loglevel", "error", "-y", "-i", percorso, + "-map", "0:" + indice, "-frames:v", "1", "-vf", scala, "-q:v", "3", "-update", "1", jpg], + CancellationToken.None, tieniUscita: false, silenzioso: silenzioso); + if (r.Codice == 0 && File.Exists(jpg)) return await File.ReadAllBytesAsync(jpg); + return null; + } + finally { try { File.Delete(jpg); } catch { } } + } + + /// Guarda se il file ha una copertina allegata e, se sì, la tira fuori. + public static async Task ProvaAllegata(Strumenti s, string percorso, int lato = 480, bool silenzioso = true) + { + try + { + var info = await Sonda.Leggi(s, percorso, silenzioso: silenzioso); + if (info.IndiceCopertina < 0) return null; + return await EstraiAllegata(s, percorso, info.IndiceCopertina, lato, silenzioso); + } + catch { return null; } + } + + /// Mette l'immagine nel file se il formato la tiene, se no la salva accanto e lo dice. + public static async Task Applica(Strumenti s, string audio, string immagine, CancellationToken ct = default) + { + if (DentroIlFile(audio)) + { + await ScriviNelFile(s, audio, immagine, ct); + var jpg = await Media.Copertina(s, audio, true, silenzioso: true); + return new EsitoCopertina(jpg, null, true, "Copertina messa nel file."); + } + var bytes = await File.ReadAllBytesAsync(immagine, ct); + var est = EstensioneImmagine(immagine); + var dove = NomeLibero(Path.GetDirectoryName(Path.GetFullPath(audio))!, Nomi.Radice(audio), est); + await File.WriteAllBytesAsync(dove, bytes, ct); + var formato = Est(audio).TrimStart('.').ToUpperInvariant(); + return new EsitoCopertina(bytes, dove, false, $"{formato} non tiene la copertina dentro. L'ho salvata accanto."); + } + + /// Una delle copertine disegnate, scritta nel file (o accanto, se il formato non la tiene). + public static async Task ApplicaGenerata(Strumenti s, string audio, string titolo, int variante, CancellationToken ct = default) + { + var png = Genera(string.IsNullOrWhiteSpace(titolo) ? Nomi.Radice(audio) : titolo, variante, null); + var tmp = Path.Combine(Strumenti.CartellaTemporanea, $"copertina-{Guid.NewGuid():N}.png"); + await File.WriteAllBytesAsync(tmp, png, ct); + try { return await Applica(s, audio, tmp, ct); } + finally { try { File.Delete(tmp); } catch { } } + } + + /// Un disegno quadrato, sempre uguale per lo stesso titolo e la stessa variante. PNG. + public static byte[] Genera(string titolo, int variante, float[]? onda) + { + variante = ((variante % Quante) + Quante) % Quante; + var w = Lato; + var px = new byte[w * w * 4]; + var seme = Seme(titolo, variante); + switch (variante) + { + case 0: Disco(px, w, seme); break; + case 1: Onda(px, w, seme, onda); break; + case 2: Cassetta(px, w); break; + case 3: Notte(px, w, seme, titolo); break; + case 4: Cornice(px, w, seme); break; + default: Anelli(px, w, seme, titolo); break; + } + Vignetta(px, w); + ScriviTitolo(px, w, string.IsNullOrWhiteSpace(titolo) ? "DAPROD" : titolo); + return Png(px, w, w); + } + + static int Seme(string titolo, int variante) + { + var h = variante * 9973 + 17; + foreach (var c in titolo) h = unchecked(h * 33 + c); + return h & 0x7fffffff; + } + + static void Disco(byte[] px, int w, int seme) + { + Riempi(px, w, 18, 12, 32); + var c = w / 2; + var rng = new Random(seme); + for (var i = 0; i < 18; i++) + { + var x = rng.Next(w); + var y = rng.Next(w / 2); + Cerchio(px, w, x, y, rng.Next(2, 5), 255, 213, 74); + } + Cerchio(px, w, c, c - 10, 168, 255, 213, 74); + Cerchio(px, w, c, c - 10, 150, 90, 40, 120); + Cerchio(px, w, c, c - 10, 118, 255, 61, 242); + Cerchio(px, w, c, c - 10, 46, 20, 14, 28); + Cerchio(px, w, c, c - 10, 14, 255, 243, 196); + } + + static void Onda(byte[] px, int w, int seme, float[]? onda) + { + Gradiente(px, w, (12, 10, 22), (48, 16, 72), true); + var n = 48; + var picchi = new float[n]; + if (onda is { Length: > 4 }) + { + for (var i = 0; i < n; i++) picchi[i] = onda[Math.Clamp((int)((long)i * onda.Length / n), 0, onda.Length - 1)]; + } + else + { + var rng = new Random(seme); + for (var i = 0; i < n; i++) + { + var t = i / (float)(n - 1); + picchi[i] = (float)(0.22 + 0.72 * Math.Abs(Math.Sin(t * 8.5 + seme * 0.01)) * (0.55 + 0.45 * rng.NextDouble())); + } + } + var passo = (w - 64) / (double)n; + var base_ = (int)(w * 0.72); + var altoMax = (int)(w * 0.46); + for (var i = 0; i < n; i++) + { + var alto = Math.Max(8, (int)(picchi[i] * altoMax)); + var x = 32 + (int)(i * passo); + var t = i / (double)(n - 1); + Rett(px, w, x, base_ - alto, Math.Max(3, (int)passo - 3), alto, (byte)(93 + t * 160), (byte)(255 - t * 180), (byte)(180 + t * 60)); + } + } + + static void Cassetta(byte[] px, int w) + { + Riempi(px, w, 22, 14, 40); + Rett(px, w, 36, 70, w - 72, w - 150, 28, 18, 48); + Rett(px, w, 48, 86, w - 96, 150, 255, 213, 74); + Rett(px, w, 60, 100, w - 120, 122, 18, 12, 28); + Cerchio(px, w, w / 2 - 78, 250, 52, 40, 24, 64); + Cerchio(px, w, w / 2 + 78, 250, 52, 40, 24, 64); + Cerchio(px, w, w / 2 - 78, 250, 16, 255, 61, 242); + Cerchio(px, w, w / 2 + 78, 250, 16, 255, 61, 242); + Rett(px, w, 70, 300, w - 140, 8, 255, 213, 74); + } + + static void Notte(byte[] px, int w, int seme, string titolo) + { + Gradiente(px, w, (8, 6, 16), (78, 20, 110), false); + var rng = new Random(seme); + for (var i = 0; i < 70; i++) + { + var x = rng.Next(w); + var y = rng.Next((int)(w * 0.7)); + var r = rng.Next(1, 3); + var caldo = rng.Next(2) == 0; + Cerchio(px, w, x, y, r, caldo ? (byte)255 : (byte)255, caldo ? (byte)213 : (byte)255, caldo ? (byte)74 : (byte)255); + } + var lettera = PrimaLettera(titolo, seme); + ScriviTesto(px, w, lettera.ToString(), w / 2 - 28, (int)(w * 0.28), 8, 255, 213, 74); + } + + static void Cornice(byte[] px, int w, int seme) + { + Riempi(px, w, 14, 10, 24); + for (var i = 0; i < w; i += 18) + { + var oro = ((i / 18) + seme) % 2 == 0; + Rett(px, w, i, 0, 9, w, oro ? (byte)255 : (byte)255, oro ? (byte)213 : (byte)61, oro ? (byte)74 : (byte)242); + } + Rett(px, w, 28, 28, w - 56, w - 56, 16, 12, 28); + Rett(px, w, 40, 40, w - 80, w - 80, 32, 18, 58); + } + + static void Anelli(byte[] px, int w, int seme, string titolo) + { + Riempi(px, w, 20, 12, 36); + var c = w / 2; + var raggi = new[] { 200, 164, 128, 92, 56 }; + for (var i = 0; i < raggi.Length; i++) + { + var oro = (i + seme) % 2 == 0; + Anello(px, w, c, c - 16, raggi[i], raggi[i] - 16, oro ? (byte)255 : (byte)255, oro ? (byte)213 : (byte)61, oro ? (byte)74 : (byte)242); + } + var lettere = Iniziali(titolo, seme); + var scala = lettere.Length > 1 ? 5 : 7; + var largo = lettere.Length * 6 * scala; + ScriviTesto(px, w, lettere, c - largo / 2, c - 16 - 4 * scala, scala, 255, 251, 224); + } + + static char PrimaLettera(string titolo, int seme) + { + foreach (var c in titolo) + { + var b = Base(c); + if (glifi.ContainsKey(b) && char.IsLetter(b)) return b; + } + const string alfabeto = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + return alfabeto[Math.Abs(seme) % alfabeto.Length]; + } + + static string Iniziali(string titolo, int seme) + { + var viste = new List(); + var parola = true; + foreach (var c in titolo) + { + var b = Base(c); + if (!char.IsLetter(b)) { parola = true; continue; } + if (parola && glifi.ContainsKey(b)) { viste.Add(b); parola = false; if (viste.Count == 2) break; } + } + if (viste.Count == 0) return PrimaLettera(titolo, seme).ToString(); + return new string(viste.ToArray()); + } + + static void Vignetta(byte[] p, int w) + { + var c = (w - 1) / 2.0; + for (var y = 0; y < w; y++) + for (var x = 0; x < w; x++) + { + var dx = (x - c) / c; + var dy = (y - c) / c; + var d = Math.Sqrt(dx * dx + dy * dy); + if (d < 0.78) continue; + var k = Math.Clamp((d - 0.78) / 0.5, 0, 0.62); + var i = (y * w + x) * 4; + p[i] = (byte)(p[i] * (1 - k)); + p[i + 1] = (byte)(p[i + 1] * (1 - k)); + p[i + 2] = (byte)(p[i + 2] * (1 - k)); + } + } + + static void ScriviTitolo(byte[] px, int w, string titolo) + { + var righe = Spezza(titolo, 16); + var scala = 3; + var y = w - 28 - righe.Count * (8 * scala); + foreach (var riga in righe) + { + var largo = riga.Length * 6 * scala; + ScriviTesto(px, w, riga, Math.Max(8, (w - largo) / 2), y, scala, 255, 243, 196); + y += 8 * scala; + } + } + + static List Spezza(string titolo, int max) + { + var pulito = new string(titolo.Select(c => + { + var b = Base(c); + return char.IsLetterOrDigit(b) || b == ' ' ? b : ' '; + }).ToArray()); + while (pulito.Contains(" ", StringComparison.Ordinal)) pulito = pulito.Replace(" ", " ", StringComparison.Ordinal); + pulito = pulito.Trim(); + if (pulito.Length == 0) return ["DAPROD"]; + if (pulito.Length <= max) return [pulito]; + var righe = new List(); + var riga = ""; + foreach (var parola in pulito.Split(' ')) + { + var pezzo = parola.Length > max ? parola[..max] : parola; + if (riga.Length == 0) riga = pezzo; + else if (riga.Length + 1 + pezzo.Length <= max) riga += " " + pezzo; + else + { + righe.Add(riga); + riga = pezzo; + if (righe.Count == 2) return righe; + } + } + if (riga.Length > 0 && righe.Count < 2) righe.Add(riga); + return righe; + } + + static char Base(char c) + { + if (c == ' ') return ' '; + var s = c.ToString().Normalize(NormalizationForm.FormD); + var b = s.FirstOrDefault(ch => CharUnicodeInfo.GetUnicodeCategory(ch) != UnicodeCategory.NonSpacingMark); + return char.ToUpperInvariant(b == 0 ? c : b); + } + + static void ScriviTesto(byte[] px, int w, string testo, int x, int y, int scala, byte r, byte g, byte b) + { + var dx = x; + foreach (var ch in testo) + { + if (ch == ' ' || !glifi.TryGetValue(ch, out var glyph)) { dx += 4 * scala; continue; } + for (var row = 0; row < 7; row++) + for (var col = 0; col < 5; col++) + if (glyph[row * 5 + col] == '1') + Rett(px, w, dx + col * scala, y + row * scala, scala, scala, r, g, b); + dx += 6 * scala; + } + } + + static void Riempi(byte[] p, int w, byte r, byte g, byte b) + { + for (var i = 0; i < p.Length; i += 4) { p[i] = r; p[i + 1] = g; p[i + 2] = b; p[i + 3] = 255; } + } + + static void Gradiente(byte[] p, int w, (byte R, byte G, byte B) a, (byte R, byte G, byte B) b, bool diagonale) + { + for (var y = 0; y < w; y++) + for (var x = 0; x < w; x++) + { + var t = diagonale ? (x + y) / (2.0 * (w - 1)) : y / (double)(w - 1); + Px(p, w, x, y, Mix(a.R, b.R, t), Mix(a.G, b.G, t), Mix(a.B, b.B, t)); + } + } + + static byte Mix(byte a, byte b, double t) => (byte)(a + (b - a) * t); + + static void Rett(byte[] p, int w, int x, int y, int rw, int rh, byte r, byte g, byte b) + { + for (var yy = y; yy < y + rh; yy++) + for (var xx = x; xx < x + rw; xx++) + Px(p, w, xx, yy, r, g, b); + } + + static void Cerchio(byte[] p, int w, int cx, int cy, int raggio, byte r, byte g, byte b) + { + var r2 = raggio * raggio; + for (var y = cy - raggio; y <= cy + raggio; y++) + for (var x = cx - raggio; x <= cx + raggio; x++) + { + var dx = x - cx; + var dy = y - cy; + if (dx * dx + dy * dy <= r2) Px(p, w, x, y, r, g, b); + } + } + + static void Anello(byte[] p, int w, int cx, int cy, int esterno, int interno, byte r, byte g, byte b) + { + var e2 = esterno * esterno; + var i2 = interno * interno; + for (var y = cy - esterno; y <= cy + esterno; y++) + for (var x = cx - esterno; x <= cx + esterno; x++) + { + var d = (x - cx) * (x - cx) + (y - cy) * (y - cy); + if (d <= e2 && d >= i2) Px(p, w, x, y, r, g, b); + } + } + + static void Px(byte[] p, int w, int x, int y, byte r, byte g, byte b) + { + if ((uint)x >= (uint)w || (uint)y >= (uint)w) return; + var i = (y * w + x) * 4; + p[i] = r; + p[i + 1] = g; + p[i + 2] = b; + p[i + 3] = 255; + } + + static byte[] Png(byte[] rgba, int w, int h) + { + var raw = new byte[h * (w * 4 + 1)]; + for (var y = 0; y < h; y++) + Buffer.BlockCopy(rgba, y * w * 4, raw, y * (w * 4 + 1) + 1, w * 4); + using var comp = new MemoryStream(); + using (var z = new ZLibStream(comp, CompressionLevel.Fastest, leaveOpen: true)) + z.Write(raw); + var ms = new MemoryStream(); + ms.Write(new byte[] { 137, 80, 78, 71, 13, 10, 26, 10 }); + var ihdr = new byte[13]; + Be(ihdr, 0, w); + Be(ihdr, 4, h); + ihdr[8] = 8; + ihdr[9] = 6; + Chunk(ms, "IHDR", ihdr); + Chunk(ms, "IDAT", comp.ToArray()); + Chunk(ms, "IEND", []); + return ms.ToArray(); + } + + static void Chunk(Stream ms, string tipo, byte[] dati) + { + var len = new byte[4]; + Be(len, 0, dati.Length); + ms.Write(len); + var t = Encoding.ASCII.GetBytes(tipo); + ms.Write(t); + ms.Write(dati); + var crc = new byte[4]; + Be(crc, 0, Crc(t, dati)); + ms.Write(crc); + } + + static void Be(byte[] b, int o, int v) => Be(b, o, (uint)v); + + static void Be(byte[] b, int o, uint v) + { + b[o] = (byte)(v >> 24); + b[o + 1] = (byte)(v >> 16); + b[o + 2] = (byte)(v >> 8); + b[o + 3] = (byte)v; + } + + static uint Crc(byte[] tipo, byte[] dati) + { + var c = 0xffffffffu; + void Byte(byte b) + { + c ^= b; + for (var i = 0; i < 8; i++) c = (c & 1) != 0 ? 0xedb88320u ^ (c >> 1) : c >> 1; + } + foreach (var b in tipo) Byte(b); + foreach (var b in dati) Byte(b); + return c ^ 0xffffffffu; + } + + static string EstensioneImmagine(string percorso) + { + var e = Path.GetExtension(percorso).ToLowerInvariant(); + return e is ".png" or ".webp" or ".bmp" ? e : ".jpg"; + } +} diff --git a/src/DaPConvertitore.Motore/Lettore/Media.cs b/src/DaPConvertitore.Motore/Lettore/Media.cs index 0f482f9..47d716f 100644 --- a/src/DaPConvertitore.Motore/Lettore/Media.cs +++ b/src/DaPConvertitore.Motore/Lettore/Media.cs @@ -68,11 +68,19 @@ public static async Task Leggi(Strumenti s, string percorso) return new SchedaMedia(info, tag, audio, sub, capitoli); } - /// La copertina: quella dentro il file, o cover.jpg / folder.jpg nella cartella. JPEG piccolo. + /// + /// La copertina: quella dentro il file, poi «nome (copertina).jpg» accanto, poi cover.jpg / folder.jpg nella cartella. + /// Quella dentro esce in JPEG; un file accanto si legge così com'è (JPG o PNG). + /// public static async Task Copertina(Strumenti s, string percorso, bool dentro, bool silenzioso = false, int lato = 800) { if (dentro) { + // un video: solo la copertina allegata, non un fotogramma del film + if (Copertine.VideoNelFile(percorso)) + return await Copertine.ProvaAllegata(s, percorso, lato, silenzioso); + var allegata = await Copertine.ProvaAllegata(s, percorso, lato, silenzioso: true); + if (allegata is not null) return allegata; var jpg = Path.Combine(Strumenti.CartellaTemporanea, $"copertina-{Guid.NewGuid():N}.jpg"); try { @@ -84,10 +92,15 @@ public static async Task Leggi(Strumenti s, string percorso) finally { try { File.Delete(jpg); } catch { } } } var cartella = Path.GetDirectoryName(percorso)!; - foreach (var nome in new[] { "cover.jpg", "folder.jpg", "cover.png", "front.jpg", "album.jpg", "Cover.jpg", "Folder.jpg" }) + var radice = Nomi.Radice(percorso); + foreach (var nome in new[] + { + $"{radice} (copertina).jpg", $"{radice} (copertina).png", $"{radice} (copertina).jpeg", + "cover.jpg", "folder.jpg", "cover.png", "front.jpg", "album.jpg", "Cover.jpg", "Folder.jpg", + }) { var p = Path.Combine(cartella, nome); - if (File.Exists(p) && new FileInfo(p).Length < 20_000_000) return await File.ReadAllBytesAsync(p); + if (File.Exists(p) && new FileInfo(p).Length is > 0 and < 20_000_000) return await File.ReadAllBytesAsync(p); } return null; } diff --git a/src/DaPConvertitore.Motore/Lettore/Modifiche.cs b/src/DaPConvertitore.Motore/Lettore/Modifiche.cs index ff75ad0..0e197e3 100644 --- a/src/DaPConvertitore.Motore/Lettore/Modifiche.cs +++ b/src/DaPConvertitore.Motore/Lettore/Modifiche.cs @@ -241,6 +241,57 @@ public static async Task TagliaVideo(Strumenti s, string percorso, doubl finally { Nomi.Libera(uscita); } } + /// + /// Tiene i pezzi indicati, nell'ordine dato, e li mette uno dopo l'altro accanto all'originale + /// (nome «tagliato»). L'originale non si tocca. Un pezzo solo è il taglio di sempre. + /// + public static async Task TagliaPezzi(Strumenti s, string percorso, IReadOnlyList<(double Da, double A)> pezzi, CancellationToken ct = default) + { + var utili = pezzi.Where(p => p.A > p.Da + 0.05).ToList(); + if (utili.Count == 0) throw new ErroreConversione("Non c'è niente da tenere."); + if (utili.Count == 1) return await TagliaVideo(s, percorso, utili[0].Da, utili[0].A, ct); + + var dir = Path.Combine(Strumenti.CartellaTemporanea, "tagli-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(dir); + var uscita = Nomi.Prenota(percorso, Path.GetExtension(percorso), "tagliato"); + var bozza = Nomi.Bozza(uscita); + try + { + string N(double v) => v.ToString("0.###", CultureInfo.InvariantCulture); + var pezziFile = new List(); + for (var i = 0; i < utili.Count; i++) + { + var pezzo = Path.Combine(dir, $"p{i}{Path.GetExtension(percorso)}"); + var r = await Processi.Esegui(s.Ffmpeg, ["-hide_banner", "-loglevel", "error", "-y", + "-ss", N(utili[i].Da), "-to", N(utili[i].A), "-i", percorso, + "-map", "0", "-c", "copy", "-avoid_negative_ts", "make_zero", "-reset_timestamps", "1", + "-f", FormatoFfmpeg(percorso), pezzo], ct); + if (r.Codice != 0 || !File.Exists(pezzo)) throw new ErroreConversione("Non sono riuscito a staccare un pezzo.", r.Errori); + pezziFile.Add(pezzo); + } + var lista = Path.Combine(dir, "lista.txt"); + await File.WriteAllLinesAsync(lista, pezziFile.Select(p => "file '" + p.Replace('\\', '/').Replace("'", "'\\''") + "'"), ct); + var unione = await Processi.Esegui(s.Ffmpeg, ["-hide_banner", "-loglevel", "error", "-y", + "-f", "concat", "-safe", "0", "-i", lista, "-c", "copy", "-fflags", "+genpts", + "-f", FormatoFfmpeg(percorso), bozza], ct); + if (unione.Codice != 0 || !File.Exists(bozza)) throw new ErroreConversione("Non sono riuscito a rimettere insieme i pezzi.", unione.Errori); + File.Move(bozza, uscita); + return uscita; + } + catch + { + try { if (File.Exists(bozza)) File.Delete(bozza); } catch { } + try { if (File.Exists(uscita)) File.Delete(uscita); } catch { } + Nomi.Libera(uscita); + throw; + } + finally + { + Nomi.Libera(uscita); + try { Directory.Delete(dir, true); } catch { } + } + } + static string FormatoFfmpeg(string p) => Path.GetExtension(p).ToLowerInvariant() switch { ".mp4" or ".m4v" => "mp4", ".mov" => "mov", ".mkv" => "matroska", ".webm" => "webm", ".avi" => "avi", ".ts" or ".m2ts" or ".mts" => "mpegts", diff --git a/src/DaPConvertitore.Motore/Metadati.cs b/src/DaPConvertitore.Motore/Metadati.cs new file mode 100644 index 0000000..b67fd7f --- /dev/null +++ b/src/DaPConvertitore.Motore/Metadati.cs @@ -0,0 +1,175 @@ +using System.Globalization; +using DaP.Convertitore.Lettore; + +namespace DaP.Convertitore; + +/// +/// Quello che l'utente ha corretto nella sezione «Info del file». Si scrive nel file convertito. +/// I campi vuoti si scrivono vuoti (così si può togliere un titolo). Quello che il formato non tiene si ignora. +/// +public sealed class OpzioniScheda +{ + public bool Scrivi { get; set; } + public string? Titolo { get; set; } + public string? Artista { get; set; } + public string? Album { get; set; } + public string? Anno { get; set; } + public string? Traccia { get; set; } + public string? Commento { get; set; } + public string? Autore { get; set; } + public string? Descrizione { get; set; } + public string? DataScatto { get; set; } + /// Null = tieni quella che c'è. «nessuna» = toglila. «generata:2» = un disegno. Altrimenti il percorso di un'immagine. + public string? Copertina { get; set; } +} + +/// Quello che la sezione mostra, letto dal file, e quali campi il formato di arrivo sa tenere. +public sealed class DatiScheda +{ + public string Titolo { get; set; } = ""; + public string Artista { get; set; } = ""; + public string Album { get; set; } = ""; + public string Anno { get; set; } = ""; + public string Traccia { get; set; } = ""; + public string Commento { get; set; } = ""; + public string Autore { get; set; } = ""; + public string Descrizione { get; set; } = ""; + public string DataScatto { get; set; } = ""; + public string? Copertina { get; set; } + public string[] Campi { get; set; } = []; +} + +/// +/// I campi che un formato sa conservare, e come si passano a FFmpeg. Niente campi inventati: +/// la musica tiene titolo, artista, album, anno, traccia (e la copertina su MP3, M4A, FLAC); +/// il video MP4, MOV e MKV tiene titolo e commento; JPG e TIFF tengono data, descrizione e autore. +/// +public static class Metadati +{ + public static bool FotoTiene(string estensione) => + estensione.ToLowerInvariant() is ".jpg" or ".jpeg" or ".tif" or ".tiff"; + + /// I nomi dei campi, come li aspetta l'interfaccia. Vuoto = il formato non ne tiene. + public static string[] Campi(string estensione) => estensione.ToLowerInvariant() switch + { + ".mp3" or ".m4a" or ".flac" => ["titolo", "artista", "album", "anno", "traccia", "copertina"], + ".ogg" or ".opus" or ".wma" => ["titolo", "artista", "album", "anno", "traccia"], + ".mp4" or ".mov" or ".mkv" => ["titolo", "commento"], + ".jpg" or ".jpeg" or ".tif" or ".tiff" => ["data", "descrizione", "autore"], + _ => [], + }; + + /// Aggiunge i -metadata al comando, solo per i campi che questo formato tiene. + public static void SulComando(List a, OpzioniScheda? s, string estensione) + { + if (s is not { Scrivi: true }) return; + var est = estensione.ToLowerInvariant(); + if (est is ".mp3" or ".m4a" or ".flac" or ".ogg" or ".opus" or ".wma") + { + Meta(a, "title", s.Titolo); + Meta(a, "artist", s.Artista); + Meta(a, "album", s.Album); + Meta(a, "date", s.Anno); + Meta(a, "track", s.Traccia); + } + else if (est is ".mp4" or ".mov" or ".mkv") + { + Meta(a, "title", s.Titolo); + Meta(a, "comment", s.Commento); + } + } + + static void Meta(List a, string chiave, string? valore) + { + if (valore is null) return; + var pulito = valore.Replace('\r', ' ').Replace('\n', ' ').Trim(); + a.Add("-metadata"); + a.Add($"{chiave}={pulito}"); + } + + /// Una data scritta a mano: un anno, 2024-03-12, oppure 12/03/2024. Mezzogiorno, così il fuso non cambia giorno. + public static DateTimeOffset? DataDi(string? testo) + { + if (string.IsNullOrWhiteSpace(testo)) return null; + var t = testo.Trim(); + if (t.Length == 4 && int.TryParse(t, NumberStyles.None, CultureInfo.InvariantCulture, out var anno) && anno is >= 1000 and <= 9999) + return new DateTimeOffset(anno, 1, 1, 12, 0, 0, TimeSpan.Zero); + string[] formati = ["yyyy-MM-dd", "yyyy/MM/dd", "dd/MM/yyyy", "d/M/yyyy", "yyyy:MM:dd HH:mm:ss", "yyyy-MM-ddTHH:mm:ss", "yyyy-MM-dd HH:mm:ss"]; + if (DateTime.TryParseExact(t, formati, CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out var d) + || DateTime.TryParse(t, CultureInfo.GetCultureInfo("it-IT"), DateTimeStyles.AllowWhiteSpaces, out d)) + return new DateTimeOffset(d.Year, d.Month, d.Day, 12, 0, 0, TimeSpan.Zero); + return null; + } + + public static async Task Leggi(Strumenti s, string percorso, string estensioneUscita) + { + var dati = new DatiScheda { Campi = Campi(estensioneUscita) }; + try + { + var m = await Media.Leggi(s, percorso); + string T(params string[] chiavi) + { + foreach (var k in chiavi) + if (m.Tag.TryGetValue(k, out var v) && !string.IsNullOrWhiteSpace(v)) return v.Trim(); + return ""; + } + dati.Titolo = T("title"); + dati.Artista = T("artist", "album_artist"); + dati.Album = T("album"); + dati.Anno = Anno(T("date", "year")); + dati.Traccia = Traccia(T("track")); + dati.Commento = T("comment", "description"); + dati.Autore = T("artist", "author", "composer"); + dati.Descrizione = T("comment", "description", "title"); + dati.DataScatto = Giorno(T("creation_time", "date", "DateTimeOriginal")); + } + catch (ErroreConversione) { /* una foto che FFprobe non racconta: restano i campi della foto */ } + + if (FotoTiene(Path.GetExtension(percorso)) || FotoTiene(estensioneUscita)) + { + try + { + var foto = await Immagini.LeggiTesti(percorso); + if (!string.IsNullOrWhiteSpace(foto.Autore)) dati.Autore = foto.Autore; + if (!string.IsNullOrWhiteSpace(foto.Descrizione)) dati.Descrizione = foto.Descrizione; + if (foto.Data is { } d) dati.DataScatto = d.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); + } + catch { /* senza i testi della foto si tengono quelli di FFprobe, se c'erano */ } + } + + if (dati.Campi.Contains("copertina")) + { + try + { + var b = await Media.Copertina(s, percorso, true, silenzioso: true, lato: 280); + if (b is not null) dati.Copertina = new EsitoCopertina(b, null, true, null).ComeDataUrl(); + } + catch { /* niente copertina da mostrare */ } + } + return dati; + } + + static string Anno(string data) + { + for (var i = 0; i + 4 <= data.Length; i++) + { + if (data.Skip(i).Take(4).All(char.IsDigit) && (i == 0 || !char.IsDigit(data[i - 1]))) + return data.Substring(i, 4); + } + return ""; + } + + static string Traccia(string t) + { + if (t.Length == 0) return ""; + var p = t.Split('/')[0].Trim(); + return p.Length <= 4 ? p : ""; + } + + static string Giorno(string data) + { + var d = DataDi(data); + return d is null ? "" : d.Value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); + } + +} diff --git a/src/DaPConvertitore.Motore/MiniaturaFile.cs b/src/DaPConvertitore.Motore/MiniaturaFile.cs new file mode 100644 index 0000000..6450490 --- /dev/null +++ b/src/DaPConvertitore.Motore/MiniaturaFile.cs @@ -0,0 +1,39 @@ +using System.Diagnostics; + +namespace DaP.Convertitore; + +/// Un fotogramma piccolo di un video (o la copertina di un audio) per i recenti della home. +public static class MiniaturaFile +{ + public static string? PngBase64(string percorso) + { + try + { + if (!File.Exists(percorso)) return null; + var cat = Catalogo.CategoriaDi(percorso); + if (cat is not (Categoria.Video or Categoria.Audio)) return null; + var ff = Strumenti.Trova().Ffmpeg; + if (!File.Exists(ff)) return null; + var psi = new ProcessStartInfo(ff) + { + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + }; + foreach (var a in ComandiRegistrazione.ArgomentiFotogramma(percorso)) psi.ArgumentList.Add(a); + using var p = Process.Start(psi); + if (p is null) return null; + using var ms = new MemoryStream(); + p.StandardOutput.BaseStream.CopyTo(ms); + if (!p.WaitForExit(8000)) { try { p.Kill(entireProcessTree: true); } catch { /* è già fermo */ } } + if (ms.Length < 32) return null; + return Convert.ToBase64String(ms.ToArray()); + } + catch (Exception e) + { + Registro.Scrivi($"miniatura di {Path.GetFileName(percorso)}: {e.Message}"); + return null; + } + } +} diff --git a/src/DaPConvertitore.Motore/Opzioni.cs b/src/DaPConvertitore.Motore/Opzioni.cs index 315105c..1cb1149 100644 --- a/src/DaPConvertitore.Motore/Opzioni.cs +++ b/src/DaPConvertitore.Motore/Opzioni.cs @@ -14,6 +14,8 @@ public sealed class Opzioni public OpzioniImmagine Immagine { get; set; } = new(); public OpzioniPdf Pdf { get; set; } = new(); public OpzioniArchivio Archivio { get; set; } = new(); + /// Le info corrette nella sezione «Info del file». Null = si tengono quelle del file di partenza. Finiscono nel convertito. + public OpzioniScheda? Scheda { get; set; } public static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web) { diff --git a/src/DaPConvertitore.Motore/Sonda.cs b/src/DaPConvertitore.Motore/Sonda.cs index 8ab8cb8..e0d2c0e 100644 --- a/src/DaPConvertitore.Motore/Sonda.cs +++ b/src/DaPConvertitore.Motore/Sonda.cs @@ -26,7 +26,13 @@ public sealed record InfoMedia( InfoVideo? Video, IReadOnlyList Audio, IReadOnlyList Sottotitoli, - bool Copertina); + bool Copertina) +{ + /// Indice del flusso attached_pic, o -1 se non c'è. La miniatura e la copertina usano quello. + public int IndiceCopertina { get; init; } = -1; + /// Quanti flussi video veri (non la copertina). Serve a mettere la copertina nuova come ultimo. + public int VideoVeri { get; init; } +} public static class Sonda { @@ -53,6 +59,8 @@ public static InfoMedia Interpreta(string json) var audio = new List(); var sub = new List(); var copertina = false; + var indiceCopertina = -1; + var videoVeri = 0; long bitrateAudio = 0; if (radice.TryGetProperty("streams", out var flussi)) @@ -66,7 +74,8 @@ public static InfoMedia Interpreta(string json) if (tipo == "video") { var allegata = st.TryGetProperty("disposition", out var disp) && Numero(disp, "attached_pic") == 1; - if (allegata) { copertina = true; continue; } + if (allegata) { copertina = true; if (indiceCopertina < 0) indiceCopertina = indice; continue; } + videoVeri++; if (video is not null) continue; int w = (int)Numero(st, "width"), h = (int)Numero(st, "height"); if (Ruotato(st)) (w, h) = (h, w); @@ -95,7 +104,11 @@ public static InfoMedia Interpreta(string json) // MKV e WEBM spesso non dicono il bitrate del video: lo si ricava dal totale if (video is { Bitrate: 0 } && bitrate > 0) video = video with { Bitrate = Math.Max(0, bitrate - (bitrateAudio > 0 ? bitrateAudio : audio.Count * 160_000L)) }; - return new InfoMedia(durata, bitrate, contenitore, video, audio, sub, copertina); + return new InfoMedia(durata, bitrate, contenitore, video, audio, sub, copertina) + { + IndiceCopertina = indiceCopertina, + VideoVeri = videoVeri, + }; } static bool Ruotato(JsonElement st) diff --git a/src/DaPConvertitore.Motore/Storico.cs b/src/DaPConvertitore.Motore/Storico.cs index c5ebde3..a964c5e 100644 --- a/src/DaPConvertitore.Motore/Storico.cs +++ b/src/DaPConvertitore.Motore/Storico.cs @@ -25,6 +25,9 @@ sealed class Dati public List Voci { get; set; } = []; } + /// È entrata una voce (conversione, screenshot, registrazione). La home se ne accorge. + public static event Action? Cambiato; + static Dati Leggi() { try @@ -35,12 +38,20 @@ static Dati Leggi() return new(); } + static void Scrivi(Dati d) + { + var tmp = Percorso + ".tmp"; + File.WriteAllText(tmp, JsonSerializer.Serialize(d, new JsonSerializerOptions(Opzioni.Json) { WriteIndented = true })); + File.Move(tmp, Percorso, true); + } + /// Registra un lavoro riuscito. Non fa mai fallire la conversione. public static void Aggiungi(Lavoro l) { try { if (l.Uscita is null || l.Stato != StatoLavoro.Fatto) return; + Action? avviso; lock (chiave) { var d = Leggi(); @@ -50,14 +61,38 @@ public static void Aggiungi(Lavoro l) if (d.Voci.Count > Massimo) d.Voci.RemoveRange(Massimo, d.Voci.Count - Massimo); d.Conversioni++; if (l.Formato.Sostituisce && l.PesoPrima > dopo && dopo > 0) d.ByteRisparmiati += l.PesoPrima - dopo; - var tmp = Percorso + ".tmp"; - File.WriteAllText(tmp, JsonSerializer.Serialize(d, new JsonSerializerOptions(Opzioni.Json) { WriteIndented = true })); - File.Move(tmp, Percorso, true); + Scrivi(d); + avviso = Cambiato; } + avviso?.Invoke(); } catch (Exception e) { Registro.Errore("storico: salva", e); } } + /// + /// Uno screenshot o una registrazione, nella stessa lista dei recenti. Non conta come conversione: + /// il totale «in tutto» resta quello delle conversioni. + /// + public static void AggiungiFile(string percorso, string formato) + { + try + { + if (!File.Exists(percorso)) return; + Action? avviso; + lock (chiave) + { + var d = Leggi(); + var info = new FileInfo(percorso); + d.Voci.Insert(0, new VoceStorico(DateTime.Now, info.Name, formato, percorso, 0, info.Length, Catalogo.Chiave(Catalogo.CategoriaDi(percorso)))); + if (d.Voci.Count > Massimo) d.Voci.RemoveRange(Massimo, d.Voci.Count - Massimo); + Scrivi(d); + avviso = Cambiato; + } + avviso?.Invoke(); + } + catch (Exception e) { Registro.Errore("storico: file", e); } + } + /// Le ultime conversioni il cui risultato c'è ancora, e i totali. public static (List Recenti, TotaliStorico Totali) Recenti(int quante) { diff --git a/src/DaPConvertitore.Motore/Video.cs b/src/DaPConvertitore.Motore/Video.cs index eef1f8b..516508b 100644 --- a/src/DaPConvertitore.Motore/Video.cs +++ b/src/DaPConvertitore.Motore/Video.cs @@ -134,6 +134,7 @@ static async Task Esegui(Lavoro l, Contesto ctx, InfoMedia info, PianoVideo p, s } } + if (passata != 1) Metadati.SulComando(a, l.Opzioni.Scheda, est); if (est is ".mp4" or ".mov") a.AddRange(["-movflags", "+faststart"]); if (passata == 1) { diff --git a/src/DaPConvertitore/AnteprimaSchermo.cs b/src/DaPConvertitore/AnteprimaSchermo.cs new file mode 100644 index 0000000..5917656 --- /dev/null +++ b/src/DaPConvertitore/AnteprimaSchermo.cs @@ -0,0 +1,116 @@ +using System.Runtime.InteropServices; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Threading; + +namespace DaP.Convertitore.App; + +/// +/// Lo schermo, dal vivo, dentro la finestra di registrazione. Pochi fotogrammi al secondo, rimpiccioliti: +/// è un'anteprima, non il video. BitBlt del desktop rispetta l'esclusione della finestra +/// (WDA_EXCLUDEFROMCAPTURE), così non si vede l'effetto specchio. +/// +public sealed class AnteprimaSchermo : IDisposable +{ + readonly Image img; + readonly DispatcherTimer timer; + WriteableBitmap? bmp; + int x, y, w, h; + int occupata; + bool detto; + + public AnteprimaSchermo(Image img) + { + this.img = img; + timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(125) }; + timer.Tick += (_, _) => Scatta(); + } + + public void Guarda(int x, int y, int w, int h) + { + this.x = x; this.y = y; this.w = w; this.h = h; + if (w > 1 && h > 1 && !timer.IsEnabled) timer.Start(); + } + + public void Ferma() => timer.Stop(); + + public void Dispose() => timer.Stop(); + + void Scatta() + { + if (w < 2 || h < 2) return; + if (Interlocked.Exchange(ref occupata, 1) == 1) return; + var (sx, sy, sw, sh) = (x, y, w, h); + Task.Run(() => Cattura(sx, sy, sw, sh)).ContinueWith(t => + { + var px = t.IsFaulted ? null : t.Result; + img.Dispatcher.BeginInvoke(() => + { + try + { + if (px is { } f) Dipingi(f); + else if (!detto && t.IsFaulted) { detto = true; Registro.Errore("anteprima schermo", t.Exception?.GetBaseException() ?? new Exception("vuota")); } + } + finally { Interlocked.Exchange(ref occupata, 0); } + }); + }); + } + + void Dipingi((int L, int A, byte[] Pixel) f) + { + if (bmp is null || bmp.PixelWidth != f.L || bmp.PixelHeight != f.A) + { + bmp = new WriteableBitmap(f.L, f.A, 96, 96, PixelFormats.Bgra32, null); + img.Source = bmp; + } + bmp.WritePixels(new Int32Rect(0, 0, f.L, f.A), f.Pixel, f.L * 4, 0); + } + + static (int L, int A, byte[] Pixel)? Cattura(int x, int y, int w, int h) + { + var dw = Math.Min(480, w); + var dh = Math.Max(1, (int)Math.Round(h * (dw / (double)w))); + var hdc = GetDC(IntPtr.Zero); + if (hdc == IntPtr.Zero) return null; + var mem = CreateCompatibleDC(hdc); + var bmp = CreateCompatibleBitmap(hdc, dw, dh); + var vecchio = SelectObject(mem, bmp); + try + { + SetStretchBltMode(mem, 3); + if (StretchBlt(mem, 0, 0, dw, dh, hdc, x, y, w, h, 0x00CC0020) == 0) return null; + var info = new BITMAPINFO { biSize = 40, biWidth = dw, biHeight = -dh, biPlanes = 1, biBitCount = 32 }; + var pixel = new byte[dw * dh * 4]; + if (GetDIBits(mem, bmp, 0, (uint)dh, pixel, ref info, 0) == 0) return null; + return (dw, dh, pixel); + } + finally + { + SelectObject(mem, vecchio); + DeleteObject(bmp); + DeleteDC(mem); + ReleaseDC(IntPtr.Zero, hdc); + } + } + + [StructLayout(LayoutKind.Sequential)] + struct BITMAPINFO + { + public int biSize, biWidth, biHeight; + public short biPlanes, biBitCount; + public int biCompression, biSizeImage, biXPelsPerMeter, biYPelsPerMeter, biClrUsed, biClrImportant; + } + + [DllImport("user32.dll")] static extern IntPtr GetDC(IntPtr h); + [DllImport("user32.dll")] static extern int ReleaseDC(IntPtr h, IntPtr hdc); + [DllImport("gdi32.dll")] static extern IntPtr CreateCompatibleDC(IntPtr hdc); + [DllImport("gdi32.dll")] static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, int w, int h); + [DllImport("gdi32.dll")] static extern IntPtr SelectObject(IntPtr hdc, IntPtr o); + [DllImport("gdi32.dll")] static extern bool DeleteObject(IntPtr o); + [DllImport("gdi32.dll")] static extern bool DeleteDC(IntPtr hdc); + [DllImport("gdi32.dll")] static extern int SetStretchBltMode(IntPtr hdc, int mode); + [DllImport("gdi32.dll")] static extern int StretchBlt(IntPtr dest, int x, int y, int w, int h, IntPtr src, int sx, int sy, int sw, int sh, int rop); + [DllImport("gdi32.dll")] static extern int GetDIBits(IntPtr hdc, IntPtr bmp, uint start, uint lines, byte[] bits, ref BITMAPINFO info, uint usage); +} diff --git a/src/DaPConvertitore/Avatar.cs b/src/DaPConvertitore/Avatar.cs index fba7623..1be2caf 100644 --- a/src/DaPConvertitore/Avatar.cs +++ b/src/DaPConvertitore/Avatar.cs @@ -8,6 +8,7 @@ using System.Windows.Media.Effects; using System.Windows.Media.Imaging; using System.Windows.Threading; +using DaP.Convertitore.Lettore; using Microsoft.Win32; namespace DaP.Convertitore.App; @@ -99,6 +100,7 @@ public sealed class FinestraAvatar : Window double angolo; // quanto è girato, in radianti (0 = di fronte) MenuAvatar? menu; MiniPlayer? player; + MiniVideo? video; Cronometro? cronometro; ScegliPersonaggio? scelta; public event Action? Spostato; @@ -307,6 +309,21 @@ void ApriMenu() m.Items.Add(new Separator()); m.Items.Add(Voce("Apri DaP Convertitore", () => Regia.Gestisci(new Richiesta(null, [], true)))); m.Items.Add(new Separator()); + m.Items.Add(Voce("Screenshot", Schermata.Cattura)); + var apriRegistra = false; + m.Items.Add(Voce(Registrazione.Attiva ? "La registrazione è in corso" : "Registra…", () => + { + apriRegistra = true; + Registro.Scrivi("registrazione: clic su Registra nell'avatar"); + })); + m.Items.Add(new Separator()); + Registrazione.EscludiMenu(m); + m.Closed += (_, _) => + { + if (!apriRegistra) return; + try { Registrazione.Chiedi("avatar", this); } + catch (Exception e) { Registro.Errore("registrazione: avatar", e); } + }; m.Items.Add(Voce("Nascondi l'avatar", () => Regia.Avatar(false))); m.IsOpen = true; } @@ -316,8 +333,9 @@ void ApriMenu() void Chiedi(IReadOnlyList file) { if (file.Count == 0) return; - // solo musica: parte subito, col suo piccolo player sull'avatar, senza aprire l'app (foto e video si aprono come sempre) + // musica e video partono subito, col loro piccolo player sull'avatar, senza aprire l'app if (file.All(f => File.Exists(f) && Catalogo.CategoriaDi(f) == Categoria.Audio)) { RiproduciMusica(file); return; } + if (file.All(f => File.Exists(f) && Catalogo.CategoriaDi(f) == Categoria.Video)) { RiproduciVideo(file); return; } ApriFumetto(file); } @@ -328,7 +346,8 @@ public void ApriFumetto(IReadOnlyList file) menu = new MenuAvatar(file, this); // il player (se c'è) si nasconde, ma la musica va avanti; quando si torna indietro riappare player?.Hide(); - menu.Closed += (_, _) => { menu = null; player?.Show(); }; + video?.Hide(); + menu.Closed += (_, _) => { menu = null; player?.Show(); video?.Show(); }; menu.Show(); } @@ -336,6 +355,7 @@ public void ApriFumetto(IReadOnlyList file) public void RiproduciMusica(IReadOnlyList brani) { player?.Close(); + video?.Close(); menu?.Close(); player = new MiniPlayer(brani, this); player.Closed += (_, _) => { player = null; this.Suona("idle", true); }; @@ -343,6 +363,18 @@ public void RiproduciMusica(IReadOnlyList brani) player.Show(); } + /// Fa partire il video sul piccolo player attaccato all'avatar. + public void RiproduciVideo(IReadOnlyList filmati) + { + video?.Close(); + player?.Close(); + menu?.Close(); + video = new MiniVideo(filmati, this); + video.Closed += (_, _) => { video = null; this.Suona("idle", true); }; + video.StatoCambiato += (inRiproduzione) => this.Suona(inRiproduzione ? "attento" : "idle", true); + video.Show(); + } + /// Il cronometro dal tasto destro: se c'è lo chiude, se no lo apre e lo fa partire. public void AlternaCronometro() { @@ -548,6 +580,11 @@ static UIElement Icona(string disegno, Brush colore, double misura, bool piena) }; readonly Grid barra = new() { Height = 22, Background = Brushes.Transparent, Cursor = Cursors.Hand, Margin = new Thickness(0, 12, 0, 0) }; readonly List equalizzatore = []; + readonly Image fotoCopertina = new() { Stretch = Stretch.UniformToFill, IsHitTestVisible = false }; + readonly StackPanel barretteEq = new() { Orientation = Orientation.Horizontal, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Height = 22, IsHitTestVisible = false }; + byte[]? copertinaOra; + string? notaSotto; + int notaPer; readonly Button bPlay; readonly DispatcherTimer orologio; int i; @@ -578,20 +615,30 @@ void Cerca(MouseEventArgs e) barra.MouseMove += (_, e) => { if (barra.IsMouseCaptured) Cerca(e); }; barra.MouseLeftButtonUp += (_, _) => barra.ReleaseMouseCapture(); - // in alto: l'icona con le barrette che ballano, il titolo (intero, per quanto ci sta) e la X + // in alto: la copertina (o le barrette, se il brano non ne ha), il titolo e la X. + // sopra la copertina, col mouse, escono Modifica e Download var tessera = new Border { - Width = 46, Height = 46, CornerRadius = new CornerRadius(14), VerticalAlignment = VerticalAlignment.Center, + Width = 112, Height = 112, CornerRadius = new CornerRadius(16), VerticalAlignment = VerticalAlignment.Center, ClipToBounds = true, Background = new LinearGradientBrush(Color.FromArgb(120, 0xff, 0x3d, 0xf2), Color.FromArgb(150, 0x5a, 0x2b, 0xbf), 45), BorderBrush = new SolidColorBrush(Color.FromArgb(60, 255, 255, 255)), BorderThickness = new Thickness(1), }; - var barrette = new StackPanel { Orientation = Orientation.Horizontal, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Height = 22 }; for (var k = 0; k < 4; k++) { var br = new Border { Width = 4, Height = 5, CornerRadius = new CornerRadius(2), Background = Col("#ffd54a"), VerticalAlignment = VerticalAlignment.Bottom, Margin = new Thickness(k == 0 ? 0 : 3, 0, 0, 0) }; - equalizzatore.Add(br); barrette.Children.Add(br); + equalizzatore.Add(br); barretteEq.Children.Add(br); } - tessera.Child = barrette; + var sopra = new StackPanel { Orientation = Orientation.Vertical, Margin = new Thickness(6, 0, 6, 4) }; + sopra.Children.Add(TastoCopertina("Modifica", () => ModificaCopertina())); + sopra.Children.Add(TastoCopertina("Download", () => ScaricaCopertina())); + var velo = new Border { Background = new SolidColorBrush(Color.FromArgb(170, 8, 6, 14)), CornerRadius = new CornerRadius(0, 0, 14, 14), VerticalAlignment = VerticalAlignment.Bottom, Height = 58, Child = sopra, Visibility = Visibility.Collapsed }; + var riquadro = new Grid(); + riquadro.Children.Add(fotoCopertina); + riquadro.Children.Add(barretteEq); + riquadro.Children.Add(velo); + riquadro.MouseEnter += (_, _) => velo.Visibility = Visibility.Visible; + riquadro.MouseLeave += (_, _) => velo.Visibility = Visibility.Collapsed; + tessera.Child = riquadro; var chiudi = Tasto(null, "Chiudi", () => Close(), lato: 28, tondo: true, ico: IcChiudi); chiudi.VerticalAlignment = VerticalAlignment.Top; chiudi.Margin = new Thickness(0); var nomi = new StackPanel { VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(13, 0, 10, 0) }; @@ -684,6 +731,114 @@ void Vai(int n) mp.Open(new Uri(brani[i])); mp.Play(); Stato(true); + _ = CaricaCopertina(i); + } + + async Task CaricaCopertina(int n) + { + byte[]? jpg = null; + try { jpg = await Media.Copertina(Strumenti.Trova(), brani[n], true); } + catch { /* niente copertina: restano le barrette */ } + if (n != i) return; + await Dispatcher.InvokeAsync(() => MostraCopertina(jpg)); + } + + void MostraCopertina(byte[]? jpg) + { + copertinaOra = jpg; + if (jpg is null) + { + fotoCopertina.Source = null; + barretteEq.Visibility = Visibility.Visible; + return; + } + fotoCopertina.Source = ImmagineDi(jpg); + barretteEq.Visibility = Visibility.Collapsed; + } + + static BitmapImage ImmagineDi(byte[] b) + { + var img = new BitmapImage(); + using var ms = new MemoryStream(b); + img.BeginInit(); + img.CacheOption = BitmapCacheOption.OnLoad; + img.StreamSource = ms; + img.EndInit(); + img.Freeze(); + return img; + } + + Button TastoCopertina(string testo, Action fai) + { + var b = new Button + { + Content = new TextBlock { Text = testo, FontSize = 10, FontWeight = FontWeights.Bold, Foreground = Brushes.White, HorizontalAlignment = HorizontalAlignment.Center }, + Height = 22, Margin = new Thickness(0, 2, 0, 0), HorizontalAlignment = HorizontalAlignment.Stretch, Cursor = Cursors.Hand, Focusable = false, + Background = new SolidColorBrush(Color.FromArgb(40, 255, 255, 255)), BorderThickness = new Thickness(0), + }; + var t = new ControlTemplate(typeof(Button)); + var bordo = new FrameworkElementFactory(typeof(Border)) { Name = "b" }; + bordo.SetValue(Border.CornerRadiusProperty, new CornerRadius(8)); + bordo.SetBinding(Border.BackgroundProperty, new System.Windows.Data.Binding("Background") { RelativeSource = System.Windows.Data.RelativeSource.TemplatedParent }); + var presente = new FrameworkElementFactory(typeof(ContentPresenter)); + presente.SetValue(FrameworkElement.HorizontalAlignmentProperty, HorizontalAlignment.Center); + presente.SetValue(FrameworkElement.VerticalAlignmentProperty, VerticalAlignment.Center); + bordo.AppendChild(presente); + t.VisualTree = bordo; + var su = new Trigger { Property = UIElement.IsMouseOverProperty, Value = true }; + su.Setters.Add(new Setter(Border.BackgroundProperty, new SolidColorBrush(Color.FromRgb(0xff, 0xd5, 0x4a)), "b")); + t.Triggers.Add(su); + b.Template = t; + b.Click += (_, _) => fai(); + return b; + } + + async void ScaricaCopertina() + { + try + { + var dove = await Copertine.SalvaAccanto(Strumenti.Trova(), brani[i]); + Dice($"Salvata: {Path.GetFileName(dove)}"); + } + catch (Exception e) { Dice(e.Message); } + } + + async void ModificaCopertina() + { + var era = suona; + var n = i; + mp.Pause(); + Stato(false); + try + { + var esito = await FinestraCopertina.Mostra(this, brani[n]); + if (n != i || esito is null) { if (era && n == i) { mp.Play(); Stato(true); } return; } + if (esito.Dentro) + { + mp.Close(); + mp.Open(new Uri(brani[n])); + if (era) { mp.Play(); Stato(true); } + } + else if (era) { mp.Play(); Stato(true); } + if (esito.Immagine is not null) MostraCopertina(esito.Immagine); + if (!string.IsNullOrEmpty(esito.Nota)) Dice(esito.Nota); + } + catch (Exception e) + { + Dice(e.Message); + if (era && n == i) { try { mp.Play(); Stato(true); } catch { /* il file non si riapre: la nota basta */ } } + } + } + + void Dice(string testo) + { + notaSotto = sotto.Text; + sotto.Text = testo; + var giro = ++notaPer; + _ = Task.Delay(2400).ContinueWith(_ => Dispatcher.Invoke(() => + { + if (giro == notaPer && notaSotto is not null) { sotto.Text = notaSotto; notaSotto = null; } + })); } void Gira() { if (suona) { mp.Pause(); Stato(false); } else { mp.Play(); Stato(true); } } diff --git a/src/DaPConvertitore/BarraRegistrazione.cs b/src/DaPConvertitore/BarraRegistrazione.cs new file mode 100644 index 0000000..7a9a3cc --- /dev/null +++ b/src/DaPConvertitore/BarraRegistrazione.cs @@ -0,0 +1,199 @@ +using System.ComponentModel; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Shapes; +using System.Windows.Threading; + +namespace DaP.Convertitore.App; + +/// +/// La barretta mentre si registra: tempo, pausa, salva, annulla. Sta sopra a tutto e non entra nella cattura. +/// +public sealed class BarraRegistrazione : Window +{ + static BarraRegistrazione? aperta; + readonly TextBlock tempo; + readonly Button pausa; + readonly Ellipse punto; + readonly DispatcherTimer orologio; + Window? ancora; + bool chiusuraVoluta; + bool sistemo; + + public static void Mostra() + { + if (aperta is not null) { PortaDavanti(); return; } + try + { + aperta = new BarraRegistrazione(); + Registrazione.Escludi(aperta); + aperta.Closed += (_, _) => { if (aperta is not null) aperta = null; }; + aperta.Show(); + if (!aperta.IsVisible) Registro.Scrivi("registrazione: la barra non è visibile dopo Show()"); + } + catch (Exception e) + { + aperta = null; + Registro.Errore("registrazione: barra", e); + Vassoio.Dire("La barra della registrazione non si è aperta", e.Message); + } + } + + public static void Chiudi() + { + var f = aperta; + if (f is null) return; + aperta = null; + f.chiusuraVoluta = true; + f.Close(); + } + + public static void PortaDavanti() + { + if (aperta is null) Mostra(); + else + { + aperta.Topmost = true; + try { aperta.Activate(); } catch { /* già davanti */ } + } + } + + public static void Aggiorna() => aperta?.Rinfresca(); + + BarraRegistrazione() + { + // opaca, come il menu: una finestra trasparente esclusa dalla cattura su Windows 11 non si vede + WindowStyle = WindowStyle.None; + ResizeMode = ResizeMode.NoResize; + ShowInTaskbar = false; + ShowActivated = false; + Topmost = true; + SizeToContent = SizeToContent.WidthAndHeight; + Background = new SolidColorBrush(Color.FromRgb(0x12, 0x10, 0x18)); + Title = "Registrazione"; + MinWidth = 280; + + punto = new Ellipse { Width = 10, Height = 10, Fill = new SolidColorBrush(Color.FromRgb(0xff, 0x3d, 0x6e)), VerticalAlignment = VerticalAlignment.Center }; + tempo = new TextBlock + { + Text = "00:00", + Foreground = new SolidColorBrush(Color.FromRgb(0xff, 0xd5, 0x4a)), + FontFamily = new FontFamily("Consolas, Segoe UI"), + FontSize = 18, + FontWeight = FontWeights.Bold, + VerticalAlignment = VerticalAlignment.Center, + MinWidth = 64, + }; + pausa = Tasto("Pausa", "#3a3548", () => { if (Registrazione.InPausa) Registrazione.Riprendi(); else Registrazione.Pausa(); Rinfresca(); }); + var riga = new StackPanel { Orientation = Orientation.Horizontal, Margin = new Thickness(12, 8, 10, 8) }; + riga.Children.Add(punto); + riga.Children.Add(tempo); + tempo.Margin = new Thickness(8, 0, 12, 0); + riga.Children.Add(pausa); + riga.Children.Add(Tasto("Salva", "#1c9a62", Registrazione.Salva)); + riga.Children.Add(Tasto("Annulla", "#8a2a3c", Registrazione.Annulla)); + Content = new Border + { + Background = new SolidColorBrush(Color.FromRgb(0x12, 0x10, 0x18)), + BorderBrush = new SolidColorBrush(Color.FromRgb(0xff, 0xd5, 0x4a)), + BorderThickness = new Thickness(1), + Child = riga, + }; + MouseLeftButtonDown += (_, e) => + { + if (DentroTasto(e.OriginalSource)) return; + try { DragMove(); } catch { /* il tasto è già partito */ } + }; + + orologio = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(200) }; + orologio.Tick += (_, _) => Rinfresca(); + SourceInitialized += (_, _) => Sistema(false); + Loaded += (_, _) => + { + UpdateLayout(); + Aggancia(Registrazione.Ancora); + Sistema(true); + orologio.Start(); + Rinfresca(); + }; + Closed += (_, _) => + { + orologio.Stop(); + if (ancora is not null) ancora.LocationChanged -= Segui; + }; + } + + void Aggancia(Window? a) + { + if (ancora is not null) ancora.LocationChanged -= Segui; + ancora = a; + if (ancora is not null) ancora.LocationChanged += Segui; + } + + void Segui(object? sender, EventArgs e) => Sistema(false); + + void Sistema(bool scrivi) + { + if (sistemo) return; + sistemo = true; + try + { + UpdateLayout(); + var w = ActualWidth > 8 ? ActualWidth : 420; + var h = ActualHeight > 8 ? ActualHeight : 48; + PosizioneFinestre.Sistema(this, ancora ?? Registrazione.Ancora, w, h, scrivi); + } + finally { sistemo = false; } + } + + void Rinfresca() + { + tempo.Text = Registrazione.TestoTempo(); + var ferma = Registrazione.InPausa; + pausa.Content = ferma ? "Riprendi" : "Pausa"; + punto.Fill = new SolidColorBrush(ferma ? Color.FromRgb(0xa1, 0x9d, 0xb0) : Color.FromRgb(0xff, 0x3d, 0x6e)); + } + + protected override void OnClosing(CancelEventArgs e) + { + if (!chiusuraVoluta && Registrazione.Attiva) + { + e.Cancel = true; + Registrazione.Annulla(); + return; + } + base.OnClosing(e); + } + + static bool DentroTasto(object? o) + { + var d = o as DependencyObject; + while (d is not null) + { + if (d is Button) return true; + d = VisualTreeHelper.GetParent(d); + } + return false; + } + + static Button Tasto(string testo, string sfondo, Action fai) + { + var b = new Button + { + Content = testo, + Margin = new Thickness(4, 0, 0, 0), + Padding = new Thickness(12, 6, 12, 6), + Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString(sfondo)), + Foreground = Brushes.White, + BorderThickness = new Thickness(0), + FontFamily = new FontFamily("Segoe UI"), + FontWeight = FontWeights.Bold, + FontSize = 13, + Cursor = Cursors.Hand, + }; + b.Click += (_, _) => fai(); + return b; + } +} diff --git a/src/DaPConvertitore/CopertinaUi.cs b/src/DaPConvertitore/CopertinaUi.cs new file mode 100644 index 0000000..f23663d --- /dev/null +++ b/src/DaPConvertitore/CopertinaUi.cs @@ -0,0 +1,197 @@ +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using DaP.Convertitore.Lettore; +using Microsoft.Win32; + +namespace DaP.Convertitore.App; + +/// +/// La scelta della copertina, dal player sull'avatar: salvarla nella cartella, caricarne una, o prenderne una disegnata. +/// Sul lettore intero la stessa scelta sta nella pagina. +/// +public sealed class FinestraCopertina : Window +{ + readonly string audio; + readonly double? fotogramma; + readonly TaskCompletionSource fatto = new(); + readonly WrapPanel varianti = new() { Margin = new Thickness(0, 8, 0, 0) }; + bool chiuso; + + FinestraCopertina(string audio, double? fotogramma) + { + this.audio = audio; + this.fotogramma = fotogramma; + Title = "Copertina"; + WindowStyle = WindowStyle.None; + AllowsTransparency = true; + Background = Brushes.Transparent; + Topmost = true; + ShowInTaskbar = false; + ResizeMode = ResizeMode.NoResize; + SizeToContent = SizeToContent.WidthAndHeight; + Width = 440; + + var titolo = new TextBlock { Text = "Copertina", Foreground = Brushes.White, FontSize = 18, FontWeight = FontWeights.Bold }; + var video = Copertine.VideoNelFile(audio); + var nota = new TextBlock + { + Text = video + ? "MP4, MOV e MKV tengono la copertina dentro (è la miniatura). Gli altri: la salvo accanto. Se qualcosa va storto, il file resta com'è." + : "MP3, M4A e FLAC la tengono dentro il file. Gli altri: la salvo accanto, e l'originale resta com'è se qualcosa va storto.", + Foreground = Col("#a19db0"), FontSize = 12.5, TextWrapping = TextWrapping.Wrap, Margin = new Thickness(0, 6, 0, 12), + }; + var salva = Tasto("Salva nella cartella", true, () => _ = Salva()); + var carica = Tasto("Carica un'immagine", false, () => _ = Carica()); + var fila = new StackPanel { Orientation = Orientation.Horizontal }; + fila.Children.Add(salva); + fila.Children.Add(carica); + if (video && fotogramma is not null) + fila.Children.Add(Tasto("Questo fotogramma", false, () => _ = DalFotogramma(fotogramma.Value))); + var disegnate = new TextBlock { Text = "OPPURE UNA DISEGNATA", Foreground = Col("#ffd54a"), FontSize = 11, FontWeight = FontWeights.Bold, Margin = new Thickness(0, 14, 0, 0) }; + var chiudi = Tasto("Chiudi", false, () => Close()); + chiudi.HorizontalAlignment = HorizontalAlignment.Right; + chiudi.Margin = new Thickness(0, 12, 0, 0); + + var pila = new StackPanel { Margin = new Thickness(18, 16, 18, 16) }; + pila.Children.Add(titolo); + pila.Children.Add(nota); + pila.Children.Add(fila); + pila.Children.Add(disegnate); + pila.Children.Add(varianti); + pila.Children.Add(chiudi); + Content = new Border + { + CornerRadius = new CornerRadius(16), Margin = new Thickness(12), Child = pila, Width = 416, + Background = new SolidColorBrush(Color.FromArgb(242, 18, 16, 26)), + BorderBrush = new SolidColorBrush(Color.FromArgb(50, 255, 255, 255)), BorderThickness = new Thickness(1), + }; + Closed += (_, _) => { chiuso = true; fatto.TrySetResult(null); }; + PreviewKeyDown += (_, e) => { if (e.Key == Key.Escape) Close(); }; + Loaded += (_, _) => _ = Disegna(); + } + + public static Task Mostra(Window sopra, string audio, double? fotogramma = null) + { + var w = new FinestraCopertina(audio, fotogramma) { Owner = sopra }; + w.WindowStartupLocation = WindowStartupLocation.CenterOwner; + w.Show(); + return w.fatto.Task; + } + + async Task Disegna() + { + var nome = Path.GetFileNameWithoutExtension(audio); + for (var n = 0; n < Copertine.Quante; n++) + { + var variante = n; + byte[] png; + try { png = await Task.Run(() => Copertine.Genera(nome, variante, null)); } + catch { return; } + if (chiuso) return; + var img = Immagine(png); + var b = new Button { Width = 112, Height = 112, Margin = new Thickness(0, 0, 8, 8), Padding = new Thickness(0), Cursor = Cursors.Hand, ToolTip = "Usa questa" }; + var bordo = new Border { CornerRadius = new CornerRadius(10), Child = new Image { Source = img, Stretch = Stretch.UniformToFill } }; + b.Content = bordo; + b.Background = Brushes.Transparent; + b.BorderThickness = new Thickness(0); + b.Click += async (_, _) => + { + try { await Finisci(await Copertine.ApplicaGenerata(Strumenti.Trova(), audio, nome, variante)); } + catch (Exception e) { notaErrore(e.Message); } + }; + varianti.Children.Add(b); + } + } + + async Task Salva() + { + try + { + var dove = await Copertine.SalvaAccanto(Strumenti.Trova(), audio); + await Finisci(new EsitoCopertina(null, dove, false, "Salvata: " + Path.GetFileName(dove))); + } + catch (Exception e) { notaErrore(e.Message); } + } + + async Task Carica() + { + var d = new OpenFileDialog { Title = "Scegli la copertina", Filter = "Immagini|*.jpg;*.jpeg;*.png;*.webp;*.bmp;*.tif;*.tiff" }; + if (d.ShowDialog(this) != true) return; + try { await Finisci(await Copertine.Applica(Strumenti.Trova(), audio, d.FileName)); } + catch (Exception e) { notaErrore(e.Message); } + } + + async Task DalFotogramma(double secondo) + { + var tmp = Path.Combine(Strumenti.CartellaTemporanea, $"frame-{Guid.NewGuid():N}.png"); + try + { + var n = secondo.ToString("0.###", System.Globalization.CultureInfo.InvariantCulture); + var r = await Processi.Esegui(Strumenti.Trova().Ffmpeg, ["-hide_banner", "-loglevel", "error", "-y", "-ss", n, "-i", audio, "-frames:v", "1", tmp], CancellationToken.None, tieniUscita: false); + if (r.Codice != 0 || !File.Exists(tmp)) throw new ErroreConversione("Non ho preso il fotogramma.", r.Errori); + await Finisci(await Copertine.Applica(Strumenti.Trova(), audio, tmp)); + } + catch (Exception e) { notaErrore(e.Message); } + finally { try { File.Delete(tmp); } catch { } } + } + + Task Finisci(EsitoCopertina esito) + { + chiuso = true; + fatto.TrySetResult(esito); + Close(); + return Task.CompletedTask; + } + + void notaErrore(string testo) + { + if (Content is Border { Child: StackPanel p } && p.Children.Count > 1 && p.Children[1] is TextBlock t) + { + t.Text = testo; + t.Foreground = new SolidColorBrush(Color.FromRgb(0xff, 0xb3, 0xc1)); + } + } + + static BitmapImage Immagine(byte[] b) + { + var img = new BitmapImage(); + using var ms = new MemoryStream(b); + img.BeginInit(); + img.CacheOption = BitmapCacheOption.OnLoad; + img.StreamSource = ms; + img.EndInit(); + img.Freeze(); + return img; + } + + static SolidColorBrush Col(string c) => (SolidColorBrush)new BrushConverter().ConvertFromString(c)!; + + static Button Tasto(string testo, bool oro, Action fai) + { + var b = new Button + { + Content = new TextBlock + { + Text = testo, FontWeight = FontWeights.Bold, FontSize = 13, + Foreground = oro ? new SolidColorBrush(Color.FromRgb(0x1a, 0x14, 0x05)) : Brushes.White, + HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, + }, + Height = 32, Margin = new Thickness(0, 0, 8, 0), Padding = new Thickness(12, 0, 12, 0), + Cursor = Cursors.Hand, Focusable = false, BorderThickness = new Thickness(0), + Background = oro ? new SolidColorBrush(Color.FromRgb(0xff, 0xd5, 0x4a)) : new SolidColorBrush(Color.FromArgb(36, 255, 255, 255)), + }; + var t = new ControlTemplate(typeof(Button)); + var bordo = new FrameworkElementFactory(typeof(Border)); + bordo.SetValue(Border.CornerRadiusProperty, new CornerRadius(9)); + bordo.SetValue(Border.PaddingProperty, new Thickness(12, 0, 12, 0)); + bordo.SetBinding(Border.BackgroundProperty, new System.Windows.Data.Binding("Background") { RelativeSource = System.Windows.Data.RelativeSource.TemplatedParent }); + bordo.AppendChild(new FrameworkElementFactory(typeof(ContentPresenter))); + t.VisualTree = bordo; + b.Template = t; + b.Click += (_, _) => fai(); + return b; + } +} diff --git a/src/DaPConvertitore/DaPConvertitore.csproj b/src/DaPConvertitore/DaPConvertitore.csproj index 4eb8f79..d7a905f 100644 --- a/src/DaPConvertitore/DaPConvertitore.csproj +++ b/src/DaPConvertitore/DaPConvertitore.csproj @@ -4,6 +4,10 @@ WinExe true + + true + + $(NoWarn);WFO0003 DaPConvertitore DaP.Convertitore.App ..\..\risorse\icona.ico @@ -12,6 +16,11 @@ true + + + + + diff --git a/src/DaPConvertitore/Istanza.cs b/src/DaPConvertitore/Istanza.cs index bd5b5bd..e363d76 100644 --- a/src/DaPConvertitore/Istanza.cs +++ b/src/DaPConvertitore/Istanza.cs @@ -47,7 +47,11 @@ public static void Ascolta(Action arriva) using var r = new StreamReader(s); var testo = r.ReadToEnd(); var richiesta = JsonSerializer.Deserialize(testo); - if (richiesta is not null) arriva(richiesta); + if (richiesta is not null) + { + Registro.Scrivi($"istanza: arriva una richiesta da un altro processo (file {richiesta.Percorsi.Count}, azione {richiesta.Azione ?? "-"})"); + arriva(richiesta); + } } catch (Exception e) { Registro.Errore("istanza", e); Thread.Sleep(200); } } diff --git a/src/DaPConvertitore/LivelloAudio.cs b/src/DaPConvertitore/LivelloAudio.cs new file mode 100644 index 0000000..7b07ef5 --- /dev/null +++ b/src/DaPConvertitore/LivelloAudio.cs @@ -0,0 +1,158 @@ +using System.Runtime.InteropServices; + +namespace DaP.Convertitore.App; + +/// +/// Quanto è alto il microfono e l'audio del PC, adesso. È il misuratore di Windows (non un secondo FFmpeg, +/// che terrebbe il dispositivo occupato). Se il nome scelto non si trova, si usa quello di sistema. +/// Se la chiamata non riesce, il livello resta a zero e la registrazione va avanti lo stesso. +/// +public static class LivelloAudio +{ + static string? nomeMic, nomePc; + static IAudioMeterInformation? metroMic, metroPc; + static bool detto; + + public static float Microfono(string? nome) => Picco(ref nomeMic, ref metroMic, nome, cattura: true); + public static float Uscita(string? nome) => Picco(ref nomePc, ref metroPc, nome, cattura: false); + + static float Picco(ref string? tenuto, ref IAudioMeterInformation? metro, string? nome, bool cattura) + { + if (string.IsNullOrWhiteSpace(nome)) return 0; + try + { + if (tenuto != nome || metro is null) + { + if (metro is not null) try { Marshal.ReleaseComObject(metro); } catch { /* già lasciato */ } + metro = Apri(nome, cattura); + tenuto = nome; + } + if (metro is null) return 0; + metro.GetPeakValue(out var v); + return float.IsFinite(v) ? Math.Clamp(v, 0f, 1f) : 0; + } + catch (Exception e) + { + if (!detto) { detto = true; Registro.Scrivi($"registrazione: livello audio non letto ({e.Message})"); } + return 0; + } + } + + static IAudioMeterInformation? Apri(string nome, bool cattura) + { + var e = (IMMDeviceEnumerator)new MMDeviceEnumerator(); + try + { + var flusso = cattura ? 1 : 0; + e.EnumAudioEndpoints(flusso, 1, out var col); + try + { + col.GetCount(out var n); + for (var i = 0; i < n; i++) + { + col.Item(i, out var dev); + var friendly = Nome(dev); + var va = friendly is not null && (string.Equals(friendly, nome, StringComparison.OrdinalIgnoreCase) + || friendly.Contains(nome, StringComparison.OrdinalIgnoreCase) + || nome.Contains(friendly, StringComparison.OrdinalIgnoreCase)); + if (va && Attiva(dev) is { } m) return m; + try { Marshal.ReleaseComObject(dev); } catch { /* il metro lo tiene */ } + } + } + finally { try { Marshal.ReleaseComObject(col); } catch { /* già lasciato */ } } + e.GetDefaultAudioEndpoint(flusso, 0, out var def); + return Attiva(def); + } + finally { try { Marshal.ReleaseComObject(e); } catch { /* già lasciato */ } } + } + + static IAudioMeterInformation? Attiva(IMMDevice dev) + { + var iid = typeof(IAudioMeterInformation).GUID; + dev.Activate(ref iid, 23, IntPtr.Zero, out var metro); + return metro; + } + + static string? Nome(IMMDevice dev) + { + dev.OpenPropertyStore(0, out var store); + try + { + var chiave = new PROPERTYKEY { fmtid = new Guid("a45c254e-df1c-4efd-8020-67d146a850e0"), pid = 14 }; + store.GetValue(ref chiave, out var v); + try + { + if (v.vt != 31 || v.p == IntPtr.Zero) return null; + return Marshal.PtrToStringUni(v.p); + } + finally { PropVariantClear(ref v); } + } + finally { try { Marshal.ReleaseComObject(store); } catch { /* già lasciato */ } } + } + + [ComImport, Guid("BCDE0395-E52F-467C-8E3D-C4579291692E")] + class MMDeviceEnumerator { } + + [ComImport, Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + interface IMMDeviceEnumerator + { + void EnumAudioEndpoints(int dataFlow, int stateMask, out IMMDeviceCollection devices); + void GetDefaultAudioEndpoint(int dataFlow, int role, out IMMDevice device); + void GetDevice([MarshalAs(UnmanagedType.LPWStr)] string id, out IMMDevice device); + void RegisterEndpointNotificationCallback(IntPtr client); + void UnregisterEndpointNotificationCallback(IntPtr client); + } + + [ComImport, Guid("0BD7A1BE-7A1A-44DB-8397-CC5392387B5E"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + interface IMMDeviceCollection + { + void GetCount(out int n); + void Item(int i, out IMMDevice device); + } + + [ComImport, Guid("D666063F-1587-4E43-81F1-B948E807363F"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + interface IMMDevice + { + void Activate(ref Guid iid, int clsCtx, IntPtr activation, out IAudioMeterInformation meter); + void OpenPropertyStore(int access, out IPropertyStore store); + void GetId([MarshalAs(UnmanagedType.LPWStr)] out string id); + void GetState(out int state); + } + + [ComImport, Guid("886d8eeb-8cf2-4446-8d02-cdba1dbdcf99"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + interface IPropertyStore + { + void GetCount(out int n); + void GetAt(int i, out PROPERTYKEY key); + void GetValue(ref PROPERTYKEY key, out PROPVARIANT value); + void SetValue(ref PROPERTYKEY key, ref PROPVARIANT value); + void Commit(); + } + + [ComImport, Guid("C02216F6-8C67-4B5B-9D00-D008E73E0064"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + interface IAudioMeterInformation + { + void GetPeakValue(out float peak); + void GetMeterChannelCount(out int n); + void GetChannelsPeakValues(int n, IntPtr peaks); + void QueryHardwareSupport(out int mask); + } + + [StructLayout(LayoutKind.Sequential)] + struct PROPERTYKEY + { + public Guid fmtid; + public int pid; + } + + [StructLayout(LayoutKind.Sequential)] + struct PROPVARIANT + { + public ushort vt; + public ushort w1, w2, w3; + public IntPtr p; + public int extra; + } + + [DllImport("ole32.dll")] static extern int PropVariantClear(ref PROPVARIANT p); +} diff --git a/src/DaPConvertitore/MenuRegistrazione.cs b/src/DaPConvertitore/MenuRegistrazione.cs new file mode 100644 index 0000000..3fa7919 --- /dev/null +++ b/src/DaPConvertitore/MenuRegistrazione.cs @@ -0,0 +1,652 @@ +using System.ComponentModel; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Threading; + +namespace DaP.Convertitore.App; + +/// +/// La finestra di registrazione: l'anteprima dello schermo, i tasti e le impostazioni. +/// Sta accanto all'avatar (o al centro del monitor principale) e lo segue se si sposta. +/// È esclusa dalla cattura, quindi non entra nel video e non fa da specchio. +/// +public sealed class MenuRegistrazione : Window +{ + const double MisuraL = 400; + const double MisuraA = 680; + + static MenuRegistrazione? aperta; + readonly Image quadro = new() { Stretch = Stretch.Uniform }; + readonly TextBlock soloAudioTesto; + readonly TextBlock contoTesto; + readonly TextBlock tempo; + readonly TextBlock nota; + readonly TextBlock chiudiTesto; + readonly ComboBox monitor = Combo(); + readonly ComboBox microfono = Combo(); + readonly ComboBox uscita = Combo(); + readonly ComboBox finestre = Combo(); + readonly StackPanel impostazioni = new(); + readonly Border barraMic = BarraLivello(); + readonly Border barraPc = BarraLivello(); + readonly Button avvia, pausa, salva, annulla; + readonly Button areaIntero, areaZona, areaFinestra, fps30, fps60, qLeggera, qBuona, qAlta; + readonly CheckBox cursore, conto, solo; + readonly AnteprimaSchermo anteprima; + readonly DispatcherTimer orologio; + Window? ancora; + Ancoraggio.Riquadro? zona; + string area = "intero"; + string qualita = "buona"; + bool blocco = true; + bool sistemo; + int fps = 30; + + public static bool Visibile => aperta is { IsVisible: true }; + + public static void Mostra(Window? accanto, string da) + { + if (Registrazione.Attiva) { PortaDavanti(); return; } + if (aperta is not null) + { + aperta.Aggancia(accanto); + aperta.Show(); + aperta.Activate(); + Registro.Scrivi("registrazione: la finestra era già aperta, la porto davanti"); + return; + } + try + { + aperta = new MenuRegistrazione(accanto, da); + Registrazione.Escludi(aperta); + aperta.Closed += (_, _) => { Registro.Scrivi("registrazione: finestra chiusa"); aperta = null; }; + aperta.Show(); + aperta.Activate(); + aperta.Topmost = true; + if (!aperta.IsVisible) Registro.Scrivi("registrazione: Show() è tornato ma la finestra non è visibile"); + } + catch (Exception e) + { + aperta = null; + Registro.Errore("registrazione: finestra", e); + Vassoio.Dire("Registra non si è aperto", e.Message); + } + } + + public static void PortaDavanti() + { + if (aperta is null) { BarraRegistrazione.PortaDavanti(); return; } + BarraRegistrazione.Chiudi(); + aperta.Show(); + aperta.Posiziona(true); + aperta.Topmost = true; + try { aperta.Activate(); } catch { /* già davanti */ } + } + + public static void Aggiorna() => aperta?.Rinfresca(); + + MenuRegistrazione(Window? accanto, string da) + { + WindowStyle = WindowStyle.None; + ResizeMode = ResizeMode.NoResize; + ShowInTaskbar = false; + Topmost = true; + ShowActivated = true; + WindowStartupLocation = WindowStartupLocation.Manual; + Width = MisuraL; + Height = MisuraA; + Background = Sfondo(); + Title = "Registra"; + + soloAudioTesto = new TextBlock + { + Text = "Solo audio", + Foreground = Pennello("#ffd54a"), + FontSize = 18, + FontWeight = FontWeights.Bold, + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Center, + Visibility = Visibility.Collapsed, + }; + contoTesto = new TextBlock + { + Foreground = Pennello("#ffd54a"), + FontSize = 64, + FontWeight = FontWeights.Bold, + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Center, + Visibility = Visibility.Collapsed, + }; + var palco = new Grid { Height = 200, Background = Brushes.Black, Margin = new Thickness(0, 6, 0, 6) }; + palco.Children.Add(quadro); + palco.Children.Add(soloAudioTesto); + palco.Children.Add(contoTesto); + anteprima = new AnteprimaSchermo(quadro); + + tempo = new TextBlock { Text = "00:00", Foreground = Pennello("#ffd54a"), FontFamily = new FontFamily("Consolas"), FontSize = 18, FontWeight = FontWeights.Bold, VerticalAlignment = VerticalAlignment.Center, MinWidth = 58 }; + var rigaTempo = new StackPanel { Orientation = Orientation.Horizontal, Margin = new Thickness(0, 0, 0, 6) }; + rigaTempo.Children.Add(tempo); + rigaTempo.Children.Add(EtichettaLivello("Mic", barraMic)); + rigaTempo.Children.Add(EtichettaLivello("PC", barraPc)); + + avvia = Tasto("Avvia", "#ff3df2", () => _ = Parti()); + pausa = Tasto("Pausa", "#3a3548", () => { if (Registrazione.InPausa) Registrazione.Riprendi(); else Registrazione.Pausa(); Rinfresca(); }); + salva = Tasto("Salva", "#1c9a62", Registrazione.Salva); + annulla = Tasto("Annulla", "#8a2a3c", Registrazione.Annulla); + pausa.Visibility = Visibility.Collapsed; + var rigaTasti = new WrapPanel { Margin = new Thickness(0, 0, 0, 8) }; + foreach (var b in new[] { avvia, pausa, salva, annulla }) { b.Margin = new Thickness(0, 0, 6, 6); rigaTasti.Children.Add(b); } + + areaIntero = Mini("Intero", () => ScegliArea("intero")); + areaZona = Mini("Zona", () => ScegliArea("zona")); + areaFinestra = Mini("Finestra", () => ScegliArea("finestra")); + var scegliZona = Mini("Scegli la zona", () => _ = PrendiZona()); + fps30 = Mini("30", () => ScegliFps(30)); + fps60 = Mini("60", () => ScegliFps(60)); + qLeggera = Mini("Leggera", () => ScegliQualita("leggera")); + qBuona = Mini("Buona", () => ScegliQualita("buona")); + qAlta = Mini("Alta", () => ScegliQualita("alta")); + cursore = Spunta("Mostra il cursore"); + conto = Spunta("Conto alla rovescia"); + solo = Spunta("Solo audio"); + + var pila = new StackPanel { Margin = new Thickness(14, 12, 14, 14) }; + var testa = new DockPanel { Margin = new Thickness(0, 0, 0, 4) }; + var titolo = new TextBlock { Text = "REGISTRA", Foreground = Pennello("#ffd54a"), FontWeight = FontWeights.Bold, FontSize = 13, FontFamily = new FontFamily("Segoe UI") }; + chiudiTesto = new TextBlock { Text = "Chiudi", Foreground = Pennello("#a19db0"), FontSize = 12, Cursor = Cursors.Hand, HorizontalAlignment = HorizontalAlignment.Right }; + chiudiTesto.MouseLeftButtonUp += (_, _) => ChiudiORiduci(); + DockPanel.SetDock(chiudiTesto, Dock.Right); + testa.Children.Add(chiudiTesto); + testa.Children.Add(titolo); + pila.Children.Add(testa); + pila.Children.Add(palco); + pila.Children.Add(rigaTempo); + pila.Children.Add(rigaTasti); + + impostazioni.Children.Add(Etichetta("MONITOR")); + impostazioni.Children.Add(monitor); + impostazioni.Children.Add(Etichetta("AREA")); + impostazioni.Children.Add(Riga(areaIntero, areaZona, areaFinestra, scegliZona)); + impostazioni.Children.Add(finestre); + impostazioni.Children.Add(Etichetta("FOTOGRAMMI E QUALITÀ")); + impostazioni.Children.Add(Riga(fps30, fps60, qLeggera, qBuona, qAlta)); + impostazioni.Children.Add(Etichetta("MICROFONO")); + impostazioni.Children.Add(microfono); + impostazioni.Children.Add(Etichetta("AUDIO DEL PC")); + impostazioni.Children.Add(uscita); + impostazioni.Children.Add(cursore); + impostazioni.Children.Add(conto); + impostazioni.Children.Add(solo); + pila.Children.Add(impostazioni); + nota = new TextBlock + { + Text = "Cerco microfoni e l'audio del PC…", + Foreground = Pennello("#a19db0"), + FontSize = 12, + TextWrapping = TextWrapping.Wrap, + Margin = new Thickness(0, 8, 0, 0), + }; + pila.Children.Add(nota); + pila.Children.Add(new TextBlock + { + Text = "Questa finestra non entra nel video. Nell'anteprima, dove sta lei, si vede un buco: non è lo specchio.", + Foreground = Pennello("#6e6a7a"), + FontSize = 11, + TextWrapping = TextWrapping.Wrap, + Margin = new Thickness(0, 6, 0, 0), + }); + Content = new Border + { + Background = Sfondo(), + BorderBrush = Pennello("#ffd54a"), + BorderThickness = new Thickness(1), + Child = new ScrollViewer { Content = pila, VerticalScrollBarVisibility = ScrollBarVisibility.Auto }, + }; + + monitor.SelectionChanged += (_, _) => { if (!blocco) { Ricorda(); AggiornaAnteprima(); } }; + microfono.SelectionChanged += (_, _) => Ricorda(); + uscita.SelectionChanged += (_, _) => Ricorda(); + finestre.SelectionChanged += (_, _) => Ricorda(); + cursore.Checked += (_, _) => Ricorda(); + cursore.Unchecked += (_, _) => Ricorda(); + conto.Checked += (_, _) => Ricorda(); + conto.Unchecked += (_, _) => Ricorda(); + solo.Checked += (_, _) => { if (!blocco) { Ricorda(); AggiornaAnteprima(); } }; + solo.Unchecked += (_, _) => { if (!blocco) { Ricorda(); AggiornaAnteprima(); } }; + PreviewKeyDown += (_, e) => { if (e.Key == Key.Escape) ChiudiORiduci(); }; + + orologio = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(200) }; + orologio.Tick += (_, _) => { if (Registrazione.Attiva || Registrazione.InPausa) tempo.Text = Registrazione.TestoTempo(); Livelli(); }; + SourceInitialized += (_, _) => Posiziona(false); + ContentRendered += (_, _) => + { + Posiziona(true); + Registro.Scrivi($"registrazione: finestra aperta da {da}"); + }; + Loaded += async (_, _) => + { + orologio.Start(); + RiempiMonitori(); + RiempiFinestre(); + ApplicaSalvato(); + blocco = false; + SegnaTutto(); + AggiornaAnteprima(); + Rinfresca(); + DispositiviAudio d; + try { d = await Task.Run(Registrazione.Elenca); } + catch (Exception e) + { + Registro.Errore("registrazione: dispositivi", e); + nota.Text = e.Message; + return; + } + if (!IsLoaded) return; + blocco = true; + var imp = Impostazioni.Comune; + RiempiAudio(microfono, d.Microfoni, imp.RegistrazioneMic); + RiempiAudio(uscita, d.Uscite, imp.RegistrazionePc); + blocco = false; + nota.Text = d.Microfoni.Count == 0 && d.Uscite.Count == 0 + ? "Non vedo dispositivi. Il microfono arriva da DirectShow, l'audio del PC da WASAPI." + : "Scegli e premi Avvia. La scelta resta per la prossima volta."; + }; + Closed += (_, _) => + { + orologio.Stop(); + anteprima.Dispose(); + if (ancora is not null) ancora.LocationChanged -= Segui; + }; + Aggancia(accanto); + } + + async Task Parti() + { + var modo = ModoScelto(); + var mic = Valore(microfono); + var pc = Valore(uscita); + var titolo = Valore(finestre); + var perche = ComandiRegistrazione.MotivoRifiuto(modo, mic, pc, zona is null, string.IsNullOrWhiteSpace(titolo)); + if (perche is not null) { nota.Text = perche; Registro.Scrivi("registrazione: " + perche); return; } + avvia.IsEnabled = false; + if (conto.IsChecked == true && modo != "audio") + { + for (var n = 3; n >= 1 && IsVisible; n--) + { + contoTesto.Text = n.ToString(); + contoTesto.Visibility = Visibility.Visible; + await Task.Delay(1000); + } + if (!IsVisible || !IsLoaded) return; + contoTesto.Visibility = Visibility.Collapsed; + } + ComandiRegistrazione.Schermo? schermo = null; + if (modo == "zona" && zona is { } z) schermo = new(z.X, z.Y, z.L, z.A); + else if (modo == "intero") { var m = MonitorScelto(); schermo = new(m.X, m.Y, m.L, m.A); } + var modoFf = modo == "audio" ? "audio" : modo == "finestra" ? "finestra" : "schermo"; + Registro.Scrivi($"registrazione: scelto {modoFf}, mic «{mic ?? "no"}», pc «{pc ?? "no"}», {fps} fps"); + var ok = Registrazione.Inizia(modoFf, mic, pc, schermo, fps, ComandiRegistrazione.CrfDi(qualita), cursore.IsChecked == true, titolo); + if (!ok) nota.Text = "Non è partita. Il motivo è nel registro."; + Rinfresca(); + AggiornaAnteprima(); + } + + string ModoScelto() => solo.IsChecked == true ? "audio" : area; + + void ScegliArea(string quale) + { + area = quale; + finestre.Visibility = quale == "finestra" ? Visibility.Visible : Visibility.Collapsed; + SegnaTutto(); + Ricorda(); + AggiornaAnteprima(); + if (quale == "finestra") RiempiFinestre(); + } + + async Task PrendiZona() + { + var m = MonitorScelto(); + nota.Text = "Trascina la zona sul monitor. Esc annulla."; + Hide(); + Ancoraggio.Riquadro? presa; + try { presa = await SceltaZona.Chiedi(m); } + finally { Show(); Posiziona(false); try { Activate(); } catch { /* già chiusa */ } } + if (presa is { } r && Ancoraggio.Tocca(r, m)) + { + zona = Ancoraggio.Blocca(r, m); + ScegliArea("zona"); + nota.Text = $"Zona {zona.Value.L}×{zona.Value.A}."; + Registro.Scrivi($"registrazione: zona {Ancoraggio.Chiave(zona.Value)}"); + } + } + + void ScegliFps(int n) { fps = n; SegnaTutto(); Ricorda(); } + void ScegliQualita(string q) { qualita = q; SegnaTutto(); Ricorda(); } + + void AggiornaAnteprima() + { + var audio = solo.IsChecked == true; + soloAudioTesto.Visibility = audio ? Visibility.Visible : Visibility.Collapsed; + if (audio) { anteprima.Ferma(); quadro.Source = null; return; } + Ancoraggio.Riquadro r = area == "zona" && zona is { } z ? z + : area == "finestra" && Valore(finestre) is { } titolo && RettangoloDi(titolo) is { } fr ? fr + : MonitorScelto(); + anteprima.Guarda(r.X, r.Y, r.L, r.A); + } + + void Rinfresca() + { + var on = Registrazione.Attiva; + avvia.Visibility = on ? Visibility.Collapsed : Visibility.Visible; + avvia.IsEnabled = !on; + pausa.Visibility = on ? Visibility.Visible : Visibility.Collapsed; + salva.IsEnabled = on; + annulla.IsEnabled = on; + pausa.Content = Registrazione.InPausa ? "Riprendi" : "Pausa"; + tempo.Text = Registrazione.TestoTempo(); + impostazioni.IsEnabled = !on; + chiudiTesto.Text = on ? "Riduci" : "Chiudi"; + } + + void Livelli() + { + barraMic.Width = 72 * LivelloAudio.Microfono(Valore(microfono)); + barraPc.Width = 72 * LivelloAudio.Uscita(Valore(uscita)); + } + + void ChiudiORiduci() + { + if (Registrazione.Attiva) { Hide(); BarraRegistrazione.Mostra(); return; } + Close(); + } + + void Aggancia(Window? a) + { + if (ancora is not null) ancora.LocationChanged -= Segui; + ancora = a; + if (ancora is not null) ancora.LocationChanged += Segui; + Posiziona(false); + } + + void Segui(object? sender, EventArgs e) => Posiziona(false); + + void Posiziona(bool scrivi) + { + if (sistemo) return; + sistemo = true; + try { PosizioneFinestre.Sistema(this, ancora, MisuraL, MisuraA, scrivi); } + finally { sistemo = false; } + } + + void RiempiMonitori() + { + monitor.Items.Clear(); + try + { + var n = 1; + foreach (var s in System.Windows.Forms.Screen.AllScreens) + { + var b = s.Bounds; + var nome = s.Primary ? "Principale" : $"Monitor {n++}"; + monitor.Items.Add(new ComboBoxItem + { + Content = $"{nome} · {b.Width}×{b.Height}", + Tag = new Ancoraggio.Riquadro(b.X, b.Y, b.Width, b.Height), + }); + } + } + catch (Exception e) { Registro.Scrivi($"registrazione: monitor ({e.Message})"); } + if (monitor.Items.Count == 0) + monitor.Items.Add(new ComboBoxItem { Content = "Schermo", Tag = new Ancoraggio.Riquadro(0, 0, 1920, 1080) }); + monitor.SelectedIndex = 0; + } + + Ancoraggio.Riquadro MonitorScelto() => + monitor.SelectedItem is ComboBoxItem { Tag: Ancoraggio.Riquadro r } ? r : new Ancoraggio.Riquadro(0, 0, 1920, 1080); + + void RiempiFinestre() + { + var scelto = Valore(finestre); + finestre.Items.Clear(); + finestre.Items.Add(new ComboBoxItem { Content = "Scegli una finestra", Tag = "" }); + foreach (var t in ComandiRegistrazione.TitoliUtili(TitoliAperti())) + finestre.Items.Add(new ComboBoxItem { Content = t, Tag = t }); + var trovato = finestre.Items.OfType().FirstOrDefault(i => (string?)i.Tag == scelto); + finestre.SelectedItem = trovato ?? finestre.Items[0]; + finestre.Visibility = area == "finestra" ? Visibility.Visible : Visibility.Collapsed; + } + + static IEnumerable TitoliAperti() + { + var lista = new List(); + try + { + EnumWindows((h, _) => + { + if (!IsWindowVisible(h)) return true; + var n = GetWindowTextLength(h); + if (n <= 0) return true; + var sb = new System.Text.StringBuilder(n + 1); + GetWindowText(h, sb, sb.Capacity); + lista.Add(sb.ToString()); + return true; + }, IntPtr.Zero); + } + catch (Exception e) { Registro.Scrivi($"registrazione: finestre ({e.Message})"); } + return lista; + } + + void ApplicaSalvato() + { + var imp = Impostazioni.Comune; + area = imp.RegistrazioneArea is "zona" or "finestra" ? imp.RegistrazioneArea : "intero"; + fps = ComandiRegistrazione.FpsDi(imp.RegistrazioneFps ?? 30); + qualita = imp.RegistrazioneQualita is "alta" or "leggera" ? imp.RegistrazioneQualita : "buona"; + cursore.IsChecked = imp.RegistrazioneCursore; + conto.IsChecked = imp.RegistrazioneConto; + solo.IsChecked = false; + if (Ancoraggio.ProvaChiave(imp.RegistrazioneMonitor, out var voluto)) + { + var i = monitor.Items.OfType().FirstOrDefault(x => x.Tag is Ancoraggio.Riquadro r && r.X == voluto.X && r.Y == voluto.Y); + if (i is not null) monitor.SelectedItem = i; + } + if (Ancoraggio.ProvaChiave(imp.RegistrazioneZona, out var z) && Ancoraggio.Tocca(z, MonitorScelto())) zona = z; + else if (area == "zona") area = "intero"; + if (!string.IsNullOrWhiteSpace(imp.RegistrazioneFinestra)) + { + var i = finestre.Items.OfType().FirstOrDefault(x => (string?)x.Tag == imp.RegistrazioneFinestra); + if (i is not null) finestre.SelectedItem = i; + } + finestre.Visibility = area == "finestra" ? Visibility.Visible : Visibility.Collapsed; + } + + void Ricorda() + { + if (blocco || !IsLoaded) return; + var imp = Impostazioni.Comune; + imp.RegistrazioneMic = Valore(microfono) ?? ""; + imp.RegistrazionePc = Valore(uscita) ?? ""; + imp.RegistrazioneArea = area; + imp.RegistrazioneFps = fps; + imp.RegistrazioneQualita = qualita; + imp.RegistrazioneCursore = cursore.IsChecked == true; + imp.RegistrazioneConto = conto.IsChecked == true; + imp.RegistrazioneMonitor = Ancoraggio.Chiave(MonitorScelto()); + imp.RegistrazioneZona = zona is { } z ? Ancoraggio.Chiave(z) : null; + imp.RegistrazioneFinestra = Valore(finestre); + imp.Salva(); + } + + void SegnaTutto() + { + Segna(areaIntero, area == "intero"); + Segna(areaZona, area == "zona"); + Segna(areaFinestra, area == "finestra"); + Segna(fps30, fps == 30); + Segna(fps60, fps == 60); + Segna(qLeggera, qualita == "leggera"); + Segna(qBuona, qualita == "buona"); + Segna(qAlta, qualita == "alta"); + } + + protected override void OnClosing(CancelEventArgs e) + { + if (Registrazione.Attiva) + { + e.Cancel = true; + Hide(); + BarraRegistrazione.Mostra(); + return; + } + base.OnClosing(e); + } + + /// Il rettangolo della finestra con quel titolo, in pixel veri. Serve all'anteprima. + static Ancoraggio.Riquadro? RettangoloDi(string titolo) + { + Ancoraggio.Riquadro? trovato = null; + try + { + EnumWindows((h, _) => + { + if (!IsWindowVisible(h)) return true; + var n = GetWindowTextLength(h); + if (n <= 0) return true; + var sb = new System.Text.StringBuilder(n + 1); + GetWindowText(h, sb, sb.Capacity); + if (!string.Equals(sb.ToString().Trim(), titolo, StringComparison.Ordinal)) return true; + if (GetWindowRect(h, out var r)) + trovato = new Ancoraggio.Riquadro(r.Left, r.Top, Math.Max(1, r.Right - r.Left), Math.Max(1, r.Bottom - r.Top)); + return false; + }, IntPtr.Zero); + } + catch { /* senza il rettangolo si vede il monitor intero */ } + return trovato; + } + + static void RiempiAudio(ComboBox combo, IReadOnlyList nomi, string? salvato) + { + combo.Items.Clear(); + combo.Items.Add(new ComboBoxItem { Content = "Nessuno", Tag = "" }); + foreach (var n in nomi) combo.Items.Add(new ComboBoxItem { Content = n, Tag = n }); + ComboBoxItem? scelto = null; + if (salvato == "") scelto = (ComboBoxItem)combo.Items[0]!; + else if (!string.IsNullOrEmpty(salvato)) + scelto = combo.Items.OfType().FirstOrDefault(i => (string?)i.Tag == salvato); + combo.SelectedItem = scelto ?? (nomi.Count > 0 ? combo.Items[1] : combo.Items[0]); + } + + static string? Valore(ComboBox combo) + { + var t = (combo.SelectedItem as ComboBoxItem)?.Tag as string; + return string.IsNullOrEmpty(t) ? null : t; + } + + static ComboBox Combo() => new() + { + Margin = new Thickness(0, 2, 0, 6), + FontSize = 13, + Background = Brushes.White, + Foreground = Brushes.Black, + MaxDropDownHeight = 220, + }; + + static TextBlock Etichetta(string testo) => new() + { + Text = testo, + Foreground = Pennello("#ffd54a"), + FontSize = 10.5, + FontWeight = FontWeights.Bold, + Margin = new Thickness(0, 6, 0, 0), + }; + + static StackPanel EtichettaLivello(string nome, Border barra) + { + var pista = new Border + { + Width = 72, Height = 6, Margin = new Thickness(8, 0, 0, 0), + Background = Pennello("#2a2636"), CornerRadius = new CornerRadius(3), + VerticalAlignment = VerticalAlignment.Center, Child = barra, ClipToBounds = true, + }; + var riga = new StackPanel { Orientation = Orientation.Horizontal, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(8, 0, 0, 0) }; + riga.Children.Add(new TextBlock { Text = nome, Foreground = Pennello("#a19db0"), FontSize = 11, VerticalAlignment = VerticalAlignment.Center }); + riga.Children.Add(pista); + return riga; + } + + static Border BarraLivello() => new() + { + Width = 0, Height = 6, HorizontalAlignment = HorizontalAlignment.Left, + Background = Pennello("#ffd54a"), CornerRadius = new CornerRadius(3), + }; + + static WrapPanel Riga(params UIElement[] figli) + { + var r = new WrapPanel { Margin = new Thickness(0, 2, 0, 4) }; + foreach (var f in figli) r.Children.Add(f); + return r; + } + + static Button Mini(string testo, Action fai) + { + var b = new Button + { + Content = testo, + Margin = new Thickness(0, 0, 6, 4), + Padding = new Thickness(8, 4, 8, 4), + FontSize = 12.5, + FontWeight = FontWeights.Bold, + Foreground = Brushes.White, + Background = Pennello("#2a2636"), + BorderThickness = new Thickness(0), + Cursor = Cursors.Hand, + }; + b.Click += (_, _) => fai(); + return b; + } + + static void Segna(Button b, bool su) + { + b.Background = su ? Pennello("#ffd54a") : Pennello("#2a2636"); + b.Foreground = su ? Pennello("#1a1408") : Brushes.White; + } + + static Button Tasto(string testo, string sfondo, Action fai) + { + var b = new Button + { + Content = testo, + Padding = new Thickness(12, 6, 12, 6), + Background = Pennello(sfondo), + Foreground = Brushes.White, + BorderThickness = new Thickness(0), + FontWeight = FontWeights.Bold, + FontSize = 13, + Cursor = Cursors.Hand, + }; + b.Click += (_, _) => fai(); + return b; + } + + static CheckBox Spunta(string testo) => new() + { + Content = testo, + Foreground = Pennello("#f4f0e6"), + FontSize = 13, + Margin = new Thickness(0, 3, 0, 0), + }; + + static SolidColorBrush Sfondo() => new(Color.FromRgb(0x12, 0x10, 0x1a)); + static SolidColorBrush Pennello(string hex) => new((Color)ColorConverter.ConvertFromString(hex)); + + delegate bool EnumProc(IntPtr h, IntPtr l); + [System.Runtime.InteropServices.DllImport("user32.dll")] static extern bool GetWindowRect(IntPtr h, out RETT r); + [System.Runtime.InteropServices.DllImport("user32.dll")] static extern bool EnumWindows(EnumProc f, IntPtr l); + [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)] + struct RETT { public int Left, Top, Right, Bottom; } + [System.Runtime.InteropServices.DllImport("user32.dll")] static extern bool IsWindowVisible(IntPtr h); + [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] static extern int GetWindowText(IntPtr h, System.Text.StringBuilder s, int n); + [System.Runtime.InteropServices.DllImport("user32.dll")] static extern int GetWindowTextLength(IntPtr h); +} diff --git a/src/DaPConvertitore/MiniVideo.cs b/src/DaPConvertitore/MiniVideo.cs new file mode 100644 index 0000000..fb680db --- /dev/null +++ b/src/DaPConvertitore/MiniVideo.cs @@ -0,0 +1,181 @@ +using System.Windows; +using System.Windows.Controls; +using DaP.Convertitore.Lettore; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Threading; + +namespace DaP.Convertitore.App; + +/// +/// Il video sull'avatar, come la musica: parte subito, senza aprire l'app. Se Windows non lo sa suonare, lo apre il lettore. +/// +public sealed class MiniVideo : Window +{ + readonly MediaElement film = new() { LoadedBehavior = MediaState.Manual, UnloadedBehavior = MediaState.Manual, Stretch = Stretch.Uniform }; + readonly IReadOnlyList file; + readonly FinestraAvatar avatar; + readonly TextBlock titolo = new() { Foreground = Brushes.White, FontWeight = FontWeights.Bold, FontSize = 14, TextTrimming = TextTrimming.CharacterEllipsis }; + readonly Border riempimento = new() + { + Background = new LinearGradientBrush(Color.FromRgb(0xff, 0xd5, 0x4a), Color.FromRgb(0xff, 0x3d, 0xf2), 0), + Height = 6, CornerRadius = new CornerRadius(3), HorizontalAlignment = HorizontalAlignment.Left, Width = 0, IsHitTestVisible = false, + }; + readonly Grid barra = new() { Height = 18, Cursor = Cursors.Hand, Margin = new Thickness(0, 8, 0, 0) }; + readonly Button play; + readonly DispatcherTimer orologio; + int i; + bool suona = true; + + public event Action? StatoCambiato; + + public MiniVideo(IReadOnlyList file, FinestraAvatar avatar) + { + this.file = file; + this.avatar = avatar; + WindowStyle = WindowStyle.None; + AllowsTransparency = true; + Background = Brushes.Transparent; + Topmost = true; + ShowInTaskbar = false; + ShowActivated = false; + ResizeMode = ResizeMode.NoResize; + Width = 420; + SizeToContent = SizeToContent.Height; + + film.Width = 384; + film.Height = 216; + film.MediaEnded += (_, _) => { if (i + 1 < file.Count) Vai(i + 1); else Close(); }; + film.MediaFailed += (_, _) => + { + Regia.Gestisci(new Richiesta(null, [file[i]], false, true)); + Close(); + }; + + barra.Children.Add(new Border { Height = 6, CornerRadius = new CornerRadius(3), Background = new SolidColorBrush(Color.FromArgb(46, 255, 255, 255)), VerticalAlignment = VerticalAlignment.Center, IsHitTestVisible = false }); + barra.Children.Add(riempimento); + void Cerca(MouseEventArgs e) + { + if (!film.NaturalDuration.HasTimeSpan) return; + var f = Math.Clamp(e.GetPosition(barra).X / Math.Max(1, barra.ActualWidth), 0, 1); + film.Position = TimeSpan.FromSeconds(film.NaturalDuration.TimeSpan.TotalSeconds * f); + Aggiorna(); + } + barra.MouseLeftButtonDown += (_, e) => { barra.CaptureMouse(); Cerca(e); }; + barra.MouseMove += (_, e) => { if (barra.IsMouseCaptured) Cerca(e); }; + barra.MouseLeftButtonUp += (_, _) => barra.ReleaseMouseCapture(); + + var riquadro = new Grid { Width = 384, Height = 216 }; + riquadro.Children.Add(new Border { Background = Brushes.Black, CornerRadius = new CornerRadius(12), Child = film, ClipToBounds = true }); + var sopra = new StackPanel { Orientation = Orientation.Horizontal, HorizontalAlignment = HorizontalAlignment.Center }; + sopra.Children.Add(Tasto("Modifica", () => _ = Modifica())); + sopra.Children.Add(Tasto("Download", () => _ = Scarica())); + var velo = new Border + { + Background = new SolidColorBrush(Color.FromArgb(170, 8, 6, 14)), + VerticalAlignment = VerticalAlignment.Bottom, Height = 42, Child = sopra, Visibility = Visibility.Collapsed, + }; + riquadro.Children.Add(velo); + riquadro.MouseEnter += (_, _) => velo.Visibility = Visibility.Visible; + riquadro.MouseLeave += (_, _) => velo.Visibility = Visibility.Collapsed; + + play = Tasto("Pausa", Gira, oro: true); + var chiudi = Tasto("Chiudi", Close); + var tasti = new StackPanel { Orientation = Orientation.Horizontal, HorizontalAlignment = HorizontalAlignment.Center, Margin = new Thickness(0, 8, 0, 0) }; + tasti.Children.Add(Tasto("Apri nel lettore", () => { film.Pause(); Regia.Gestisci(new Richiesta(null, [file[i]], false, true)); Close(); })); + if (file.Count > 1) tasti.Children.Add(Tasto("Prima", () => Vai(i - 1))); + tasti.Children.Add(play); + if (file.Count > 1) tasti.Children.Add(Tasto("Dopo", () => Vai(i + 1))); + tasti.Children.Add(chiudi); + + var pila = new StackPanel { Margin = new Thickness(16, 14, 16, 12) }; + pila.Children.Add(titolo); + pila.Children.Add(riquadro); + pila.Children.Add(barra); + pila.Children.Add(tasti); + Content = new Border + { + CornerRadius = new CornerRadius(16), Margin = new Thickness(12), Child = pila, + Background = new SolidColorBrush(Color.FromArgb(230, 18, 16, 26)), + BorderBrush = new SolidColorBrush(Color.FromArgb(50, 255, 255, 255)), BorderThickness = new Thickness(1), + }; + + orologio = new DispatcherTimer(TimeSpan.FromMilliseconds(200), DispatcherPriority.Normal, (_, _) => Aggiorna(), Dispatcher); + Loaded += (_, _) => { Posiziona(); Vai(0); orologio.Start(); }; + avatar.Spostato += Posiziona; + Closed += (_, _) => { avatar.Spostato -= Posiziona; orologio.Stop(); film.Stop(); film.Close(); StatoCambiato?.Invoke(false); }; + PreviewKeyDown += (_, e) => { if (e.Key == Key.Escape) Close(); else if (e.Key == Key.Space) Gira(); }; + } + + void Vai(int n) + { + i = (n + file.Count) % file.Count; + titolo.Text = Path.GetFileName(file[i]); + film.Source = new Uri(file[i]); + film.Play(); + suona = true; + play.Content = "Pausa"; + StatoCambiato?.Invoke(true); + } + + void Gira() + { + if (suona) { film.Pause(); suona = false; play.Content = "Play"; } + else { film.Play(); suona = true; play.Content = "Pausa"; } + StatoCambiato?.Invoke(suona); + } + + void Aggiorna() + { + if (!film.NaturalDuration.HasTimeSpan || barra.ActualWidth <= 0) return; + var tot = film.NaturalDuration.TimeSpan.TotalSeconds; + if (tot <= 0) return; + riempimento.Width = barra.ActualWidth * Math.Clamp(film.Position.TotalSeconds / tot, 0, 1); + } + + async Task Modifica() + { + film.Pause(); + var era = suona; + suona = false; + try + { + var esito = await FinestraCopertina.Mostra(this, file[i], film.Position.TotalSeconds); + if (esito?.Nota is { Length: > 0 }) titolo.ToolTip = esito.Nota; + } + catch { /* la finestra lo dice */ } + if (era) { film.Play(); suona = true; play.Content = "Pausa"; } + } + + async Task Scarica() + { + try + { + var dove = await Copertine.SalvaAccanto(Strumenti.Trova(), file[i]); + titolo.ToolTip = "Salvata: " + Path.GetFileName(dove); + } + catch (Exception e) { titolo.ToolTip = e.Message; } + } + + void Posiziona() + { + var a = avatar.Area; + var area = SystemParameters.WorkArea; + Left = Math.Clamp(a.Left + a.Width / 2 - Width / 2, area.Left, Math.Max(area.Left, area.Right - Width)); + var sotto = a.Bottom - 10; + Top = sotto + 280 <= area.Bottom ? sotto : Math.Max(area.Top, a.Top - 280); + } + + static Button Tasto(string testo, Action fai, bool oro = false) + { + var b = new Button + { + Content = testo, Height = 30, Margin = new Thickness(4, 0, 4, 0), Padding = new Thickness(10, 0, 10, 0), + Foreground = oro ? new SolidColorBrush(Color.FromRgb(0x1a, 0x14, 0x05)) : Brushes.White, + Background = oro ? new SolidColorBrush(Color.FromRgb(0xff, 0xd5, 0x4a)) : new SolidColorBrush(Color.FromArgb(30, 255, 255, 255)), + BorderThickness = new Thickness(0), Cursor = Cursors.Hand, FontWeight = FontWeights.Bold, + }; + b.Click += (_, _) => fai(); + return b; + } +} diff --git a/src/DaPConvertitore/Miniature/Multimedia.cs b/src/DaPConvertitore/Miniature/Multimedia.cs index 8cc82a4..3fcacf4 100644 --- a/src/DaPConvertitore/Miniature/Multimedia.cs +++ b/src/DaPConvertitore/Miniature/Multimedia.cs @@ -29,7 +29,8 @@ public static class Multimedia if (info is null) return null; var durata = info.Durata; var t = durata > 4 ? durata * 0.1 : 0; - var img = Tela.Immagine(Fotogramma(s, percorso, L, t)) ?? (t > 0 ? Tela.Immagine(Fotogramma(s, percorso, L, 0)) : null); + byte[]? prima = info.IndiceCopertina >= 0 ? Aspetta(() => Copertine.EstraiAllegata(s, percorso, info.IndiceCopertina, L, silenzioso: true)) : null; + var img = Tela.Immagine(prima) ?? Tela.Immagine(Fotogramma(s, percorso, L, t)) ?? (t > 0 ? Tela.Immagine(Fotogramma(s, percorso, L, 0)) : null); if (img is null) return null; var scala = (double)L / Math.Max(img.PixelWidth, img.PixelHeight); diff --git a/src/DaPConvertitore/Ponte.cs b/src/DaPConvertitore/Ponte.cs index fdc7a92..013c56a 100644 --- a/src/DaPConvertitore/Ponte.cs +++ b/src/DaPConvertitore/Ponte.cs @@ -1,9 +1,11 @@ using System.Collections.Concurrent; using System.Diagnostics; +using System.Globalization; using System.Text.Json; using System.Text.Json.Nodes; using System.Windows; using System.Windows.Threading; +using DaP.Convertitore.Lettore; using Microsoft.Web.WebView2.Core; using Microsoft.Web.WebView2.Wpf; @@ -34,8 +36,22 @@ public sealed class Ponte // la stampante arriva quando WebView2 è pronto; un lavoro che parte prima la aspetta readonly TaskCompletionSource stampante = new(TaskCreationOptions.RunContinuationsAsynchronously); bool pronta; + bool chiediImpostazioni; + + /// Si è arrivati dal lettore: la pagina mostra «Indietro» sulla barra bianca. + public void MostraIndietro(string percorso) + { + if (pronta) finestra.Dispatcher.BeginInvoke(() => Manda("torna", new { percorso }), DispatcherPriority.Background); + } readonly HashSet giro = []; + /// Dal vassoio: apri le impostazioni appena la pagina è pronta. + public void ApriImpostazioni() + { + chiediImpostazioni = true; + if (pronta) finestra.Dispatcher.BeginInvoke(() => { chiediImpostazioni = false; Manda("apriImpostazioni", null); }); + } + public Coda Coda { get; } static readonly JsonSerializerOptions json = new(JsonSerializerDefaults.Web); @@ -57,6 +73,11 @@ public Ponte(Finestra finestra, WebView2 vista) rilevazione = Task.Run(() => Hardware.Rileva(strumenti)); Coda = new Coda(strumenti, () => hardware ?? rilevazione.GetAwaiter().GetResult(), () => new StampanteInAttesa(stampante.Task), imp.ScrittaPulita, () => imp.CestinoDaSolo) { QuandoFatto = Storico.Aggiungi }; Coda.Cambiato += l => finestra.Dispatcher.BeginInvoke(() => LavoroCambiato(l)); + Storico.Cambiato += () => + { + try { finestra.Dispatcher.BeginInvoke(() => { if (pronta) Manda("recenti", null); }); } + catch { /* la finestra è già chiusa */ } + }; timerRapide = new DispatcherTimer(TimeSpan.FromMilliseconds(450), DispatcherPriority.Normal, (_, _) => PartonoRapide(), finestra.Dispatcher) { IsEnabled = false }; timerCarico = new DispatcherTimer(TimeSpan.FromMilliseconds(700), DispatcherPriority.Background, (_, _) => Carico(), finestra.Dispatcher) { IsEnabled = false }; _ = rilevazione.ContinueWith(t => @@ -235,6 +256,11 @@ async void Ricevi(object? _, CoreWebView2WebMessageReceivedEventArgs e) } pronta = true; timerCarico.Start(); + if (chiediImpostazioni) + { + chiediImpostazioni = false; + _ = finestra.Dispatcher.BeginInvoke(() => Manda("apriImpostazioni", null), System.Windows.Threading.DispatcherPriority.Background); + } return new { versione = Versione, @@ -252,6 +278,7 @@ async void Ricevi(object? _, CoreWebView2WebMessageReceivedEventArgs e) menu11 = StatoMenu11(), compatto, scelta = sceltaIniziale, + torna = Regia.PercorsoIndietro, }; case "pronto": return true; @@ -263,6 +290,17 @@ async void Ricevi(object? _, CoreWebView2WebMessageReceivedEventArgs e) 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 "url": + { + var p = (string?)a["percorso"]; + return p is not null && File.Exists(p) ? risorse.Url(p) : null; + } + case "miniatura": + { + var p = (string?)a["percorso"] ?? ""; + var png = await Task.Run(() => MiniaturaFile.PngBase64(p)); + return new { png }; + } case "incolla": { // i file copiati in Esplora file (Ctrl+C) entrano nella coda, come se fossero trascinati @@ -383,6 +421,22 @@ async void Ricevi(object? _, CoreWebView2WebMessageReceivedEventArgs e) imp.ApriCon = ap.GetValue(); if (imp.ApriCon) ApriCon.Registra(Environment.ProcessPath!); else ApriCon.Rimuovi(); } + if (a["codificaCon"] is { } cc) + { + var v = (string?)cc; + imp.CodificaCon = v is "gpu" or "cpu" ? v : null; + } + if (a["cartellaMia"] is { } cm) + { + var p = ((string?)cm)?.Trim(); + imp.CartellaMia = string.IsNullOrEmpty(p) ? null : p; + try { CartellaLavori.Percorso(imp.CartellaMia); } catch (Exception e) { Registro.Errore("cartella", e); } + } + if (a["scorciatoiaSchermo"] is { } ss) + { + imp.ScorciatoiaSchermo = string.IsNullOrWhiteSpace((string?)ss) ? null : (string)ss!; + Schermata.ApplicaScorciatoia(); + } 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(); @@ -544,13 +598,101 @@ async void Ricevi(object? _, CoreWebView2WebMessageReceivedEventArgs e) { // solo i posti che conosciamo: l'interfaccia non apre indirizzi a caso var url = (string?)a["url"] ?? ""; - if (url.StartsWith("https://it.libreoffice.org/") || url.StartsWith("https://github.com/cammo22/DaP-Convertitore")) + if (url.StartsWith("https://it.libreoffice.org/") || url.StartsWith("https://github.com/cammo22/")) Process.Start(new ProcessStartInfo(url) { UseShellExecute = true }); return true; } case "registro": if (File.Exists(Registro.Percorso)) Process.Start(new ProcessStartInfo(Registro.Percorso) { UseShellExecute = true }); return true; + case "schedaFile": + { + var v = file.TryGetValue((string?)a["id"] ?? "", out var x) ? x : throw new ErroreConversione("Il file non è più nella coda."); + var fmt = Catalogo.Trova((string?)a["formato"] ?? ""); + var est = string.IsNullOrEmpty(fmt?.Estensione) ? Path.GetExtension(v.Info.Percorso) : fmt!.Estensione; + return await Metadati.Leggi(strumenti, v.Info.Percorso, est); + } + case "scegliImmagine": + { + string? scelto = null; + await finestra.Dispatcher.InvokeAsync(() => + { + var d = new Microsoft.Win32.OpenFileDialog { Title = "Scegli la copertina", Filter = "Immagini|*.jpg;*.jpeg;*.png;*.webp;*.bmp;*.tif;*.tiff" }; + if (d.ShowDialog(finestra) == true) scelto = d.FileName; + }); + return scelto; + } + case "copertine": + { + var titolo = (string?)a["titolo"] ?? ""; + var elenco = new List(); + for (var n = 0; n < Copertine.Quante; n++) + elenco.Add(new EsitoCopertina(Copertine.Genera(titolo, n, null), null, false, null).ComeDataUrl()!); + return elenco; + } + case "cartellaMia": + { + var p = CartellaLavori.Assicura(); + return new { percorso = p, file = CartellaLavori.Recenti(p).Select(v => new { v.Nome, v.Peso, v.Percorso }) }; + } + case "apriCartellaMia": + Programma.Mostra(CartellaLavori.Assicura()); + return true; + case "scegliCartellaMia": + { + string? scelto = null; + await finestra.Dispatcher.InvokeAsync(() => + { + var d = new Microsoft.Win32.OpenFolderDialog { Title = "Dove metto quello che faccio", InitialDirectory = CartellaLavori.Assicura() }; + if (d.ShowDialog(finestra) == true) scelto = d.FolderName; + }); + if (scelto is null) return new { percorso = (string?)null }; + imp.CartellaMia = scelto; + imp.Salva(); + CartellaLavori.Percorso(scelto); + return new { percorso = scelto }; + } + case "scorciatoia": + Schermata.ApplicaScorciatoia(); + return true; + case "cattura": + _ = finestra.Dispatcher.BeginInvoke(() => Schermata.Cattura()); + return true; + case "registra": + // stessa strada del vassoio e dell'avatar: ComandiRegistrazione.CosaFa + Registrazione.Chiedi("ponte"); + return new { inCorso = Registrazione.Attiva }; + case "tornaLettore": + Regia.TornaAlLettore(); + return true; + case "salvaPng": + { + var dati = (string?)a["png"] ?? ""; + var i = dati.IndexOf(','); + if (i < 0 || i >= dati.Length - 1) throw new ErroreConversione("Manca l'immagine."); + byte[] bytes; + try { bytes = Convert.FromBase64String(dati[(i + 1)..]); } + catch { throw new ErroreConversione("L'immagine non è valida."); } + if (bytes.Length < 32) throw new ErroreConversione("L'immagine è vuota."); + var nomePng = $"fotogramma {DateTime.Now:yyyy-MM-dd HH-mm-ss}.png"; + var destPng = Path.Combine(CartellaLavori.Assicura(), nomePng); + await File.WriteAllBytesAsync(destPng, bytes); + return new { nome = nomePng, percorso = destPng }; + } + case "salvaQuadro": + { + var idQuadro = (string?)a["id"] ?? ""; + if (!file.TryGetValue(idQuadro, out var voce)) throw new ErroreConversione("Il file non è più nella coda."); + var t = Math.Max(0, a["t"]?.GetValue() ?? 0); + var nomeQ = $"fotogramma {DateTime.Now:yyyy-MM-dd HH-mm-ss}.png"; + var destQ = Path.Combine(CartellaLavori.Assicura(), nomeQ); + var esito = await Processi.Esegui(strumenti.Ffmpeg, + ["-hide_banner", "-y", "-i", voce.Info.Percorso, "-ss", t.ToString(CultureInfo.InvariantCulture), "-frames:v", "1", destQ], + CancellationToken.None); + if (esito.Codice != 0 || !File.Exists(destQ)) + throw new ErroreConversione("Non sono riuscito a salvare il fotogramma.", esito.Errori); + return new { nome = nomeQ, percorso = destQ }; + } } throw new InvalidOperationException($"Comando sconosciuto: {cmd}"); } diff --git a/src/DaPConvertitore/PonteLettore.cs b/src/DaPConvertitore/PonteLettore.cs index 916d028..8cb66ae 100644 --- a/src/DaPConvertitore/PonteLettore.cs +++ b/src/DaPConvertitore/PonteLettore.cs @@ -137,7 +137,8 @@ static List Voci(JsonObject a) => var p = P(a); var s = await Scheda_(p); var i = s.Info; - var copertina = i.Video is null ? await Media.Copertina(strumenti, p, i.Copertina) : null; + // si prova sempre la copertina dentro il file: a volte FFprobe non la segna, e dopo una modifica la scheda in cache è vecchia + var copertina = i.Video is null ? await Media.Copertina(strumenti, p, true) : null; return new { durata = i.Durata, contenitore = i.Contenitore, bitrate = i.Bitrate, @@ -153,7 +154,7 @@ static List Voci(JsonObject a) => esterni = Media.SottotitoliAccanto(p).Select(f => new { nome = Path.GetFileName(f), percorso = f }), tag = s.Tag, capitoli = s.Capitoli.Select(c => new { inizio = double.Parse(c.Inizio, CultureInfo.InvariantCulture), titolo = c.Titolo }), - copertina = copertina is null ? null : $"data:image/jpeg;base64,{Convert.ToBase64String(copertina)}", + copertina = new EsitoCopertina(copertina, null, true, null).ComeDataUrl(), }; } case "audioCache": @@ -281,7 +282,7 @@ static List Voci(JsonObject a) => // ——— cose da fare col file ——— case "converti": - Regia.Converti(P(a)); + Regia.Converti(P(a), finestra); return true; case "estrai": if (!string.IsNullOrEmpty(passwordArchivio)) @@ -345,7 +346,13 @@ static List Voci(JsonObject a) => case "taglia": { var p = P(a); - var nuovo = await Modifiche.TagliaVideo(strumenti, p, a["da"]!.GetValue(), a["a"]!.GetValue()); + string nuovo; + if (a["pezzi"] is JsonArray arr && arr.Count > 0) + { + var pezzi = arr.Select(x => (x!["da"]!.GetValue(), x["a"]!.GetValue())).ToList(); + nuovo = await Modifiche.TagliaPezzi(strumenti, p, pezzi); + } + else nuovo = await Modifiche.TagliaVideo(strumenti, p, a["da"]!.GetValue(), a["a"]!.GetValue()); return new { percorso = nuovo, nome = Path.GetFileName(nuovo) }; } case "ruotaPdf": @@ -416,6 +423,53 @@ static List Voci(JsonObject a) => await File.WriteAllBytesAsync(uscita, b); return uscita; } + case "copertinaPng": + { + var p = P(a); + var dati = (string?)a["png"] ?? ""; + var b = Convert.FromBase64String(dati[(dati.IndexOf(',') + 1)..]); + var tmp = Path.Combine(Strumenti.CartellaTemporanea, $"frame-{Guid.NewGuid():N}.png"); + await File.WriteAllBytesAsync(tmp, b); + try + { + var esito = await Copertine.Applica(strumenti, p, tmp); + schede.Remove(p); + return new { copertina = esito.ComeDataUrl(), dentro = esito.Dentro, nota = esito.Nota }; + } + finally { try { File.Delete(tmp); } catch { } } + } + case "salvaCopertina": + { + var dove = await Copertine.SalvaAccanto(strumenti, P(a)); + return new { percorso = dove, nome = Path.GetFileName(dove) }; + } + case "scegliCopertina": + { + string? scelto = null; + await finestra.Dispatcher.InvokeAsync(() => + { + var d = new Microsoft.Win32.OpenFileDialog { Title = "Scegli la copertina", Filter = "Immagini|*.jpg;*.jpeg;*.png;*.webp;*.bmp;*.tif;*.tiff" }; + if (d.ShowDialog(finestra) == true) scelto = d.FileName; + }); + if (scelto is null) return null; + var esito = await Copertine.Applica(strumenti, P(a), scelto); + schede.Remove(P(a)); + return new { copertina = esito.ComeDataUrl(), accanto = esito.Accanto, dentro = esito.Dentro, nota = esito.Nota }; + } + case "mettiCopertina": + { + var esito = await Copertine.ApplicaGenerata(strumenti, P(a), (string?)a["titolo"] ?? "", a["variante"]?.GetValue() ?? 0); + schede.Remove(P(a)); + return new { copertina = esito.ComeDataUrl(), accanto = esito.Accanto, dentro = esito.Dentro, nota = esito.Nota }; + } + case "copertine": + { + var titolo = (string?)a["titolo"] ?? ""; + var elenco = new List(); + for (var n = 0; n < Copertine.Quante; n++) + elenco.Add(new EsitoCopertina(Copertine.Genera(titolo, n, null), null, false, null).ComeDataUrl()!); + return elenco; + } case "apriFile": { var d = new Microsoft.Win32.OpenFileDialog { Title = "Apri nel lettore", Multiselect = true }; diff --git a/src/DaPConvertitore/PosizioneFinestre.cs b/src/DaPConvertitore/PosizioneFinestre.cs new file mode 100644 index 0000000..5e43c2b --- /dev/null +++ b/src/DaPConvertitore/PosizioneFinestre.cs @@ -0,0 +1,127 @@ +using System.Runtime.InteropServices; +using System.Windows; +using System.Windows.Interop; +using System.Windows.Threading; + +namespace DaP.Convertitore.App; + +/// +/// Mette una finestra accanto all'avatar, nel monitor dove sta lui, in pixel veri. +/// è solo il principale e in unità diverse dai pixel: +/// con un avatar su un altro monitor, o con un DPI diverso, la finestra finiva fuori dallo schermo. +/// +public static class PosizioneFinestre +{ + const uint MonitorVicino = 2; + static readonly Dictionary giri = new(); + + [DllImport("user32.dll")] static extern bool GetWindowRect(IntPtr h, out RECT r); + [DllImport("user32.dll")] static extern IntPtr MonitorFromWindow(IntPtr hwnd, uint flags); + [DllImport("user32.dll")] static extern IntPtr MonitorFromPoint(POINT p, uint flags); + [DllImport("user32.dll")] static extern bool GetMonitorInfo(IntPtr h, ref MONITORINFO mi); + [DllImport("user32.dll")] static extern bool SetWindowPos(IntPtr h, IntPtr dopo, int x, int y, int cx, int cy, uint flags); + [DllImport("user32.dll")] static extern uint GetDpiForWindow(IntPtr hwnd); + [DllImport("user32.dll")] static extern bool PhysicalToLogicalPointForPerMonitorDPI(IntPtr hwnd, ref POINT pt); + [DllImport("shcore.dll")] static extern int GetDpiForMonitor(IntPtr hmonitor, int tipo, out uint dpiX, out uint dpiY); + + [StructLayout(LayoutKind.Sequential)] struct RECT { public int Left, Top, Right, Bottom; } + [StructLayout(LayoutKind.Sequential)] struct POINT { public int X, Y; } + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + struct MONITORINFO + { + public int cbSize; + public RECT rcMonitor; + public RECT rcWork; + public uint dwFlags; + } + + /// + /// Accanto ad , o al centro del monitor principale se l'avatar è spento. + /// e sono la misura voluta, in DIP: + /// sul monitor dell'avatar diventano pixel con il DPI di quel monitor, e se non ci stanno si riducono. + /// + public static void Sistema(Window finestra, Window? ancora, double dipLarghezza, double dipAltezza, bool scrivi) + { + var h = new WindowInteropHelper(finestra).Handle; + if (h == IntPtr.Zero) return; + try + { + var (monitor, area) = AreaDi(ancora, h); + var dpi = DpiDi(monitor, h); + var pxL = Math.Max(80, (int)Math.Round(dipLarghezza * dpi / 96.0)); + var pxA = Math.Max(60, (int)Math.Round(dipAltezza * dpi / 96.0)); + Ancoraggio.Riquadro dove; + if (ancora is not null && ancora.IsVisible && GetWindowRect(new WindowInteropHelper(ancora).Handle, out var ar)) + { + var box = new Ancoraggio.Riquadro(ar.Left, ar.Top, Math.Max(1, ar.Right - ar.Left), Math.Max(1, ar.Bottom - ar.Top)); + dove = Ancoraggio.Accanto(box, pxL, pxA, area); + } + else dove = Ancoraggio.Centro(pxL, pxA, area); + // prima i pixel veri, così la finestra è già sul monitor giusto quando WPF legge i DPI + Metti(h, dove); + var logica = Logica(h, dove.X, dove.Y, dpi); + finestra.Left = logica.X; + finestra.Top = logica.Y; + var dipW = dove.L * 96.0 / dpi; + var dipH = dove.A * 96.0 / dpi; + if (Math.Abs(finestra.Width - dipW) > 1) finestra.Width = dipW; + if (Math.Abs(finestra.Height - dipH) > 1) finestra.Height = dipH; + // WPF, scrivendo Left e Width, può rimandare la finestra. L'ultima parola sono i pixel veri. + var x = dove.X; var y = dove.Y; var l = dove.L; var a = dove.A; + var mio = giri[finestra] = giri.GetValueOrDefault(finestra) + 1; + finestra.Dispatcher.BeginInvoke(DispatcherPriority.Render, () => + { + if (giri.GetValueOrDefault(finestra) != mio) return; + if (new WindowInteropHelper(finestra).Handle == h) Metti(h, new Ancoraggio.Riquadro(x, y, l, a)); + }); + if (scrivi) + Registro.Scrivi($"registrazione: finestra a {dove.X},{dove.Y} ({dove.L}×{dove.A} px, dpi {dpi}) dentro {area.X},{area.Y} {area.L}×{area.A}"); + } + catch (Exception e) { Registro.Errore("registrazione: posizione", e); } + } + + static (IntPtr Monitor, Ancoraggio.Riquadro Area) AreaDi(Window? ancora, IntPtr finestra) + { + IntPtr mon; + if (ancora is not null && ancora.IsVisible) + { + var ha = new WindowInteropHelper(ancora).Handle; + mon = ha != IntPtr.Zero ? MonitorFromWindow(ha, MonitorVicino) : MonitorPrincipale(); + } + else mon = MonitorPrincipale(); + if (mon == IntPtr.Zero) mon = MonitorFromWindow(finestra, MonitorVicino); + var info = new MONITORINFO { cbSize = Marshal.SizeOf() }; + if (mon != IntPtr.Zero && GetMonitorInfo(mon, ref info)) + { + var w = info.rcWork; + return (mon, new Ancoraggio.Riquadro(w.Left, w.Top, Math.Max(1, w.Right - w.Left), Math.Max(1, w.Bottom - w.Top))); + } + var s = System.Windows.Forms.Screen.PrimaryScreen?.WorkingArea ?? new System.Drawing.Rectangle(0, 0, 1280, 720); + return (mon, new Ancoraggio.Riquadro(s.X, s.Y, s.Width, s.Height)); + } + + static IntPtr MonitorPrincipale() + { + var s = System.Windows.Forms.Screen.PrimaryScreen; + if (s is null) return MonitorFromPoint(new POINT { X = 1, Y = 1 }, 1); + var b = s.Bounds; + return MonitorFromPoint(new POINT { X = b.X + Math.Max(1, b.Width / 2), Y = b.Y + Math.Max(1, b.Height / 2) }, MonitorVicino); + } + + static uint DpiDi(IntPtr monitor, IntPtr hwnd) + { + if (monitor != IntPtr.Zero && GetDpiForMonitor(monitor, 0, out var x, out _) == 0 && x >= 96) return x; + var d = GetDpiForWindow(hwnd); + return d >= 96 ? d : 96; + } + + static void Metti(IntPtr h, Ancoraggio.Riquadro dove) => + SetWindowPos(h, new IntPtr(-1), dove.X, dove.Y, dove.L, dove.A, 0x0010); + + static Point Logica(IntPtr hwnd, int x, int y, uint dpi) + { + var pt = new POINT { X = x, Y = y }; + if (PhysicalToLogicalPointForPerMonitorDPI(hwnd, ref pt)) return new Point(pt.X, pt.Y); + return new Point(x * 96.0 / dpi, y * 96.0 / dpi); + } +} diff --git a/src/DaPConvertitore/Programma.cs b/src/DaPConvertitore/Programma.cs index 3fec874..e0281c5 100644 --- a/src/DaPConvertitore/Programma.cs +++ b/src/DaPConvertitore/Programma.cs @@ -58,7 +58,7 @@ public static void Main(string[] args) // Velopack per primo: installazione, aggiornamento e disinstallazione passano da qui e finiscono subito VelopackApp.Build() .SetAppUserModelId(MenuContestuale.Aumid) - .OnAfterInstallFastCallback(_ => { Registra(); RegistraWindows11(); RegistraApriCon(); }) + .OnAfterInstallFastCallback(_ => { Registra(); RegistraWindows11(); RegistraApriCon(); try { CartellaLavori.Assicura(); } catch { } }) .OnAfterUpdateFastCallback(_ => { var imp = Impostazioni.Carica(); @@ -89,14 +89,34 @@ public static void Main(string[] args) using var mutex = new Mutex(true, $@"Local\{MenuContestuale.Aumid}", out var primo); // Esplora file lancia un processo per ogni file scelto: il primo apre la finestra, gli altri gli passano i file // parte con Windows: se c'è già un programma aperto non serve altro; se no si apre solo l'avatar - if (!primo && soloAvatar) return; - if (!primo && Istanza.Manda(richiesta)) return; + if (!primo && soloAvatar) + { + Registro.Scrivi($"non parto: l'avatar è già acceso. Questa copia: {Environment.ProcessPath}"); + return; + } + if (!primo) + { + Registro.Scrivi($"non parto: DaP è già aperto ({LeggiIstanza()}). Questa copia: {Environment.ProcessPath}. Chiudi l'icona vicino all'orologio e rilancia, se no provi il processo vecchio."); + if (Istanza.Manda(richiesta)) return; + Registro.Scrivi("il processo già aperto non risponde: parto lo stesso"); + } var app = new Application { ShutdownMode = ShutdownMode.OnExplicitShutdown }; app.DispatcherUnhandledException += (_, e) => { Registro.Errore("interfaccia", e.Exception); e.Handled = true; }; AppDomain.CurrentDomain.UnhandledException += (_, e) => Registro.Errore("app", (Exception)e.ExceptionObject); - app.Exit += (_, _) => Aggiornamenti.AllaChiusura(); + try + { + System.Windows.Forms.Application.SetUnhandledExceptionMode(System.Windows.Forms.UnhandledExceptionMode.CatchException); + System.Windows.Forms.Application.ThreadException += (_, e) => Registro.Errore("vassoio", e.Exception); + } + catch (Exception e) { Registro.Scrivi($"eccezioni del vassoio non agganciate: {e.Message}"); } + app.Exit += (_, _) => { Vassoio.Chiudi(); Aggiornamenti.AllaChiusura(); }; Regia.Avvia(app); + try { CartellaLavori.Assicura(); } catch (Exception e) { Registro.Errore("cartella", e); } + SegnaIstanza(); + Registro.Scrivi($"avviato {typeof(Programma).Assembly.GetName().Version} · {Environment.ProcessPath}"); + Vassoio.Avvia(app); + Schermata.Avvia(); if (!soloAvatar) Regia.Gestisci(richiesta); if (soloAvatar || Impostazioni.Comune.AvatarAttivo) Regia.Avatar(true); Aggiornamenti.Avvia(); // guarda le release in silenzio, all'avvio e poi ogni qualche ora @@ -105,6 +125,27 @@ public static void Main(string[] args) app.Run(); } + /// Chi è il processo aperto: la copia nuova, se ne trova uno già acceso, lo scrive nel registro. + static void SegnaIstanza() + { + try + { + File.WriteAllText(Path.Combine(Strumenti.CartellaDati, "istanza.txt"), + $"{Environment.ProcessId} · {Environment.ProcessPath} · {DateTime.Now:yyyy-MM-dd HH:mm:ss}"); + } + catch { /* il registro dice già che siamo partiti */ } + } + + static string LeggiIstanza() + { + try + { + var p = Path.Combine(Strumenti.CartellaDati, "istanza.txt"); + return File.Exists(p) ? File.ReadAllText(p).Trim() : "non segnato"; + } + catch { return "non segnato"; } + } + /// Disinstallando, l'avatar non deve più partire con Windows (la voce «Run» dell'utente). static void ToglieAvvioAvatar() { diff --git a/src/DaPConvertitore/Regia.cs b/src/DaPConvertitore/Regia.cs index 5032dfa..16c22dc 100644 --- a/src/DaPConvertitore/Regia.cs +++ b/src/DaPConvertitore/Regia.cs @@ -58,12 +58,39 @@ static void Guarda() l.ContentRendered += (_, _) => Davanti.Porta(l); } - /// Dal lettore al convertitore: il file entra nella piastra, con tutte le scelte. - public static void Converti(string percorso) => Gestisci(new Richiesta(null, [percorso], true)); + /// Il file da cui si è arrivati in modifica: «Indietro» riapre il lettore e chiude questa finestra. + public static string? PercorsoIndietro { get; private set; } + + /// Dal lettore alla modifica: il lettore si chiude, il file entra nella piastra. Si torna con «Indietro». + public static void Converti(string percorso, Window? daChiudere = null) + { + PercorsoIndietro = percorso; + Gestisci(new Richiesta(null, [percorso], true)); + daChiudere?.Close(); + convertitore?.Ponte.MostraIndietro(percorso); + } + + /// «Indietro» sulla barra bianca: si riapre il lettore e la modifica si chiude. + public static void TornaAlLettore() + { + var p = PercorsoIndietro; + PercorsoIndietro = null; + if (string.IsNullOrEmpty(p) || !File.Exists(p)) return; + var c = convertitore; + ApriNelLettore(p); + c?.Close(); + } /// Dal convertitore al lettore. public static void ApriNelLettore(string percorso) => Gestisci(new Richiesta(null, [percorso], false, true)); + /// Dal vassoio: la finestra del convertitore, aperta sulle impostazioni. + public static void ApriImpostazioni() + { + Gestisci(new Richiesta(null, [], true)); + convertitore?.Ponte.ApriImpostazioni(); + } + /// L'avatar sul desktop: acceso o spento (e ricordato). Finché c'è, il programma resta aperto anche senza finestre. /// L'avatar si è acceso o spento (da dove sia successo): la pagina aggiorna il suo simbolo. public static event Action? AvatarCambiato; diff --git a/src/DaPConvertitore/Registrazione.cs b/src/DaPConvertitore/Registrazione.cs new file mode 100644 index 0000000..296ad2e --- /dev/null +++ b/src/DaPConvertitore/Registrazione.cs @@ -0,0 +1,425 @@ +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Text; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Interop; +using System.Windows.Threading; + +namespace DaP.Convertitore.App; + +/// Microfoni (DirectShow) e uscite del PC (WASAPI, quelle che si possono registrare in loopback). +public sealed record DispositiviAudio(IReadOnlyList Microfoni, IReadOnlyList Uscite); + +/// +/// Registra lo schermo principale con l'audio, oppure solo l'audio. La pausa chiude un pezzo e la ripresa ne apre +/// un altro: alla fine si uniscono, come fa la registrazione di DaProd Editor Video. La barra e i menu stanno +/// fuori dalla cattura (WDA_EXCLUDEFROMCAPTURE). Lo schermo è quello principale, intero: una zona no. +/// +public static class Registrazione +{ + const uint WdaEscludi = 0x11; + + [DllImport("user32.dll")] + static extern bool SetWindowDisplayAffinity(IntPtr hwnd, uint affinity); + + [DllImport("dwmapi.dll")] + static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int valore, int size); + + static readonly List pezzi = []; + static Process? proc; + static Task? chiusura; + static string? dir, finale; + static DateTime inizioPezzo; + static TimeSpan accumulato; + static bool attiva, inPausa; + static string modo = "schermo", ultimoErrore = ""; + static string? mic, audioPc, titoloScelto; + static int generazione, fpsScelto = 30, crfScelto = 23; + static bool cursoreScelto = true; + static ComandiRegistrazione.Schermo? schermoScelto; + + /// L'avatar, se è acceso: la finestra e la barra gli stanno accanto. + public static Window? Ancora { get; private set; } + + public static bool Attiva => attiva; + public static bool InPausa => inPausa; + + public static TimeSpan Trascorso + { + get + { + var t = accumulato; + if (proc is { HasExited: false }) t += DateTime.UtcNow - inizioPezzo; + return t < TimeSpan.Zero ? TimeSpan.Zero : t; + } + } + + public static string TestoTempo() + { + var t = Trascorso; + return t.TotalHours >= 1 + ? $"{(int)t.TotalHours}:{t.Minutes:00}:{t.Seconds:00}" + : $"{(int)t.TotalMinutes:00}:{t.Seconds:00}"; + } + + /// La finestra non entra nello screenshot né nella registrazione dello schermo (Windows 10 2004 in poi). + public static void Escludi(Window w) + { + w.SourceInitialized += (_, _) => + { + try + { + var h = new WindowInteropHelper(w).Handle; + if (h == IntPtr.Zero) { Registro.Scrivi($"registrazione: {w.Title} senza maniglia, non la escludo"); return; } + // angoli tondi di Windows 11 (DWMWCP_ROUND). La finestra non è trasparente: una layered + // con WDA_EXCLUDEFROMCAPTURE su Windows 11 diventa invisibile anche a chi la guarda. + int tondi = 2; + try { DwmSetWindowAttribute(h, 33, ref tondi, 4); } catch { /* Windows 10 non ha gli angoli */ } + var ok = SetWindowDisplayAffinity(h, WdaEscludi); + Registro.Scrivi(ok + ? $"registrazione: «{w.Title}» non entra nella cattura" + : $"registrazione: «{w.Title}» resta anche nella cattura (Windows prima del 2004, o la chiamata è fallita)"); + } + catch (Exception e) { Registro.Errore("registrazione: esclusione", e); } + }; + } + + /// Anche il menu a comparsa, che è una finestra a sé. + public static void EscludiMenu(ContextMenu menu) + { + menu.Opened += (_, _) => menu.Dispatcher.BeginInvoke(() => + { + if (PresentationSource.FromVisual(menu) is HwndSource hs && hs.Handle != IntPtr.Zero) + SetWindowDisplayAffinity(hs.Handle, WdaEscludi); + }, DispatcherPriority.Loaded); + } + + /// + /// «Registra» dal vassoio, dall'avatar o dal ponte. Stessa decisione (): + /// si apre il menu, oppure si porta davanti la barra se si sta già registrando. Il lavoro vero parte dopo, + /// a menu chiuso: aprirlo dentro il clic lo lasciava a misura zero, o lo chiudeva insieme al menu. + /// + public static void Chiedi(string da, Window? accanto = null) + { + accanto ??= AvatarVisibile(); + Ancora = accanto; + var cosa = ComandiRegistrazione.CosaFa(da, attiva); + Registro.Scrivi($"registrazione: «Registra» da {da} → {cosa}"); + var d = System.Windows.Application.Current?.Dispatcher; + if (d is null) + { + Registro.Scrivi("registrazione: non c'è l'interfaccia, il menu non si apre"); + return; + } + d.BeginInvoke(DispatcherPriority.ApplicationIdle, () => + { + try + { + if (attiva) + { + Registro.Scrivi("registrazione: è già in corso, porto la finestra"); + MenuRegistrazione.PortaDavanti(); + return; + } + MenuRegistrazione.Mostra(accanto, da); + } + catch (Exception e) + { + Registro.Errore("registrazione: apertura", e); + try { Vassoio.Dire("Registra non si è aperto", e.Message); } catch { /* il vassoio può non esserci */ } + } + }); + } + + public static bool Inizia(string modoScelto, string? microfono, string? uscitaPc, ComandiRegistrazione.Schermo? schermo, int fps, int crf, bool cursore, string? titolo) + { + if (attiva) { MenuRegistrazione.PortaDavanti(); return true; } + if (modoScelto == "audio" && microfono is null && uscitaPc is null) + { + Vassoio.Dire("Scegli un audio", "Per registrare solo l'audio serve il microfono o l'audio del PC."); + return false; + } + modo = modoScelto == "audio" ? "audio" : modoScelto == "finestra" ? "finestra" : "schermo"; + mic = microfono; + audioPc = uscitaPc; + schermoScelto = schermo; + fpsScelto = ComandiRegistrazione.FpsDi(fps); + crfScelto = Math.Clamp(crf, 16, 32); + cursoreScelto = cursore; + titoloScelto = titolo; + pezzi.Clear(); + accumulato = TimeSpan.Zero; + inPausa = false; + ultimoErrore = ""; + dir = Path.Combine(Path.GetTempPath(), "DaP Convertitore", "reg-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(dir); + var ext = modo == "audio" ? ".m4a" : ".mp4"; + finale = Path.Combine(CartellaLavori.Assicura(), $"registrazione {DateTime.Now:yyyy-MM-dd HH-mm-ss}{ext}"); + Registro.Scrivi($"registrazione: parto ({modo}, mic «{mic ?? "no"}», pc «{audioPc ?? "no"}») → {finale}"); + attiva = true; + if (!ApriPezzo()) + { + attiva = false; + PulisciCartella(); + Registro.Scrivi($"registrazione: non è partita ({(string.IsNullOrWhiteSpace(ultimoErrore) ? "FFmpeg non è partito" : ultimoErrore)})"); + Vassoio.Dire("La registrazione non è partita", string.IsNullOrWhiteSpace(ultimoErrore) ? "FFmpeg non è partito." : ultimoErrore); + return false; + } + if (!MenuRegistrazione.Visibile) BarraRegistrazione.Mostra(); + MenuRegistrazione.Aggiorna(); + return true; + } + + static Window? AvatarVisibile() + { + var app = System.Windows.Application.Current; + if (app is null) return null; + foreach (Window w in app.Windows) + if (w is FinestraAvatar && w.IsVisible) return w; + return null; + } + + public static void Pausa() + { + if (!attiva || inPausa || proc is null) return; + Registro.Scrivi("registrazione: pausa"); + var p = proc; + proc = null; + accumulato += DateTime.UtcNow - inizioPezzo; + inPausa = true; + chiusura = Task.Run(() => ChiudiMorbido(p)); + BarraRegistrazione.Aggiorna(); + MenuRegistrazione.Aggiorna(); + } + + public static void Riprendi() + { + if (!attiva || !inPausa) return; + Registro.Scrivi("registrazione: riprendo"); + var attesa = chiusura; + _ = Task.Run(() => + { + try { attesa?.Wait(10000); } catch { /* il pezzo è già chiuso */ } + System.Windows.Application.Current?.Dispatcher.BeginInvoke(() => + { + if (!attiva || !inPausa) return; + if (!ApriPezzo()) + { + Vassoio.Dire("Non riprendo", string.IsNullOrWhiteSpace(ultimoErrore) ? "FFmpeg non è ripartito." : ultimoErrore); + return; + } + inPausa = false; + BarraRegistrazione.Aggiorna(); + MenuRegistrazione.Aggiorna(); + }); + }); + } + + public static void Salva() + { + if (!attiva) return; + Registro.Scrivi("registrazione: salvo"); + attiva = false; + inPausa = false; + var p = proc; + var attesa = chiusura; + proc = null; + var lista = pezzi.ToList(); + var dest = finale; + var cartella = dir; + dir = finale = null; + BarraRegistrazione.Chiudi(); + MenuRegistrazione.Aggiorna(); + _ = Task.Run(() => + { + if (p is not null) ChiudiMorbido(p); + else try { attesa?.Wait(10000); } catch { /* già fermo */ } + var buoni = lista.Where(x => File.Exists(x) && new FileInfo(x).Length > 800).ToList(); + try + { + if (dest is null || buoni.Count == 0) throw new InvalidOperationException("Non c'è niente da salvare."); + try { Unisci(buoni, dest); } + catch (Exception e) + { + File.Copy(buoni[0], dest, true); + Registro.Scrivi($"registrazione, unisco: {e.Message}"); + Ricorda(dest); + SulFilo(() => Vassoio.Dire("Registrazione salvata a pezzi", "Il resto non si è unito: ho tenuto il primo pezzo, " + Path.GetFileName(dest))); + return; + } + Registro.Scrivi($"registrazione: salvata {dest}"); + Ricorda(dest); + SulFilo(() => Vassoio.Dire("Registrazione salvata", Path.GetFileName(dest))); + } + catch (Exception e) + { + Registro.Errore("registrazione", e); + SulFilo(() => Vassoio.Dire("Non ho salvato la registrazione", e.Message)); + } + finally { try { if (cartella is not null) Directory.Delete(cartella, true); } catch { /* i pezzi restano nel temp */ } } + }); + } + + public static void Annulla() + { + if (!attiva && proc is null) { BarraRegistrazione.Chiudi(); return; } + Registro.Scrivi("registrazione: annullo"); + attiva = false; + inPausa = false; + var p = proc; + proc = null; + var cartella = dir; + dir = finale = null; + pezzi.Clear(); + BarraRegistrazione.Chiudi(); + MenuRegistrazione.Aggiorna(); + _ = Task.Run(() => + { + try { if (p is { HasExited: false }) p.Kill(entireProcessTree: true); } catch { /* già fermo */ } + try { p?.Dispose(); } catch { } + try { if (cartella is not null) Directory.Delete(cartella, true); } catch { /* ci riprova il temp di Windows */ } + }); + } + + /// Elenco dispositivi. Su un ffmpeg senza wasapi né dshow la lista resta vuota, e lo dice il registro. + public static DispositiviAudio Elenca() + { + var ff = Strumenti.Trova().Ffmpeg; + var microfoni = ComandiRegistrazione.MicrofoniDaElenco(Leggi(ff, "-hide_banner", "-list_devices", "true", "-f", "dshow", "-i", "dummy")); + var uscite = ComandiRegistrazione.UsciteDaElenco(Leggi(ff, "-hide_banner", "-list_devices", "true", "-f", "wasapi", "-i", "dummy")); + Registro.Scrivi(microfoni.Count == 0 && uscite.Count == 0 + ? $"registrazione: nessun dispositivo (ffmpeg {ff}). DirectShow e WASAPI servono su Windows, con l'FFmpeg dell'app." + : $"registrazione: {microfoni.Count} microfoni, {uscite.Count} uscite del PC"); + return new DispositiviAudio(microfoni, uscite); + } + + /// Il monitor principale, in pixel veri. Se non si legge, gdigrab prende tutto il desktop. + public static ComandiRegistrazione.Schermo? SchermoPrincipale() + { + try + { + var b = System.Windows.Forms.Screen.PrimaryScreen?.Bounds; + if (b is null || b.Value.Width < 2 || b.Value.Height < 2) return null; + return new ComandiRegistrazione.Schermo(b.Value.X, b.Value.Y, b.Value.Width, b.Value.Height); + } + catch (Exception e) + { + Registro.Scrivi($"registrazione: non leggo il monitor principale ({e.Message}), prendo tutto il desktop"); + return null; + } + } + + static bool ApriPezzo() + { + if (dir is null) return false; + var ext = modo == "audio" ? ".m4a" : ".mp4"; + var path = Path.Combine(dir, $"p{pezzi.Count:00}{ext}"); + try + { + var s = Strumenti.Trova(); + var psi = new ProcessStartInfo(s.Ffmpeg) + { + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardInput = true, + RedirectStandardError = true, + StandardErrorEncoding = Encoding.UTF8, + }; + var argomenti = ComandiRegistrazione.Argomenti(modo, mic, audioPc, path, modo == "audio" ? null : schermoScelto ?? SchermoPrincipale(), fpsScelto, crfScelto, cursoreScelto, titoloScelto); + Registro.Scrivi($"> ffmpeg {ComandiRegistrazione.Riga(argomenti)}"); + foreach (var a in argomenti) psi.ArgumentList.Add(a); + var p = Process.Start(psi); + if (p is null) return false; + p.ErrorDataReceived += (_, e) => { if (!string.IsNullOrWhiteSpace(e.Data)) ultimoErrore = e.Data!; }; + p.BeginErrorReadLine(); + proc = p; + pezzi.Add(path); + inizioPezzo = DateTime.UtcNow; + var gen = ++generazione; + _ = Task.Run(async () => + { + await Task.Delay(800); + if (p.HasExited && p.ExitCode != 0) + SulFilo(() => + { + if (!attiva || gen != generazione) return; + attiva = false; + proc = null; + BarraRegistrazione.Chiudi(); + Registro.Scrivi($"registrazione: FFmpeg si è chiuso subito ({p.ExitCode}) {ultimoErrore}"); + Vassoio.Dire("La registrazione non è partita", string.IsNullOrWhiteSpace(ultimoErrore) ? "FFmpeg si è chiuso subito." : ultimoErrore); + PulisciCartella(); + }); + }); + return true; + } + catch (Exception e) + { + ultimoErrore = e.Message; + Registro.Errore("registrazione", e); + return false; + } + } + + static void ChiudiMorbido(Process p) + { + try { if (!p.HasExited) { p.StandardInput.Write("q"); p.StandardInput.Flush(); } } catch { /* già chiuso */ } + try { if (!p.WaitForExit(8000)) p.Kill(entireProcessTree: true); } catch { /* se ne è già andato */ } + try { p.Dispose(); } catch { } + } + + static void Unisci(IReadOnlyList buoni, string dest) + { + Directory.CreateDirectory(Path.GetDirectoryName(dest)!); + if (buoni.Count == 1) { File.Copy(buoni[0], dest, true); return; } + var lista = Path.Combine(Path.GetDirectoryName(buoni[0])!, "lista.txt"); + File.WriteAllLines(lista, buoni.Select(p => "file '" + p.Replace('\\', '/').Replace("'", "'\\''") + "'")); + var esito = Processi.Esegui(Strumenti.Trova().Ffmpeg, + ["-hide_banner", "-y", "-f", "concat", "-safe", "0", "-i", lista, "-c", "copy", dest], + CancellationToken.None).GetAwaiter().GetResult(); + if (esito.Codice != 0 || !File.Exists(dest)) + throw new InvalidOperationException(string.IsNullOrWhiteSpace(esito.Errori) ? "I pezzi non si sono uniti." : Taglia(esito.Errori)); + } + + static void PulisciCartella() + { + var cartella = dir; + dir = finale = null; + pezzi.Clear(); + try { if (cartella is not null) Directory.Delete(cartella, true); } catch { /* il temp la toglie dopo */ } + } + + static string Leggi(string ffmpeg, params string[] args) + { + try + { + var psi = new ProcessStartInfo(ffmpeg) + { + UseShellExecute = false, CreateNoWindow = true, + RedirectStandardError = true, StandardErrorEncoding = Encoding.UTF8, + }; + foreach (var a in args) psi.ArgumentList.Add(a); + using var p = Process.Start(psi); + if (p is null) return ""; + var testo = p.StandardError.ReadToEnd(); + if (!p.WaitForExit(8000)) { try { p.Kill(entireProcessTree: true); } catch { } } + return testo; + } + catch (Exception e) { Registro.Scrivi($"dispositivi: {e.Message}"); return ""; } + } + + static void Ricorda(string? dest) + { + if (dest is not null && File.Exists(dest)) Storico.AggiungiFile(dest, "Registrazione"); + } + + static string Taglia(string s) => s.Length > 240 ? s[^240..] : s; + + static void SulFilo(Action fai) + { + var d = System.Windows.Application.Current?.Dispatcher; + if (d is null || d.CheckAccess()) fai(); + else d.BeginInvoke(fai); + } +} diff --git a/src/DaPConvertitore/SceltaZona.cs b/src/DaPConvertitore/SceltaZona.cs new file mode 100644 index 0000000..0c5ae19 --- /dev/null +++ b/src/DaPConvertitore/SceltaZona.cs @@ -0,0 +1,135 @@ +using System.Runtime.InteropServices; +using System.Windows; +using System.Windows.Input; +using System.Windows.Interop; +using System.Windows.Media; +using Rectangle = System.Windows.Shapes.Rectangle; + +namespace DaP.Convertitore.App; + +/// +/// Si trascina un rettangolo sul monitor scelto. Non è esclusa dalla cattura e non è usata mentre si registra: +/// una finestra trasparente esclusa, su Windows 11, sparirebbe anche per chi la guarda. +/// +public static class SceltaZona +{ + public static Task Chiedi(Ancoraggio.Riquadro monitor) + { + var tcs = new TaskCompletionSource(); + var w = new Finestra(monitor, tcs); + w.Show(); + return tcs.Task; + } + + sealed class Finestra : Window + { + readonly Ancoraggio.Riquadro monitor; + readonly TaskCompletionSource esito; + readonly Rectangle segno = new() + { + Stroke = new SolidColorBrush(Color.FromRgb(0xff, 0xd5, 0x4a)), + StrokeThickness = 2, + Fill = new SolidColorBrush(Color.FromArgb(40, 255, 213, 74)), + Visibility = Visibility.Collapsed, + HorizontalAlignment = HorizontalAlignment.Left, + VerticalAlignment = VerticalAlignment.Top, + }; + bool chiuso; + int? x0, y0; + + public Finestra(Ancoraggio.Riquadro monitor, TaskCompletionSource esito) + { + this.monitor = monitor; + this.esito = esito; + WindowStyle = WindowStyle.None; + ResizeMode = ResizeMode.NoResize; + AllowsTransparency = true; + Background = new SolidColorBrush(Color.FromArgb(90, 8, 6, 14)); + Topmost = true; + ShowInTaskbar = false; + ShowActivated = true; + Cursor = Cursors.Cross; + Title = "Scegli la zona"; + var tela = new System.Windows.Controls.Canvas(); + tela.Children.Add(segno); + var nota = new System.Windows.Controls.TextBlock + { + Text = "Trascina la zona. Esc annulla.", + Foreground = Brushes.White, + FontSize = 16, + FontWeight = FontWeights.Bold, + Margin = new Thickness(16), + }; + var griglia = new System.Windows.Controls.Grid(); + griglia.Children.Add(tela); + griglia.Children.Add(nota); + Content = griglia; + SourceInitialized += (_, _) => MettiSulMonitor(); + PreviewKeyDown += (_, e) => { if (e.Key == Key.Escape) Fine(null); }; + MouseLeftButtonDown += (_, _) => + { + var p = Cursore(); + x0 = p.X; y0 = p.Y; + CaptureMouse(); + }; + MouseMove += (_, _) => + { + if (x0 is not int a) return; + var p = Cursore(); + var r = Rettangolo(a, y0!.Value, p.X, p.Y); + var s = Scala(); + segno.Margin = new Thickness((r.X - monitor.X) / s, (r.Y - monitor.Y) / s, 0, 0); + segno.Width = Math.Max(1, r.L / s); + segno.Height = Math.Max(1, r.A / s); + segno.Visibility = Visibility.Visible; + }; + MouseLeftButtonUp += (_, _) => + { + if (x0 is not int a) return; + ReleaseMouseCapture(); + var p = Cursore(); + var r = Rettangolo(a, y0!.Value, p.X, p.Y); + x0 = y0 = null; + if (r.L >= 16 && r.A >= 16) Fine(r); + }; + Closed += (_, _) => { if (!chiuso) esito.TrySetResult(null); }; + } + + void MettiSulMonitor() + { + var h = new WindowInteropHelper(this).Handle; + SetWindowPos(h, new IntPtr(-1), monitor.X, monitor.Y, monitor.L, monitor.A, 0x0040); + } + + double Scala() + { + var d = VisualTreeHelper.GetDpi(this).DpiScaleX; + return d <= 0 ? 1 : d; + } + + static Ancoraggio.Riquadro Rettangolo(int x1, int y1, int x2, int y2) + { + var x = Math.Min(x1, x2); + var y = Math.Min(y1, y2); + return new Ancoraggio.Riquadro(x, y, Math.Max(1, Math.Abs(x2 - x1)), Math.Max(1, Math.Abs(y2 - y1))); + } + + void Fine(Ancoraggio.Riquadro? r) + { + if (chiuso) return; + chiuso = true; + esito.TrySetResult(r); + Close(); + } + + static (int X, int Y) Cursore() + { + GetCursorPos(out var p); + return (p.X, p.Y); + } + + [DllImport("user32.dll")] static extern bool GetCursorPos(out PUNTO p); + [DllImport("user32.dll")] static extern bool SetWindowPos(IntPtr h, IntPtr dopo, int x, int y, int cx, int cy, uint flags); + [StructLayout(LayoutKind.Sequential)] struct PUNTO { public int X, Y; } + } +} diff --git a/src/DaPConvertitore/Schermata.cs b/src/DaPConvertitore/Schermata.cs new file mode 100644 index 0000000..07f51fa --- /dev/null +++ b/src/DaPConvertitore/Schermata.cs @@ -0,0 +1,396 @@ +using System.Runtime.InteropServices; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Interop; +using System.Windows.Media; +using System.Windows.Media.Animation; +using System.Windows.Media.Imaging; +using SD = System.Drawing; +using Rectangle = System.Windows.Shapes.Rectangle; + +namespace DaP.Convertitore.App; + +/// +/// Lo screenshot, come ShareX e solo quello: scorciatoia globale, schermo fermo e scurito, la zona +/// (o la finestra sotto il cursore), le misure, la lente, poi il file nella cartella e un'anteprima. +/// +public static class Schermata +{ + const int WmHotkey = 0x0312; + const uint ModAlt = 0x0001, ModControl = 0x0002, ModShift = 0x0004, ModNoRepeat = 0x4000; + const int DwmExtended = 9, DwmCloaked = 14; + + static HwndSource? gancio; + static int idCaldo = 1; + static FinestraCattura? aperta; + + public static void Avvia() + { + if (gancio is not null) return; + var p = new HwndSourceParameters("DaP scorciatoia") + { + Width = 0, Height = 0, + WindowStyle = unchecked((int)0x80000000), + }; + gancio = new HwndSource(p); + gancio.AddHook(Messaggio); + ApplicaScorciatoia(); + } + + public static void ApplicaScorciatoia() + { + if (gancio is null) return; + UnregisterHotKey(gancio.Handle, idCaldo); + var (mod, vk) = Leggi(Impostazioni.Comune.ScorciatoiaSchermo); + if (vk == 0) return; + if (!RegisterHotKey(gancio.Handle, idCaldo, mod | ModNoRepeat, vk)) + Registro.Scrivi("La scorciatoia dello screenshot è già presa da un altro programma."); + } + + public static void Cattura() + { + if (aperta is not null) return; + try + { + var dpi = DpiDi(); + var foto = Scatta(dpi.X, dpi.Y); + aperta = new FinestraCattura(foto, dpi.X, dpi.Y); + aperta.Closed += (_, _) => aperta = null; + aperta.Show(); + } + catch (Exception e) + { + Registro.Errore("screenshot", e); + Vassoio.Dire("Screenshot non fatto", e.Message); + } + } + + static (double X, double Y) DpiDi() + { + var w = Application.Current?.Windows.OfType().FirstOrDefault(x => x.IsVisible); + if (w is null) return (1, 1); + var d = VisualTreeHelper.GetDpi(w); + return (d.DpiScaleX <= 0 ? 1 : d.DpiScaleX, d.DpiScaleY <= 0 ? 1 : d.DpiScaleY); + } + + static BitmapSource Scatta(double dpiX, double dpiY) + { + int x = (int)Math.Round(SystemParameters.VirtualScreenLeft * dpiX); + int y = (int)Math.Round(SystemParameters.VirtualScreenTop * dpiY); + int w = Math.Max(1, (int)Math.Round(SystemParameters.VirtualScreenWidth * dpiX)); + int h = Math.Max(1, (int)Math.Round(SystemParameters.VirtualScreenHeight * dpiY)); + using var bmp = new SD.Bitmap(w, h, SD.Imaging.PixelFormat.Format32bppArgb); + using (var g = SD.Graphics.FromImage(bmp)) + g.CopyFromScreen(x, y, 0, 0, bmp.Size, SD.CopyPixelOperation.SourceCopy); + var hb = bmp.GetHbitmap(); + try + { + var src = Imaging.CreateBitmapSourceFromHBitmap(hb, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); + src.Freeze(); + return src; + } + finally { DeleteObject(hb); } + } + + static (uint Mod, uint Vk) Leggi(string? testo) + { + var t = string.IsNullOrWhiteSpace(testo) ? "Ctrl+Maiusc+S" : testo!; + uint mod = 0, vk = 0; + foreach (var parte in t.Split('+')) + { + var p = parte.Trim(); + if (p.Equals("Ctrl", StringComparison.OrdinalIgnoreCase) || p.Equals("Control", StringComparison.OrdinalIgnoreCase)) mod |= ModControl; + else if (p.Equals("Alt", StringComparison.OrdinalIgnoreCase)) mod |= ModAlt; + else if (p.Equals("Maiusc", StringComparison.OrdinalIgnoreCase) || p.Equals("Shift", StringComparison.OrdinalIgnoreCase)) mod |= ModShift; + else vk = Virtuale(p); + } + return (mod, vk); + } + + static uint Virtuale(string tasto) + { + if (tasto.Length == 1) + { + var c = char.ToUpperInvariant(tasto[0]); + if (c is >= 'A' and <= 'Z' or >= '0' and <= '9') return c; + } + if (tasto.Length is >= 2 and <= 3 && tasto[0] is 'F' or 'f' && int.TryParse(tasto[1..], out var n) && n is >= 1 and <= 24) + return (uint)(0x70 + n - 1); + return tasto.ToLowerInvariant() switch + { + "spazio" or "space" => 0x20, + "invio" or "enter" => 0x0D, + "tab" => 0x09, + _ => 0, + }; + } + + static IntPtr Messaggio(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) + { + if (msg == WmHotkey && wParam.ToInt32() == idCaldo) + { + handled = true; + Application.Current?.Dispatcher.BeginInvoke(Cattura); + } + return IntPtr.Zero; + } + + sealed class FinestraCattura : Window + { + readonly BitmapSource foto; + readonly double dpiX, dpiY; + readonly Grid piano = new(); + readonly System.Windows.Controls.Image chiara; + readonly Rectangle zona = new() { Stroke = new SolidColorBrush(Color.FromRgb(0xff, 0xd5, 0x4a)), StrokeThickness = 2, Visibility = Visibility.Collapsed, IsHitTestVisible = false }; + readonly Rectangle finestra = new() { Stroke = new SolidColorBrush(Color.FromRgb(0xff, 0x3d, 0xf2)), StrokeThickness = 2, Visibility = Visibility.Collapsed, IsHitTestVisible = false }; + readonly Border lente; + readonly System.Windows.Controls.Image zoom = new() { Stretch = Stretch.Fill }; + readonly TextBlock misure = new() { Foreground = Brushes.White, FontWeight = FontWeights.Bold, FontSize = 13, IsHitTestVisible = false }; + readonly List finestre; + bool tira; + Point origine; + Rect scelta; + + public FinestraCattura(BitmapSource foto, double dpiX, double dpiY) + { + this.foto = foto; + this.dpiX = dpiX; + this.dpiY = dpiY; + finestre = Elenca(dpiX, dpiY); + WindowStyle = WindowStyle.None; + ResizeMode = ResizeMode.NoResize; + Topmost = true; + ShowInTaskbar = false; + Background = Brushes.Black; + Cursor = Cursors.Cross; + Left = SystemParameters.VirtualScreenLeft; + Top = SystemParameters.VirtualScreenTop; + Width = SystemParameters.VirtualScreenWidth; + Height = SystemParameters.VirtualScreenHeight; + + // scurimento leggero, come ShareX: la foto resta chiara, la zona scelta è a piena luce + piano.Children.Add(new System.Windows.Controls.Image { Source = foto, Stretch = Stretch.Fill, Opacity = 0.72, IsHitTestVisible = false }); + chiara = new System.Windows.Controls.Image { Source = foto, Stretch = Stretch.Fill, IsHitTestVisible = false, Visibility = Visibility.Collapsed }; + piano.Children.Add(chiara); + piano.Children.Add(finestra); + piano.Children.Add(zona); + lente = new Border + { + Width = 150, Height = 150, CornerRadius = new CornerRadius(12), + BorderBrush = new SolidColorBrush(Color.FromRgb(0xff, 0xd5, 0x4a)), BorderThickness = new Thickness(2), + Background = Brushes.Black, IsHitTestVisible = false, Child = zoom, + Visibility = Visibility.Collapsed, + }; + piano.Children.Add(lente); + misure.Background = new SolidColorBrush(Color.FromArgb(200, 12, 10, 18)); + misure.Padding = new Thickness(6, 2, 6, 2); + piano.Children.Add(misure); + Content = piano; + + MouseMove += Muovi; + MouseLeftButtonDown += Premi; + MouseLeftButtonUp += Lascia; + MouseRightButtonDown += (_, _) => Close(); + KeyDown += (_, e) => { if (e.Key == Key.Escape) Close(); }; + Opacity = 0; + Loaded += (_, _) => + { + BeginAnimation(OpacityProperty, new DoubleAnimation(0, 1, TimeSpan.FromMilliseconds(140))); + Focus(); + }; + } + + void Muovi(object sender, MouseEventArgs e) + { + var p = e.GetPosition(piano); + Lente(p); + if (tira) + { + finestra.Visibility = Visibility.Collapsed; + scelta = Normale(origine, p); + MostraZona(scelta); + return; + } + var sotto = finestre.Where(r => r.Contains(p)).OrderBy(r => r.Width * r.Height).FirstOrDefault(); + if (sotto.Width > 1) + { + finestra.Visibility = Visibility.Visible; + CanvasNonServe(finestra, sotto); + Misura((int)Math.Round(sotto.Width * dpiX), (int)Math.Round(sotto.Height * dpiY), sotto); + } + else finestra.Visibility = Visibility.Collapsed; + } + + void Premi(object sender, MouseButtonEventArgs e) + { + tira = true; + origine = e.GetPosition(piano); + CaptureMouse(); + finestra.Visibility = Visibility.Collapsed; + } + + void Lascia(object sender, MouseButtonEventArgs e) + { + if (!tira) return; + tira = false; + ReleaseMouseCapture(); + var p = e.GetPosition(piano); + Rect r; + if ((p - origine).Length < 6) + { + var sotto = finestre.Where(x => x.Contains(p)).OrderBy(x => x.Width * x.Height).FirstOrDefault(); + if (sotto.Width < 2) { Close(); return; } + r = sotto; + } + else r = Normale(origine, p); + if (r.Width < 2 || r.Height < 2) { Close(); return; } + Salva(r); + Close(); + } + + void MostraZona(Rect r) + { + zona.Visibility = Visibility.Visible; + chiara.Visibility = Visibility.Visible; + chiara.Clip = new RectangleGeometry(r); + CanvasNonServe(zona, r); + Misura((int)Math.Round(r.Width * dpiX), (int)Math.Round(r.Height * dpiY), r); + } + + void Misura(int w, int h, Rect r) + { + misure.Text = $"{w} × {h}"; + misure.Visibility = Visibility.Visible; + var x = Math.Min(r.Left, Width - 120); + var y = r.Bottom + 8; + if (y + 28 > Height) y = Math.Max(0, r.Top - 28); + misure.Margin = new Thickness(Math.Max(0, x), Math.Max(0, y), 0, 0); + misure.HorizontalAlignment = HorizontalAlignment.Left; + misure.VerticalAlignment = VerticalAlignment.Top; + } + + void Lente(Point p) + { + int cx = (int)Math.Round(p.X * dpiX); + int cy = (int)Math.Round(p.Y * dpiY); + const int lato = 48; + int x = Math.Clamp(cx - lato / 2, 0, Math.Max(0, foto.PixelWidth - lato)); + int y = Math.Clamp(cy - lato / 2, 0, Math.Max(0, foto.PixelHeight - lato)); + int w = Math.Min(lato, foto.PixelWidth - x); + int h = Math.Min(lato, foto.PixelHeight - y); + if (w < 2 || h < 2) return; + zoom.Source = new CroppedBitmap(foto, new Int32Rect(x, y, w, h)); + lente.Visibility = Visibility.Visible; + var lx = p.X + 28; + var ly = p.Y + 28; + if (lx + 160 > Width) lx = p.X - 178; + if (ly + 160 > Height) ly = p.Y - 178; + lente.Margin = new Thickness(Math.Max(0, lx), Math.Max(0, ly), 0, 0); + lente.HorizontalAlignment = HorizontalAlignment.Left; + lente.VerticalAlignment = VerticalAlignment.Top; + } + + void Salva(Rect r) + { + int x = Math.Clamp((int)Math.Round(r.X * dpiX), 0, foto.PixelWidth - 1); + int y = Math.Clamp((int)Math.Round(r.Y * dpiY), 0, foto.PixelHeight - 1); + int w = Math.Clamp((int)Math.Round(r.Width * dpiX), 1, foto.PixelWidth - x); + int h = Math.Clamp((int)Math.Round(r.Height * dpiY), 1, foto.PixelHeight - y); + var taglio = new CroppedBitmap(foto, new Int32Rect(x, y, w, h)); + taglio.Freeze(); + var cartella = CartellaLavori.Assicura(); + var percorso = Path.Combine(cartella, $"schermo {DateTime.Now:yyyy-MM-dd HH-mm-ss}.png"); + for (var n = 2; File.Exists(percorso); n++) + percorso = Path.Combine(cartella, $"schermo {DateTime.Now:yyyy-MM-dd HH-mm-ss} {n}.png"); + using (var fs = File.Create(percorso)) + { + var enc = new PngBitmapEncoder(); + enc.Frames.Add(BitmapFrame.Create(taglio)); + enc.Save(fs); + } + try { Clipboard.SetImage(taglio); } catch { /* gli appunti sono occupati */ } + Anteprima(percorso, taglio); + Storico.AggiungiFile(percorso, "Screenshot"); + Vassoio.Dire("Screenshot", Path.GetFileName(percorso)); + } + + static void CanvasNonServe(Rectangle rett, Rect r) + { + rett.HorizontalAlignment = HorizontalAlignment.Left; + rett.VerticalAlignment = VerticalAlignment.Top; + rett.Margin = new Thickness(r.X, r.Y, 0, 0); + rett.Width = r.Width; + rett.Height = r.Height; + } + + static Rect Normale(Point a, Point b) + { + var x = Math.Min(a.X, b.X); + var y = Math.Min(a.Y, b.Y); + return new Rect(x, y, Math.Abs(b.X - a.X), Math.Abs(b.Y - a.Y)); + } + + static List Elenca(double dpiX, double dpiY) + { + var lista = new List(); + EnumWindows((h, _) => + { + if (!IsWindowVisible(h)) return true; + if (GetWindowTextLength(h) == 0) return true; + DwmGetWindowAttribute(h, DwmCloaked, out int cloaked, 4); + if (cloaked != 0) return true; + if (DwmGetWindowAttribute(h, DwmExtended, out RECT r, Marshal.SizeOf()) != 0 && !GetWindowRect(h, out r)) + return true; + var dip = new Rect(r.Left / dpiX, r.Top / dpiY, Math.Max(0, r.Right - r.Left) / dpiX, Math.Max(0, r.Bottom - r.Top) / dpiY); + dip.Offset(-SystemParameters.VirtualScreenLeft, -SystemParameters.VirtualScreenTop); + if (dip.Width >= 48 && dip.Height >= 48) lista.Add(dip); + return true; + }, IntPtr.Zero); + return lista; + } + } + + static void Anteprima(string percorso, BitmapSource foto) + { + var w = new Window + { + Width = 280, SizeToContent = SizeToContent.Height, WindowStyle = WindowStyle.None, AllowsTransparency = true, + Background = Brushes.Transparent, Topmost = true, ShowInTaskbar = false, ShowActivated = false, Opacity = 0, + }; + var img = new System.Windows.Controls.Image { Source = foto, Height = 72, Stretch = Stretch.Uniform, HorizontalAlignment = HorizontalAlignment.Left }; + var nome = new TextBlock { Text = Path.GetFileName(percorso), Foreground = Brushes.White, FontWeight = FontWeights.Bold, TextTrimming = TextTrimming.CharacterEllipsis }; + var sotto = new TextBlock { Text = "Nella cartella · clic per aprirla", Foreground = new SolidColorBrush(Color.FromRgb(0xa1, 0x9d, 0xb0)), FontSize = 12 }; + var pila = new StackPanel { Margin = new Thickness(12) }; + pila.Children.Add(img); + pila.Children.Add(nome); + pila.Children.Add(sotto); + w.Content = new Border + { + CornerRadius = new CornerRadius(12), Child = pila, Background = new SolidColorBrush(Color.FromArgb(230, 18, 16, 26)), + BorderBrush = new SolidColorBrush(Color.FromArgb(80, 255, 213, 74)), BorderThickness = new Thickness(1), + }; + var area = SystemParameters.WorkArea; + w.Left = area.Right - 300; + w.Top = area.Bottom - 150; + w.MouseLeftButtonUp += (_, _) => { Programma.Mostra(percorso); w.Close(); }; + w.Loaded += (_, _) => w.BeginAnimation(UIElement.OpacityProperty, new DoubleAnimation(0, 1, TimeSpan.FromMilliseconds(180))); + w.Show(); + var t = new System.Windows.Threading.DispatcherTimer { Interval = TimeSpan.FromSeconds(4.5) }; + t.Tick += (_, _) => { t.Stop(); if (w.IsVisible) w.Close(); }; + t.Start(); + } + + delegate bool EnumProc(IntPtr h, IntPtr l); + [StructLayout(LayoutKind.Sequential)] struct RECT { public int Left, Top, Right, Bottom; } + + [DllImport("user32.dll")] static extern bool RegisterHotKey(IntPtr h, int id, uint mod, uint vk); + [DllImport("user32.dll")] static extern bool UnregisterHotKey(IntPtr h, int id); + [DllImport("user32.dll")] static extern bool EnumWindows(EnumProc cb, IntPtr l); + [DllImport("user32.dll")] static extern bool IsWindowVisible(IntPtr h); + [DllImport("user32.dll")] static extern int GetWindowTextLength(IntPtr h); + [DllImport("user32.dll")] static extern bool GetWindowRect(IntPtr h, out RECT r); + [DllImport("dwmapi.dll")] static extern int DwmGetWindowAttribute(IntPtr h, int attr, out int v, int size); + [DllImport("dwmapi.dll")] static extern int DwmGetWindowAttribute(IntPtr h, int attr, out RECT r, int size); + [DllImport("gdi32.dll")] static extern bool DeleteObject(IntPtr o); +} diff --git a/src/DaPConvertitore/Vassoio.cs b/src/DaPConvertitore/Vassoio.cs new file mode 100644 index 0000000..e19618e --- /dev/null +++ b/src/DaPConvertitore/Vassoio.cs @@ -0,0 +1,92 @@ +using System.Drawing; +using System.Windows; +using System.Windows.Forms; + +namespace DaP.Convertitore.App; + +/// +/// L'icona nell'area di notifica finché l'app è aperta: apri, screenshot, registra, impostazioni, esci. +/// +public static class Vassoio +{ + static NotifyIcon? icona; + + public static void Avvia(System.Windows.Application app) + { + if (icona is not null) return; + Icon? ico = null; + try { if (Environment.ProcessPath is { } exe) ico = Icon.ExtractAssociatedIcon(exe); } catch { /* l'icona di sistema */ } + icona = new NotifyIcon + { + Icon = ico ?? SystemIcons.Application, + Visible = true, + Text = "DaP Convertitore", + }; + var menu = new ContextMenuStrip(); + menu.Items.Add("Apri", null, (_, _) => SulFilo(() => Regia.Gestisci(new Richiesta(null, [], true)))); + menu.Items.Add("Screenshot", null, (_, _) => SulFilo(Schermata.Cattura)); + var registra = new ToolStripMenuItem("Registra…"); + var apriRegistra = false; + registra.Click += (_, _) => + { + apriRegistra = true; + Registro.Scrivi("registrazione: clic su Registra nel vassoio"); + }; + // il menu di Windows è ancora aperto durante il clic: la finestra si apre quando si è chiuso, + // se no nasce dentro quel ciclo e non si vede + menu.Closed += (_, _) => + { + if (!apriRegistra) return; + apriRegistra = false; + try { Registrazione.Chiedi("vassoio"); } + catch (Exception e) { Registro.Errore("registrazione: vassoio", e); } + }; + menu.Items.Add(registra); + var sistema = false; + var avatar = new ToolStripMenuItem("Avatar") { CheckOnClick = true, Checked = Regia.AvatarAcceso }; + avatar.CheckedChanged += (_, _) => + { + if (sistema) return; + SulFilo(() => Regia.Avatar(avatar.Checked)); + }; + Regia.AvatarCambiato += acceso => SulFilo(() => + { + sistema = true; + avatar.Checked = acceso; + sistema = false; + }); + menu.Opening += (_, _) => + { + registra.Text = Registrazione.Attiva ? "La registrazione è in corso" : "Registra…"; + sistema = true; + avatar.Checked = Regia.AvatarAcceso; + sistema = false; + }; + menu.Items.Add(avatar); + menu.Items.Add("Impostazioni", null, (_, _) => SulFilo(Regia.ApriImpostazioni)); + menu.Items.Add(new ToolStripSeparator()); + menu.Items.Add("Esci", null, (_, _) => SulFilo(() => app.Shutdown())); + icona.ContextMenuStrip = menu; + icona.DoubleClick += (_, _) => SulFilo(() => Regia.Gestisci(new Richiesta(null, [], true))); + } + + public static void Dire(string titolo, string testo) + { + try { icona?.ShowBalloonTip(4000, titolo, testo, ToolTipIcon.Info); } catch { /* il vassoio può non esserci */ } + } + + public static void Chiudi() + { + if (icona is null) return; + icona.Visible = false; + icona.Dispose(); + icona = null; + } + + static void SulFilo(Action fai) + { + var d = System.Windows.Application.Current?.Dispatcher; + if (d is null || d.CheckAccess()) fai(); + else d.Invoke(fai); + } +} diff --git a/test/DaPConvertitore.Prove/ProveModifiche.cs b/test/DaPConvertitore.Prove/ProveModifiche.cs index ab10ec0..21066a5 100644 --- a/test/DaPConvertitore.Prove/ProveModifiche.cs +++ b/test/DaPConvertitore.Prove/ProveModifiche.cs @@ -145,6 +145,20 @@ public async Task IlPezzoTagliatoVaAccantoEPesaMeno() await Assert.ThrowsAsync(() => Modifiche.TagliaVideo(b.Strumenti, mp4, 5, 2)); } + [Fact] + public async Task IPezziSiRimontanoAccantoELoriginaleResta() + { + var mp4 = b.Ffmpeg("pezzi.mp4", "-f", "lavfi", "-i", "testsrc2=s=160x90:r=25:d=2", "-c:v", "libx264", "-g", "1", "-pix_fmt", "yuv420p", "-preset", "ultrafast"); + var prima = (await Sonda.Leggi(b.Strumenti, mp4)).Durata; + var dest = await Modifiche.TagliaPezzi(b.Strumenti, mp4, [(0, 0.4), (1.2, 1.8)]); + Assert.Contains("(tagliato)", dest); + Assert.True(File.Exists(mp4)); + var dopo = await Sonda.Leggi(b.Strumenti, dest); + Assert.InRange(dopo.Durata, 0.55, 1.5); + var orig = await Sonda.Leggi(b.Strumenti, mp4); + Assert.InRange(orig.Durata, prima - 0.15, prima + 0.15); + } + [Fact] public async Task IlPdfSiGiraPaginaPerPagina() { diff --git a/test/DaPConvertitore.Prove/ProveRegistrazione.cs b/test/DaPConvertitore.Prove/ProveRegistrazione.cs new file mode 100644 index 0000000..a567e3e --- /dev/null +++ b/test/DaPConvertitore.Prove/ProveRegistrazione.cs @@ -0,0 +1,252 @@ +namespace DaP.Convertitore.Prove; + +/// +/// Il comando di FFmpeg e la strada «Registra» (vassoio, avatar, ponte) senza finestre e senza FFmpeg. +/// +public class ProveRegistrazione +{ + const string Mic = "Microphone (Realtek(R) Audio)"; + const string Casse = "Speakers (Realtek(R) Audio)"; + + [Fact] + public void IlMenuIlVassoioEIlPonteFannoLaStessaCosa() + { + foreach (var da in ComandiRegistrazione.Origini) + { + Assert.Equal(ComandiRegistrazione.ApriMenu, ComandiRegistrazione.CosaFa(da, false)); + Assert.Equal(ComandiRegistrazione.PortaBarra, ComandiRegistrazione.CosaFa(da, true)); + } + Assert.Equal(3, ComandiRegistrazione.Origini.Length); + Assert.Contains("vassoio", ComandiRegistrazione.Origini); + Assert.Contains("avatar", ComandiRegistrazione.Origini); + Assert.Contains("ponte", ComandiRegistrazione.Origini); + } + + [Fact] + public void SoloAudioSenzaDispositiviNonParte() + { + Assert.Null(ComandiRegistrazione.MotivoRifiuto("schermo", null, null)); + Assert.Null(ComandiRegistrazione.MotivoRifiuto("audio", Mic, null)); + Assert.Null(ComandiRegistrazione.MotivoRifiuto("audio", null, Casse)); + Assert.NotNull(ComandiRegistrazione.MotivoRifiuto("audio", null, null)); + Assert.NotNull(ComandiRegistrazione.MotivoRifiuto("audio", " ", "")); + } + + [Fact] + public void LoSchermoPrendeIlMonitorPrincipaleEIlMicrofonoEUnArgomentoSolo() + { + var a = ComandiRegistrazione.Argomenti("schermo", Mic, null, @"C:\out\reg.mp4", new ComandiRegistrazione.Schermo(-1920, 0, 1921, 1080)).ToList(); + var testo = string.Join("\n", a); + Assert.Contains("-f", a); + Assert.Contains("gdigrab", a); + Assert.Contains("desktop", a); + Assert.Equal("-1920", a[a.IndexOf("-offset_x") + 1]); + Assert.Equal("1920x1080", a[a.IndexOf("-video_size") + 1]); + var ingresso = a[a.IndexOf("-i", a.IndexOf("dshow")) + 1]; + Assert.Equal("audio=" + Mic, ingresso); + Assert.DoesNotContain("\"", ingresso); + Assert.Contains("-c:v", a); + Assert.Contains("libx264", a); + Assert.Contains("-map", a); + Assert.Equal("0:v", a[a.IndexOf("-map") + 1]); + Assert.Equal("1:a", a[a.LastIndexOf("-map") + 1]); + Assert.DoesNotContain("-filter_complex", a); + Assert.Equal(@"C:\out\reg.mp4", a[^1]); + Assert.Contains("-use_wallclock_as_timestamps", a); + Assert.DoesNotContain("wasapi", testo.Split('\n')); + } + + [Fact] + public void DueAudioSiMescolanoSenzaUsareVfInsiemeAlFiltro() + { + var a = ComandiRegistrazione.Argomenti("schermo", Mic, Casse, "out.mp4", new ComandiRegistrazione.Schermo(0, 0, 1280, 720)).ToList(); + Assert.Contains("-filter_complex", a); + Assert.DoesNotContain("-vf", a); + var filtro = a[a.IndexOf("-filter_complex") + 1]; + Assert.Contains("amix=inputs=2", filtro); + Assert.Contains("scale=trunc(iw/2)*2:trunc(ih/2)*2", filtro); + Assert.Equal("[v]", a[a.IndexOf("-map") + 1]); + Assert.Equal("[a]", a[a.LastIndexOf("-map") + 1]); + Assert.Equal("audio=" + Mic, a[a.IndexOf("-i", a.IndexOf("dshow")) + 1]); + var wasapi = a.IndexOf("wasapi"); + Assert.Equal("1", a[a.IndexOf("-loopback") + 1]); + Assert.Equal(Casse, a[a.IndexOf("-i", wasapi) + 1]); + Assert.DoesNotContain("\"", a[a.IndexOf("-i", wasapi) + 1]); + } + + [Fact] + public void SoloAudioEUnM4aSenzaVideo() + { + var a = ComandiRegistrazione.Argomenti("audio", null, Casse, "out.m4a", null).ToList(); + Assert.DoesNotContain("gdigrab", a); + Assert.DoesNotContain("libx264", a); + Assert.Contains("wasapi", a); + Assert.Contains("aac", a); + Assert.Equal("192k", a[a.IndexOf("-b:a") + 1]); + Assert.Equal("out.m4a", a[^1]); + Assert.DoesNotContain("dshow", a); + } + + [Fact] + public void SoloAudioConMicrofonoECasseHaIlFiltroSuiDueIngressi() + { + var a = ComandiRegistrazione.Argomenti("audio", Mic, Casse, "out.m4a", null).ToList(); + var filtro = a[a.IndexOf("-filter_complex") + 1]; + Assert.Contains("[0:a][1:a]amix=inputs=2", filtro); + Assert.DoesNotContain("scale=", filtro); + Assert.Equal("[a]", a[a.IndexOf("-map") + 1]); + } + + [Fact] + public void LoSchermoSenzaAudioNonChiedeUnaTracciaAudio() + { + var a = ComandiRegistrazione.Argomenti("schermo", null, " ", "film.mp4", null).ToList(); + Assert.Contains("gdigrab", a); + Assert.Contains("desktop", a); + Assert.DoesNotContain("-offset_x", a); + Assert.DoesNotContain("dshow", a); + Assert.DoesNotContain("wasapi", a); + Assert.DoesNotContain("-c:a", a); + Assert.DoesNotContain("-map", a); + Assert.Equal("film.mp4", a[^1]); + } + + [Fact] + public void LeVirgoletteDelNomeNonEntranoNelDispositivo() + { + Assert.Equal("audio=Cuffie", ComandiRegistrazione.ArgomentoDshow("\"Cuffie\"")); + Assert.Equal("Cuffie", ComandiRegistrazione.ArgomentoWasapi(" \"Cuffie\" ")); + var riga = ComandiRegistrazione.Riga(ComandiRegistrazione.Argomenti("audio", Mic, null, "a.m4a", null)); + Assert.Contains("\"audio=" + Mic + "\"", riga); + } + + [Fact] + public void LElencoDshowTieneIMicrofoniENonLaWebcam() + { + var testo = """ + [dshow @ 1] DirectShow video devices (some may be both video and audio devices) + [dshow @ 1] "Integrated Camera" + [dshow @ 1] Alternative name "@device_pnp_\\?\usb#vid" + [dshow @ 1] DirectShow audio devices + [dshow @ 1] "Microphone (Realtek(R) Audio)" + [dshow @ 1] Alternative name "@device_cm_{33D9A762}\\wave" + [dshow @ 1] "Stereo Mix (Realtek(R) Audio)" + """; + var nomi = ComandiRegistrazione.MicrofoniDaElenco(testo); + Assert.Equal(new[] { "Microphone (Realtek(R) Audio)", "Stereo Mix (Realtek(R) Audio)" }, nomi); + } + + [Fact] + public void LElencoWasapiTieneLeUsciteENonIlMicrofono() + { + var testo = """ + [wasapi @ 1] "Speakers (Realtek(R) Audio)" (playback) (default) + [wasapi @ 1] "Headphones" (playback) + [wasapi @ 1] "Microphone (Realtek(R) Audio)" (capture) + """; + var nomi = ComandiRegistrazione.UsciteDaElenco(testo); + Assert.Equal(new[] { "Speakers (Realtek(R) Audio)", "Headphones" }, nomi); + } + + [Fact] + public void SenzaLaParolaPlaybackRestanoTuttiTranneIlCapture() + { + var testo = """ + [wasapi @ 1] "Casse" + [wasapi @ 1] "Mic" (capture) + """; + Assert.Equal(new[] { "Casse" }, ComandiRegistrazione.UsciteDaElenco(testo)); + } + + [Fact] + public void FpsQualitaCursoreEFinestraEntranoNelComando() + { + Assert.Equal(30, ComandiRegistrazione.FpsDi(24)); + Assert.Equal(60, ComandiRegistrazione.FpsDi(60)); + Assert.Equal(18, ComandiRegistrazione.CrfDi("alta")); + Assert.Equal(28, ComandiRegistrazione.CrfDi("leggera")); + Assert.Equal(23, ComandiRegistrazione.CrfDi(null)); + var a = ComandiRegistrazione.Argomenti("finestra", null, null, "out.mp4", new ComandiRegistrazione.Schermo(0, 0, 800, 600), 60, 18, false, "Blocco note").ToList(); + Assert.Equal("60", a[a.IndexOf("-framerate") + 1]); + Assert.Equal("0", a[a.IndexOf("-draw_mouse") + 1]); + Assert.Equal("18", a[a.IndexOf("-crf") + 1]); + Assert.Contains("title=Blocco note", a); + Assert.DoesNotContain("desktop", a); + Assert.DoesNotContain("-offset_x", a); + Assert.Equal("Scegli la zona da registrare.", ComandiRegistrazione.MotivoRifiuto("zona", null, null, zonaSenzaRettangolo: true)); + Assert.Equal("Scegli la finestra da registrare.", ComandiRegistrazione.MotivoRifiuto("finestra", null, null, finestraSenzaTitolo: true)); + var zona = ComandiRegistrazione.Argomenti("zona", null, null, "z.mp4", new ComandiRegistrazione.Schermo(100, 80, 640, 480), 30, 28, true, null).ToList(); + Assert.Contains("desktop", zona); + Assert.Equal("640x480", zona[zona.IndexOf("-video_size") + 1]); + Assert.Equal("28", zona[zona.IndexOf("-crf") + 1]); + Assert.Equal(new[] { "Blocco note", "Chrome" }, ComandiRegistrazione.TitoliUtili(["", "Registra", "Blocco note", "Blocco note", "Program Manager", "Chrome"])); + Assert.Contains("-vcodec", ComandiRegistrazione.ArgomentiFotogramma("film.mp4").ToList()); + } + + [Fact] + public void LaFinestraRestaNelMonitorDellAvatarAncheSeENegativo() + { + var area = new Ancoraggio.Riquadro(-1920, 0, 1920, 1040); + var avatar = new Ancoraggio.Riquadro(-180, 800, 140, 140); + var dove = Ancoraggio.Accanto(avatar, 400, 500, area); + Assert.True(Ancoraggio.Dentro(dove, area)); + Assert.True(dove.X < 0, "deve restare sul monitor a sinistra, non sul principale"); + // l'avatar è contro il bordo destro: a destra non ci sta, quindi va a sinistra + Assert.True(dove.Destra <= avatar.X); + } + + [Fact] + public void UnAvatarFuoriDalloSchermoNonPortaLaFinestraFuori() + { + var area = new Ancoraggio.Riquadro(0, 0, 1920, 1080); + var dove = Ancoraggio.Accanto(new Ancoraggio.Riquadro(5000, 4000, 120, 120), 400, 300, area); + Assert.True(Ancoraggio.Dentro(dove, area)); + var centro = Ancoraggio.Centro(400, 300, area); + Assert.Equal(760, centro.X); + Assert.Equal(390, centro.Y); + Assert.True(Ancoraggio.Dentro(centro, area)); + var stretto = Ancoraggio.Accanto(new Ancoraggio.Riquadro(10, 10, 80, 80), 400, 200, area); + Assert.True(Ancoraggio.Dentro(stretto, area)); + Assert.True(stretto.X >= 10 + 80); + } + + [Fact] + public void LaChiaveDelMonitorSiLeggeESiRiscrive() + { + var r = new Ancoraggio.Riquadro(-1920, 12, 1920, 1080); + Assert.True(Ancoraggio.ProvaChiave(Ancoraggio.Chiave(r), out var diNuovo)); + Assert.Equal(r, diNuovo); + Assert.False(Ancoraggio.ProvaChiave("no", out _)); + Assert.True(Ancoraggio.Tocca(r, new Ancoraggio.Riquadro(-10, 0, 20, 20))); + Assert.False(Ancoraggio.Tocca(r, new Ancoraggio.Riquadro(100, 0, 20, 20))); + } + + [Fact] + public void ScreenshotERegistrazioneEntranoNeiRecentiSenzaContareComeConversione() + { + var dir = Path.Combine(Path.GetTempPath(), "dap-storico-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(dir); + var prima = Environment.GetEnvironmentVariable("DAP_DATI"); + Environment.SetEnvironmentVariable("DAP_DATI", dir); + try + { + var file = Path.Combine(dir, "schermo.png"); + File.WriteAllBytes(file, [1, 2, 3, 4]); + Storico.AggiungiFile(file, "Screenshot"); + var (recenti, totali) = Storico.Recenti(6); + Assert.Single(recenti); + Assert.Equal(file, recenti[0].Uscita); + Assert.Equal("Screenshot", recenti[0].Formato); + Assert.Equal("immagine", recenti[0].Categoria); + Assert.Equal(4, recenti[0].PesoDopo); + Assert.Equal(0, totali.Conversioni); + File.Delete(file); + Assert.Empty(Storico.Recenti(6).Recenti); + } + finally + { + Environment.SetEnvironmentVariable("DAP_DATI", prima); + try { Directory.Delete(dir, true); } catch { /* il temp la toglie dopo */ } + } + } +} diff --git a/test/DaPConvertitore.Prove/ProveScheda.cs b/test/DaPConvertitore.Prove/ProveScheda.cs new file mode 100644 index 0000000..dd4bd7d --- /dev/null +++ b/test/DaPConvertitore.Prove/ProveScheda.cs @@ -0,0 +1,192 @@ +using DaP.Convertitore.Lettore; + +namespace DaP.Convertitore.Prove; + +/// Copertine disegnate e nomi accanto: non serve FFmpeg. +public class ProveCopertine +{ + [Fact] + public void IlNomeAccantoNonSovrascrive() + { + var dir = Path.Combine(Path.GetTempPath(), "dap-copertina-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(dir); + try + { + File.WriteAllBytes(Path.Combine(dir, "brano (copertina).jpg"), [1]); + var primo = Copertine.NomeLibero(dir, "brano", ".jpg"); + Assert.Equal(Path.Combine(dir, "brano (copertina 2).jpg"), primo); + File.WriteAllBytes(primo, [2]); + var secondo = Copertine.NomeLibero(dir, "brano", ".jpg"); + Assert.EndsWith("(copertina 3).jpg", secondo); + } + finally { Directory.Delete(dir, true); } + } + + [Fact] + public void LeCopertineDisegnateSonoPngUgualiPerLoStessoTitolo() + { + var a = Copertine.Genera("Poco dopo lo zero", 0, null); + var b = Copertine.Genera("Poco dopo lo zero", 0, null); + var c = Copertine.Genera("Poco dopo lo zero", 1, null); + var d = Copertine.Genera("Altro titolo", 3, null); + Assert.Equal(a, b); + Assert.NotEqual(a, c); + Assert.NotEqual(a, d); + Assert.Equal(new byte[] { 137, 80, 78, 71, 13, 10, 26, 10 }, a[..8]); + Assert.True(a.Length > 1000); + // IHDR: larghezza subito dopo la firma, la lunghezza e il tipo + Assert.Equal(Copertine.Lato, (a[16] << 24) | (a[17] << 16) | (a[18] << 8) | a[19]); + Assert.Equal(Copertine.Lato, (a[20] << 24) | (a[21] << 16) | (a[22] << 8) | a[23]); + } + + [Fact] + public void IlVideoTieneLaCopertinaDentroIlFile() + { + Assert.True(Copertine.VideoNelFile("film.mp4")); + Assert.True(Copertine.VideoNelFile("film.MKV")); + Assert.True(Copertine.DentroIlFile("film.mov")); + Assert.False(Copertine.VideoNelFile("film.webm")); + Assert.False(Copertine.AudioNelFile("film.mp4")); + } + + [Fact] + public void LaCartellaDeiLavoriStaFraLeImmagini() + { + var p = CartellaLavori.DiSistema(); + Assert.EndsWith(CartellaLavori.Nome, p); + Assert.Contains("DaPConvertitore", p); + } + + [Fact] + public void ICampiSonoQuelliCheIlFormatoTiene() + { + Assert.Contains("copertina", Metadati.Campi(".mp3")); + Assert.Contains("artista", Metadati.Campi(".FLAC")); + Assert.DoesNotContain("copertina", Metadati.Campi(".wav")); + Assert.DoesNotContain("copertina", Metadati.Campi(".ogg")); + Assert.Equal(new[] { "titolo", "commento" }, Metadati.Campi(".mkv")); + Assert.Equal(new[] { "data", "descrizione", "autore" }, Metadati.Campi(".jpg")); + Assert.Empty(Metadati.Campi(".png")); + Assert.Equal(new DateTime(2024, 3, 12), Metadati.DataDi("2024-03-12")!.Value.Date); + Assert.Equal(2026, Metadati.DataDi("2026")!.Value.Year); + Assert.Equal(12, Metadati.DataDi("12/03/2024")!.Value.Day); + Assert.Null(Metadati.DataDi("ieri")); + } +} + +/// I tag e la copertina scritti davvero, nel convertito o nel file, con la bozza che non tocca l'originale se fallisce. +[Collection("banco")] +public class ProveScheda(Banco b) +{ + [Fact] + public async Task CopertinaNelFileEOriginaleIntattoSeMancaLImmagine() + { + var mp3 = b.Ffmpeg("dentro.mp3", "-f", "lavfi", "-i", "sine=f=440:d=1", "-c:a", "libmp3lame", "-q:a", "7", "-metadata", "title=Ciao"); + var prima = await File.ReadAllBytesAsync(mp3); + await Assert.ThrowsAsync(() => Copertine.ScriviNelFile(b.Strumenti, mp3, Path.Combine(b.Cartella, "non-c-e.png"))); + Assert.Equal(prima, await File.ReadAllBytesAsync(mp3)); + + var png = Path.Combine(b.Cartella, "cover-gen.png"); + await File.WriteAllBytesAsync(png, Copertine.Genera("Ciao", 2, null)); + await Copertine.ScriviNelFile(b.Strumenti, mp3, png); + var info = await Sonda.Leggi(b.Strumenti, mp3); + Assert.True(info.Copertina); + var scheda = await Media.Leggi(b.Strumenti, mp3); + Assert.Equal("Ciao", scheda.Tag["title"]); + var jpg = await Media.Copertina(b.Strumenti, mp3, true); + Assert.NotNull(jpg); + Assert.True(jpg!.Length > 100); + + var salvata = await Copertine.SalvaAccanto(b.Strumenti, mp3); + Assert.EndsWith("dentro (copertina).jpg", salvata.Replace('\\', '/')); + Assert.True(new FileInfo(salvata).Length > 100); + var seconda = await Copertine.SalvaAccanto(b.Strumenti, mp3); + Assert.EndsWith("(copertina 2).jpg", seconda); + Assert.True(File.Exists(salvata)); + } + + [Fact] + public async Task ITagELaCopertinaFinisconoNelConvertito() + { + var wav = b.Ffmpeg("scheda.wav", "-f", "lavfi", "-i", "sine=f=330:d=1", "-metadata", "title=Vecchio"); + var o = new Opzioni + { + Audio = { Kbps = 128 }, + Scheda = new OpzioniScheda + { + Scrivi = true, + Titolo = "Poco dopo lo zero", + Artista = "DaProd", + Album = "Notte", + Anno = "2026", + Traccia = "4", + Copertina = "generata:0", + }, + }; + var l = await b.Converti(wav, "audio.mp3", o); + var s = await Media.Leggi(b.Strumenti, l.Uscita!); + Assert.Equal("Poco dopo lo zero", s.Tag["title"]); + Assert.Equal("DaProd", s.Tag["artist"]); + Assert.Equal("Notte", s.Tag["album"]); + Assert.Contains("2026", s.Tag["date"]); + Assert.StartsWith("4", s.Tag["track"]); + Assert.True(s.Info.Copertina); + // l'originale non viene riscritto + var orig = await Media.Leggi(b.Strumenti, wav); + Assert.False(orig.Info.Copertina); + Assert.True(new FileInfo(wav).Length > 0); + } + + [Fact] + public async Task LaCopertinaDelVideoEUnFotogrammaAllegato() + { + var mp4 = b.Ffmpeg("film-cover.mp4", "-f", "lavfi", "-i", "testsrc2=s=160x90:r=15:d=1", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-preset", "ultrafast"); + var png = Path.Combine(b.Cartella, "cover-video.png"); + await File.WriteAllBytesAsync(png, Copertine.Genera("Film", 1, null)); + var prima = await File.ReadAllBytesAsync(mp4); + await Copertine.ScriviNelFile(b.Strumenti, mp4, png); + Assert.NotEqual(prima, await File.ReadAllBytesAsync(mp4)); + var info = await Sonda.Leggi(b.Strumenti, mp4); + Assert.True(info.Copertina); + Assert.True(info.IndiceCopertina >= 0); + Assert.Equal(1, info.VideoVeri); + var jpg = await Copertine.EstraiAllegata(b.Strumenti, mp4, info.IndiceCopertina, 160, true); + Assert.NotNull(jpg); + Assert.True(jpg!.Length > 80); + Assert.InRange(info.Durata, 0.4, 2.5); + } + + [Fact] + public async Task IlVideoConvertitoTieneTitoloECommento() + { + var mp4 = b.Ffmpeg("film-scheda.mp4", "-f", "lavfi", "-i", "testsrc2=s=160x90:r=15:d=1", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-preset", "ultrafast"); + var o = new Opzioni + { + Video = { Modo = "copia" }, + Scheda = new OpzioniScheda { Scrivi = true, Titolo = "Episodio", Commento = "Una nota" }, + }; + var l = await b.Converti(mp4, "video.mkv", o); + var s = await Media.Leggi(b.Strumenti, l.Uscita!); + Assert.Equal("Episodio", s.Tag["title"]); + var commento = s.Tag.TryGetValue("comment", out var c) ? c : s.Tag["description"]; + Assert.Equal("Una nota", commento); + } + + [Fact] + public async Task LaFotoConvertitaTieneAutoreEData() + { + var png = b.Ffmpeg("scheda-foto.png", "-f", "lavfi", "-i", "testsrc2=s=320x200", "-frames:v", "1"); + var o = new Opzioni + { + Immagine = { Qualita = 90, Modo = "qualita" }, + Scheda = new OpzioniScheda { Scrivi = true, Autore = "Cammo", Descrizione = "Il mare", DataScatto = "2024-03-12" }, + }; + var l = await b.Converti(png, "img.jpg", o); + var letti = await Immagini.LeggiTesti(l.Uscita!); + Assert.Equal("Cammo", letti.Autore); + Assert.Contains("mare", letti.Descrizione); + Assert.Equal(2024, letti.Data!.Value.Year); + Assert.Equal(3, letti.Data.Value.Month); + Assert.Equal(12, letti.Data.Value.Day); + } +} diff --git a/ui/src/app/colonna.ts b/ui/src/app/colonna.ts index 9f5e75d..d3a5707 100644 --- a/ui/src/app/colonna.ts +++ b/ui/src/app/colonna.ts @@ -5,7 +5,7 @@ import { chiedi } from '../ponte'; import type { InfoFile } from '../ponte'; import { h, durata } from '../util'; -import { iconaCategoria, coloreCategoria } from '../icone'; +import { iconaCategoria, coloreCategoria, icone } from '../icone'; interface Indice { tipo: 'pagine' | 'tempo' | 'singola'; voci: number; totale: number; punti: number[] } @@ -21,7 +21,6 @@ export interface Colonna { const LATO_FIGURINA = 160; const LATO_GRANDE = 720; /** Quanto dura il «tic» di suono quando il cursore scorre su un brano senza che tu abbia cliccato. */ -const SUONO_BREVE_MS = 260; const SALTO = 5; export function creaColonna(apri: () => void, pronto: () => void = () => {}): Colonna { @@ -36,7 +35,24 @@ export function creaColonna(apri: () => void, pronto: () => void = () => {}): Co const barra = h('div.cl-barra', { tabindex: '0', role: 'slider', 'aria-label': 'Posizione', hidden: true }, riempi); const grande = h('div.cl-grande', null, figura, barra, etichetta); const strisce = h('div.cl-strisce', { tabindex: '0', role: 'listbox', 'aria-label': 'Indice dell\'anteprima' }); - const el = h('div.ap-colonna', null, grande, strisce); + const bPlay = h('button.cl-play', { type: 'button', title: 'Play / pausa', html: icone.play, onclick: () => alterna() }); + const tempoSuono = h('div.cl-tempo', null, '—'); + const vol = h('input.cl-vol', { type: 'range', min: '0', max: '1', step: '0.01', value: '1', 'aria-label': 'Volume' }); + const audioEl = h('audio.cl-audio', { preload: 'auto' }); + audioEl.hidden = true; + vol.addEventListener('input', () => { audioEl.volume = +vol.value; video.volume = +vol.value; }); + video.volume = +vol.value; + const bQuadro = h('button.cl-quadro', { type: 'button', title: 'Salva questo fotogramma in Immagini\\DaPConvertitore', onclick: () => void salvaQuadro() }, 'Fotogramma'); + const tasti = h('div.cl-tasti', null, '← → fotogramma · J K L'); + const suono = h('div.cl-suono', null, + bPlay, + tempoSuono, + bQuadro, + h('div.cl-vol-etichetta', null, 'VOLUME'), + vol, + tasti, + audioEl); + const el = h('div.ap-colonna', { tabindex: '-1' }, grande, suono, strisce); let gettone = 0; // cambia a ogni file: le risposte in ritardo si scartano let file: InfoFile | null = null; @@ -54,13 +70,13 @@ export function creaColonna(apri: () => void, pronto: () => void = () => {}): Co let scrub: 'video' | 'foto' | 'audio' | 'muto' | null = null; let audio: HTMLAudioElement | null = null; let suona = false; // il clic ha fatto partire la riproduzione + let vuoleSuonare = false; // play premuto prima che il file sia pronto let posizione = 0; // secondi let ultimaRichiesta = -1; let inVolo = false; let pendenteFoto: number | null = null; let pendenteSeek: number | null = null; let rafSeek = 0; - let spegniSuono = 0; let ondaPiena = false; // l'onda intera del brano è arrivata const durataTot = () => (indice?.tipo === 'tempo' ? indice.totale : 0); const media = (): HTMLMediaElement | null => (scrub === 'video' ? video : scrub === 'audio' ? audio : null); @@ -83,7 +99,7 @@ export function creaColonna(apri: () => void, pronto: () => void = () => {}): Co function mostraPosizione(t: number) { const tot = durataTot(); - if (!tot) return; + if (!tot) { posizione = Math.max(0, t); tempoSuono.textContent = durata(posizione); return; } posizione = Math.max(0, Math.min(tot, t)); const p = `${((posizione / tot) * 100).toFixed(2)}%`; riempi.style.width = p; @@ -91,6 +107,7 @@ export function creaColonna(apri: () => void, pronto: () => void = () => {}): Co barra.setAttribute('aria-valuenow', String(Math.round(posizione))); barra.setAttribute('aria-valuemax', String(Math.round(tot))); etichetta.textContent = `${durata(posizione)} di ${durata(tot)}${suona ? ' · in riproduzione' : ''}`; + tempoSuono.textContent = `${durata(posizione)} / ${durata(tot)}`; } /** Dove cade il cursore sulla figura, in secondi. */ @@ -100,7 +117,7 @@ export function creaColonna(apri: () => void, pronto: () => void = () => {}): Co } /** Il fotogramma (o il punto del brano) di quel secondo: se ne chiede uno solo per volta, conta l'ultimo. */ - function vaiA(t: number, suonoBreve: boolean) { + function vaiA(t: number) { mostraPosizione(t); if (scrub === 'video' || scrub === 'audio') { pendenteSeek = posizione; @@ -114,12 +131,7 @@ export function creaColonna(apri: () => void, pronto: () => void = () => {}): Co pendenteSeek = null; }); if (scrub === 'video') { video.hidden = false; img.hidden = true; segnaposto.hidden = true; } - if (scrub === 'audio' && suonoBreve && !suona && audio) { - // si sente il punto dove sta il cursore, poi tace da solo - if (audio.paused) void audio.play().catch(() => {}); - clearTimeout(spegniSuono); - spegniSuono = window.setTimeout(() => { if (!suona) audio?.pause(); }, SUONO_BREVE_MS); - } + // l'audio non si sente passando il cursore: ci si sposta dalla timeline, e si sente solo col play } else if (scrub === 'foto') { pendenteFoto = posizione; void pompaFoto(); @@ -146,9 +158,10 @@ export function creaColonna(apri: () => void, pronto: () => void = () => {}): Co function parti(t: number) { const m = media(); - if (!m) return; + if (!m) { vuoleSuonare = true; return; } + vuoleSuonare = false; suona = true; - clearTimeout(spegniSuono); + bPlay.innerHTML = icone.pausa; m.muted = false; try { m.currentTime = t; } catch { /* sotto */ } mostraPosizione(t); @@ -159,24 +172,25 @@ export function creaColonna(apri: () => void, pronto: () => void = () => {}): Co function pausa() { suona = false; - clearTimeout(spegniSuono); + bPlay.innerHTML = icone.play; media()?.pause(); figura.classList.remove('suona'); barra.classList.remove('suona'); mostraPosizione(posizione); } - const alterna = (t = posizione) => { if (suona) pausa(); else parti(t); }; + const alterna = (t = posizione) => { if (suona) { vuoleSuonare = false; pausa(); } else parti(t); }; function spegniMedia() { suona = false; - clearTimeout(spegniSuono); + bPlay.innerHTML = icone.play; cancelAnimationFrame(rafSeek); rafSeek = 0; pendenteSeek = null; pendenteFoto = null; ultimaRichiesta = -1; - for (const m of [video, audio]) if (m) { m.pause(); m.removeAttribute('src'); m.load(); } + vuoleSuonare = false; + for (const m of [video, audioEl]) { m.pause(); m.removeAttribute('src'); m.load(); } audio = null; scrub = null; ondaPiena = false; @@ -189,30 +203,54 @@ export function creaColonna(apri: () => void, pronto: () => void = () => {}): Co /** Il file vero per il tag video/audio: se la pagina lo suona lo scrub è al volo, se no resta quello di FFmpeg. */ async function preparaScrub(f: InfoFile, g: number) { - scrub = f.categoria === 'video' ? 'foto' : 'muto'; + const eAudio = f.categoria === 'audio'; + scrub = eAudio ? 'audio' : 'foto'; barra.hidden = false; - testina.hidden = f.categoria !== 'audio'; - figura.classList.add('scorre'); - figura.classList.toggle('onda', f.categoria === 'audio'); - mostraPosizione(indice!.punti[0] ?? 0); + testina.hidden = true; + figura.classList.toggle('scorre', !eAudio); + figura.classList.toggle('onda', eAudio); + mostraPosizione(eAudio ? 0 : (indice!.punti[0] ?? 0)); let fonte: string | null = null; try { fonte = (await chiedi<{ url: string | null }>('fonteAnteprima', { id: f.id })).url; } catch { /* resta com'è */ } - if (g !== gettone || !fonte) return; + if (g !== gettone || !fonte) { + if (eAudio && g === gettone) tempoSuono.textContent = 'non si sente'; + return; + } if (f.categoria === 'video') { - video.onloadeddata = () => { if (g === gettone && scrub === 'foto') { scrub = 'video'; } }; + video.onloadeddata = () => { + if (g !== gettone || scrub !== 'foto') return; + scrub = 'video'; + video.hidden = false; + img.hidden = true; + segnaposto.hidden = true; + if (vuoleSuonare) parti(posizione); + }; video.onerror = () => { if (g === gettone && scrub === 'video') { scrub = 'foto'; video.hidden = true; img.hidden = false; } }; video.ontimeupdate = () => { if (g === gettone && suona) mostraPosizione(video.currentTime); }; video.onended = () => { if (g === gettone) pausa(); }; video.src = fonte; } else { - const a = new Audio(); + const a = audioEl; a.preload = 'auto'; + a.volume = +vol.value; audio = a; - a.onloadedmetadata = () => { if (g === gettone && audio === a) scrub = 'audio'; }; - a.onerror = () => { if (g === gettone && audio === a) { scrub = 'muto'; suona = false; } }; + scrub = 'audio'; + const pronto = () => { + if (g !== gettone || audio !== a) return; + scrub = 'audio'; + if (isFinite(a.duration) && a.duration > 0 && indice) { + indice.totale = a.duration; + mostraPosizione(Math.min(posizione, a.duration)); + } + if (vuoleSuonare) parti(posizione); + }; + a.onloadedmetadata = pronto; + a.oncanplay = pronto; + a.onerror = () => { if (g === gettone && audio === a) { scrub = 'muto'; suona = false; vuoleSuonare = false; tempoSuono.textContent = 'non si sente'; } }; a.ontimeupdate = () => { if (g === gettone && suona && audio === a) mostraPosizione(a.currentTime); }; a.onended = () => { if (g === gettone && audio === a) pausa(); }; a.src = fonte; + if (a.readyState >= 1) pronto(); // l'onda di tutto il brano: il cursore ci scorre sopra try { const r = await chiedi<{ url: string | null }>('scrubAnteprima', { id: f.id, lato: LATO_GRANDE }); @@ -265,7 +303,7 @@ export function creaColonna(apri: () => void, pronto: () => void = () => {}): Co etichetta.textContent = didascalia(n); if (indice.tipo === 'tempo') { // video e brani: la figurina porta il cursore in quel punto (se sta suonando, la riproduzione prosegue da lì) - if (scrub === 'video' || (scrub === 'audio' && ondaPiena)) { if (suona) { parti(indice.punti[n]); } else vaiA(indice.punti[n], false); return; } + if (scrub === 'video' || (scrub === 'audio' && ondaPiena)) { if (suona) { parti(indice.punti[n]); } else vaiA(indice.punti[n]); return; } mostraPosizione(indice.punti[n]); if (scrub === 'audio' || (scrub === 'muto' && ondaPiena)) return; } @@ -288,29 +326,98 @@ export function creaColonna(apri: () => void, pronto: () => void = () => {}): Co else if ((e.key === ' ' || e.key === 'Enter') && indice.tipo === 'tempo' && media()) { e.preventDefault(); alterna(); } }); - // ——— il cursore sulla figura e sulla barra: scorre; il clic riproduce ——— + // ——— il cursore: l'onda e la timeline spostano il punto, senza farlo sentire. Il video si cerca dalla barra. ——— const puoScorrere = () => !!indice && indice.tipo === 'tempo' && !!scrub && scrub !== 'muto'; - figura.addEventListener('pointermove', (e) => { if (puoScorrere() && !suona) vaiA(tempoDa(e, figura), true); }); - barra.addEventListener('pointermove', (e) => { if (puoScorrere() && !suona) vaiA(tempoDa(e, barra), true); }); - figura.addEventListener('pointerleave', () => { if (!suona) { clearTimeout(spegniSuono); audio?.pause(); } }); - barra.addEventListener('pointerleave', () => { if (!suona) { clearTimeout(spegniSuono); audio?.pause(); } }); + const eTempo = () => file?.categoria === 'audio' || file?.categoria === 'video'; + let tira = false; + function sposta(t: number) { + if (suona && media()) { + mostraPosizione(t); + try { media()!.currentTime = t; } catch { /* non ancora pronto */ } + } else vaiA(t); + } + function focusVideo() { if (file?.categoria === 'video') el.focus({ preventScroll: true }); } + function tastoVideo(e: KeyboardEvent) { + if (file?.categoria !== 'video') return; + const fps = file.dettagli?.fps && file.dettagli.fps > 1 ? file.dettagli.fps : 25; + const k = e.key.toLowerCase(); + const passo = (d: number, continua: boolean) => { + e.preventDefault(); + e.stopPropagation(); + const t = posizione + d; + if (continua && suona) parti(t); + else { if (!continua) pausa(); vaiA(t); } + }; + if (e.key === 'ArrowLeft') passo(-1 / fps, false); + else if (e.key === 'ArrowRight') passo(1 / fps, false); + else if (k === 'j') passo(-10, true); + else if (k === 'l') passo(10, true); + else if (k === 'k' || e.key === ' ') { e.preventDefault(); e.stopPropagation(); alterna(); } + } + async function salvaQuadro() { + if (!file || file.categoria !== 'video') return; + try { + if (video.videoWidth > 0) { + const cv = document.createElement('canvas'); + cv.width = video.videoWidth; + cv.height = video.videoHeight; + cv.getContext('2d')!.drawImage(video, 0, 0); + const r = await chiedi<{ nome: string }>('salvaPng', { png: cv.toDataURL('image/png') }); + tasti.textContent = `Salvato: ${r.nome}`; + return; + } + } catch { /* il fotogramma lo prende FFmpeg */ } + try { + const r = await chiedi<{ nome: string }>('salvaQuadro', { id: file.id, t: posizione }); + tasti.textContent = `Salvato: ${r.nome}`; + } catch (e) { tasti.textContent = (e as Error).message; } + } + figura.addEventListener('pointermove', (e) => { if (scrub === 'audio' || file?.categoria === 'video' || !puoScorrere() || suona) return; vaiA(tempoDa(e, figura)); }); + figura.addEventListener('pointerup', (e) => { + if (file?.categoria !== 'audio' || e.button !== 0) return; + sposta(tempoDa(e, figura)); + }); + barra.addEventListener('pointerdown', (e) => { + if (!eTempo() || e.button !== 0) return; + tira = true; + barra.setPointerCapture(e.pointerId); + focusVideo(); + sposta(tempoDa(e, barra)); + }); + barra.addEventListener('pointermove', (e) => { + if (eTempo()) { if (tira) sposta(tempoDa(e, barra)); return; } + if (puoScorrere() && !suona) vaiA(tempoDa(e, barra)); + }); + barra.addEventListener('pointerup', () => { tira = false; }); + figura.addEventListener('pointerleave', () => { if (!suona && scrub !== 'audio') audio?.pause(); }); + barra.addEventListener('pointerleave', () => { if (!suona && scrub !== 'audio') audio?.pause(); }); figura.addEventListener('click', (e) => { - // dove si può suonare il clic fa partire (o ferma) la riproduzione; altrimenti apre il lettore come prima + // l'onda del brano ha già messo il punto (pointerup): il play sta sotto. Il video: clic = play/pausa, la barra cerca. + if (file?.categoria === 'audio') return; + if (file?.categoria === 'video') { focusVideo(); alterna(); return; } if (indice?.tipo === 'tempo' && media()) { if (suona) pausa(); else parti(tempoDa(e, figura)); } else apri(); }); - figura.addEventListener('dblclick', () => { if (indice?.tipo === 'tempo' && media()) { pausa(); apri(); } }); - barra.addEventListener('click', (e) => { if (puoScorrere() && media()) parti(tempoDa(e, barra)); }); + figura.addEventListener('dblclick', () => { if (indice?.tipo === 'tempo' && (media() || file?.categoria === 'audio')) { pausa(); apri(); } }); + barra.addEventListener('click', (e) => { + if (eTempo()) return; + if (puoScorrere() && media()) parti(tempoDa(e, barra)); + }); barra.addEventListener('keydown', (e) => { + if (file?.categoria === 'video') { tastoVideo(e); return; } if (!puoScorrere()) return; const passo = e.shiftKey ? 30 : SALTO; - const vai = (t: number) => { e.preventDefault(); if (suona) parti(t); else vaiA(t, true); }; + const vai = (t: number) => { e.preventDefault(); if (suona) parti(t); else vaiA(t); }; if (e.key === 'ArrowRight') vai(posizione + passo); else if (e.key === 'ArrowLeft') vai(posizione - passo); else if (e.key === 'Home') vai(0); else if (e.key === 'End') vai(durataTot()); else if ((e.key === ' ' || e.key === 'Enter') && media()) { e.preventDefault(); alterna(); } }); + el.addEventListener('keydown', (e) => { + if (e.target === barra || e.target instanceof HTMLInputElement || e.target instanceof HTMLButtonElement) return; + tastoVideo(e); + }); function costruisci(i: Indice) { indice = i; @@ -352,6 +459,16 @@ export function creaColonna(apri: () => void, pronto: () => void = () => {}): Co attesa.length = 0; inCorso = false; file = f; + el.classList.toggle('audio', f.categoria === 'audio'); + el.classList.toggle('video', f.categoria === 'video'); + figura.title = f.categoria === 'audio' + ? 'Clic sull\'onda: sposta il punto, senza farlo sentire. Poi Play.' + : f.categoria === 'video' + ? 'Clic: play o pausa. La barra sotto cerca il punto. ← → un fotogramma, J K L.' + : 'Passa il cursore: scorre. Clic: riproduce. Doppio clic: apre nel lettore'; + bPlay.innerHTML = icone.play; + tempoSuono.textContent = '—'; + tasti.textContent = f.categoria === 'video' ? '← → fotogramma · J K L' : ''; indice = null; scelta = -1; tipoDescritto = ''; @@ -365,8 +482,35 @@ export function creaColonna(apri: () => void, pronto: () => void = () => {}): Co if (f.anteprima) { img.src = f.anteprima; img.hidden = false; segnaposto.hidden = true; } else { img.hidden = true; segnaposto.hidden = false; } const g = gettone; chiedi('indiceAnteprima', { id: f.id }) - .then((i) => { if (g !== gettone) return; costruisci(i); if (i.tipo === 'tempo') void preparaScrub(f, g); void scegli(0); pronto(); }) - .catch(() => { if (g !== gettone) return; costruisci({ tipo: 'singola', voci: 1, totale: 1, punti: [0] }); void scegli(0); pronto(); }); + .then((i) => { + if (g !== gettone) return; + // un brano non ha i pezzi nel tempo: si ascolta da qui, con play, posizione e volume + if (f.categoria === 'audio' || f.categoria === 'video') { + // anche se la durata letta è zero: il tag, quando è pronto, dice quanto dura davvero + indice = i.tipo === 'tempo' ? i : { tipo: 'tempo', voci: 1, totale: f.dettagli?.durata || 0, punti: [0] }; + tipoDescritto = f.categoria === 'audio' ? 'si ascolta da qui' : 'si guarda da qui'; + strisce.replaceChildren(); + void preparaScrub(f, g); + pronto(); + return; + } + costruisci(i); + if (i.tipo === 'tempo') void preparaScrub(f, g); + void scegli(0); + pronto(); + }) + .catch(() => { + if (g !== gettone) return; + if (f.categoria === 'audio' || f.categoria === 'video') { + indice = { tipo: 'tempo', voci: 1, totale: f.dettagli?.durata || 0, punti: [0] }; + void preparaScrub(f, g); + pronto(); + return; + } + costruisci({ tipo: 'singola', voci: 1, totale: 1, punti: [0] }); + void scegli(0); + pronto(); + }); }, }; } diff --git a/ui/src/app/home.ts b/ui/src/app/home.ts index f526ac4..c718e3b 100644 --- a/ui/src/app/home.ts +++ b/ui/src/app/home.ts @@ -73,29 +73,51 @@ function statoPc(): HTMLElement { s.aggiornamento ? { testo: 'Installa', fai: () => { void chiedi('aggiorna', { installa: true }); mostraAvviso('Scarico e riapro il programma…'); } } : undefined)); } +function miniatura(v: VoceRecente, cat: Categoria): HTMLElement { + const icona = h('span.recente-icona', { html: iconaCategoria[cat] }); + const img = h('img.recente-foto', { alt: '' }) as HTMLImageElement; + img.hidden = true; + const metti = (src: string) => { img.src = src; img.hidden = false; icona.hidden = true; }; + if (cat === 'immagine') { + void chiedi('url', { percorso: v.uscita }).then((u) => { if (typeof u === 'string' && u) metti(u); }).catch(() => {}); + } else { + void chiedi<{ png: string | null }>('miniatura', { percorso: v.uscita }).then((r) => { + if (r?.png) metti('data:image/png;base64,' + r.png); + }).catch(() => {}); + } + return h('span.recente-foto-box', null, icona, img); +} + function recenti(): HTMLElement { const box = h('div.recenti', null); - void chiedi('storico', { quanti: 6 }).then((r) => { - if (!box.isConnected) return; - if (!r?.recenti?.length) { - box.replaceChildren(h('p.recenti-vuoto', null, 'Qui compaiono gli ultimi file convertiti, con quanto hanno guadagnato.')); - return; - } - const risparmio = r.totali.byteRisparmiati > 0 ? ` · ${peso(r.totali.byteRisparmiati)} risparmiati` : ''; - box.replaceChildren( - h('div.titolo-sezione', null, h('span', null, 'ULTIMI CONVERTITI'), h('span.conta', null, `${r.totali.conversioni.toLocaleString('it-IT')} in tutto${risparmio}`)), - ...r.recenti.map((v) => { - const cat = (v.categoria in iconaCategoria ? v.categoria : 'altro') as Categoria; - const delta = v.pesoPrima && v.pesoDopo ? Math.round((1 - v.pesoDopo / v.pesoPrima) * 100) : null; - return h('div.recente', { style: { '--tinta': coloreCategoria[cat] } }, - h('span.recente-icona', { html: iconaCategoria[cat] }), - h('div.recente-testo', null, - h('b', { title: v.uscita }, v.nome, h('span.recente-freccia', null, ` → ${v.formato}`)), - h('small', null, `${quando(v.quando)} · ${v.pesoPrima ? `${peso(v.pesoPrima)} → ` : ''}${peso(v.pesoDopo)}${delta !== null && Math.abs(delta) >= 1 ? ` (${delta > 0 ? '−' : '+'}${Math.abs(delta)}%)` : ''}`)), - h('button.guarda', { title: 'Guarda nel lettore', html: icone.occhio, onclick: () => { clac(); void chiedi('guarda', { percorso: v.uscita }); } }), - h('button.guarda', { title: 'Mostra nella cartella', html: icone.cartella, onclick: () => { clac(); void chiedi('mostra', { percorso: v.uscita }); } })); - })); - }).catch(() => { /* senza storico la home resta com'è */ }); + const disegna = () => { + void chiedi('storico', { quanti: 6 }).then((r) => { + if (!box.isConnected) return; + if (!r?.recenti?.length) { + box.replaceChildren(h('p.recenti-vuoto', null, 'Qui compaiono gli ultimi file: conversioni, screenshot e registrazioni.')); + return; + } + const risparmio = r.totali.byteRisparmiati > 0 ? ` · ${peso(r.totali.byteRisparmiati)} risparmiati` : ''; + box.replaceChildren( + h('div.titolo-sezione', null, h('span', null, 'RECENTI'), h('span.conta', null, `${r.totali.conversioni.toLocaleString('it-IT')} conversioni${risparmio}`)), + ...r.recenti.map((v) => { + const cat = (v.categoria in iconaCategoria ? v.categoria : 'altro') as Categoria; + const prodotto = !v.pesoPrima; + const delta = v.pesoPrima && v.pesoDopo ? Math.round((1 - v.pesoDopo / v.pesoPrima) * 100) : null; + const apri = () => { clac(); void chiedi('guarda', { percorso: v.uscita }); }; + return h('div.recente', { title: v.uscita, onclick: (e: Event) => { if ((e.target as HTMLElement).closest('button')) return; apri(); } }, + miniatura(v, cat), + h('div.recente-testo', null, + h('b', null, v.nome, prodotto ? null : h('span.recente-freccia', null, ` → ${v.formato}`)), + h('small', null, prodotto + ? `${quando(v.quando)} · ${v.formato} · ${peso(v.pesoDopo)}` + : `${quando(v.quando)} · ${peso(v.pesoPrima)} → ${peso(v.pesoDopo)}${delta !== null && Math.abs(delta) >= 1 ? ` (${delta > 0 ? '−' : '+'}${Math.abs(delta)}%)` : ''}`)), + h('button.guarda', { title: 'Apri', html: icone.occhio, onclick: () => apri() }), + h('button.guarda', { title: 'Mostra nella cartella', html: icone.cartella, onclick: () => { clac(); void chiedi('mostra', { percorso: v.uscita }); } })); + })); + }).catch(() => { /* senza storico la home resta com'è */ }); + }; + disegna(); return box; } diff --git a/ui/src/app/impostazioni.ts b/ui/src/app/impostazioni.ts index fbff190..298578b 100644 --- a/ui/src/app/impostazioni.ts +++ b/ui/src/app/impostazioni.ts @@ -137,36 +137,94 @@ export function apriImpostazioni() { } }, 'Togli le voci dal sistema'), regola.attiva ? h('button.link', { title: 'Cancella la regola di Windows: i tipi tornano a come li scegli tu', onclick: () => { clac(); void chiedi<{ esito: string }>('predefiniteTogli').then((r) => esitoRegola(r.esito, false)); } }, 'Togli la regola delle app predefinite') : null); + const dove = h('p.imp-dove', null, 'Guardo la cartella…'); + const elenco = h('ul.imp-file'); + const bloccaCartella = h('div', null, + dove, + h('div.compatto-tasti', { style: 'margin-top:8px' }, + h('button.tasto', { onclick: () => { clac(); void chiedi('apriCartellaMia'); } }, 'Apri'), + h('button.tasto', { onclick: async () => { + clac(); + const r = await chiedi<{ percorso: string | null }>('scegliCartellaMia'); + if (r?.percorso) { imp.cartellaMia = r.percorso; apriImpostazioni(); } + } }, 'Cambia'), + imp.cartellaMia ? h('button.tasto', { onclick: () => { clac(); imp.cartellaMia = null; void chiedi('impostazioni', { cartellaMia: '' }); apriImpostazioni(); } }, 'Quella di partenza') : null), + elenco); + const scorciatoia = h('button.campo-scorciatoia', { type: 'button', title: 'Clicca qui, poi premi i tasti della scorciatoia' }, imp.scorciatoiaSchermo || 'Ctrl+Maiusc+S'); + scorciatoia.addEventListener('click', () => { + if (scorciatoia.classList.contains('ascolta')) return; + clac(); + scorciatoia.classList.add('ascolta'); + scorciatoia.textContent = 'Premi i tasti…'; + const f = (e: KeyboardEvent) => { + e.preventDefault(); + e.stopPropagation(); + if (['Control', 'Shift', 'Alt', 'Meta'].includes(e.key)) return; + const parti: string[] = []; + if (e.ctrlKey) parti.push('Ctrl'); + if (e.altKey) parti.push('Alt'); + if (e.shiftKey) parti.push('Maiusc'); + const tasto = e.key.length === 1 ? e.key.toUpperCase() : e.key; + const fine = () => { scorciatoia.classList.remove('ascolta'); window.removeEventListener('keydown', f, true); }; + if (!e.ctrlKey && !e.altKey && !e.metaKey && tasto !== 'Escape') return; + if (tasto === 'Escape') { scorciatoia.textContent = imp.scorciatoiaSchermo || 'Ctrl+Maiusc+S'; fine(); return; } + parti.push(tasto); + const testo = parti.join('+'); + imp.scorciatoiaSchermo = testo; + scorciatoia.textContent = testo; + salva({ scorciatoiaSchermo: testo }); + void chiedi('scorciatoia', { testo }); + fine(); + }; + window.addEventListener('keydown', f, true); + }); + cassetto.append(h('div.cassetto', null, h('div.confronto-testa', null, h('b', null, 'IMPOSTAZIONI'), h('span'), h('button.btn-fin', { html: icone.chiudi, onclick: () => cassetto.remove() })), - riga('La scritta nel nome', 'Foto.jpg diventa «Foto (convertito).webp». Puoi cambiarla.', scritta), - riga('L\'originale nel Cestino da solo', 'Spento: l\'originale resta, e lo butti tu col cestino accanto al risultato. Acceso: quando il convertito ne prende il posto (MOV → MP4, PNG → JPG…) l\'originale va nel Cestino da solo. Mai quando ne tiri fuori un pezzo (l\'audio, il testo, le pagine) né su chiavette e dischi di rete.', - leva(imp.cestinoDaSolo, (v) => { salva({ cestinoDaSolo: v }); ui.piede(); })), - h('div.imp-sezione', null, 'SISTEMA'), - sistema, - riga('Scegliere i tipi da aprire col lettore', 'La lista dei tipi di file (foto, video, musica, PDF…) con un interruttore ciascuno: «Aggiusta tutto» usa questa scelta.', - h('button.tasto', { onclick: () => { clac(); apriPredefinite(); } }, 'Scegli i tipi')), - ...(s.stato.menu11?.windows11 - ? [riga('Mostra tutti i menu del tasto destro', 'Su Windows 11 il tasto destro apre subito il menu completo, con tutte le voci a un clic e senza «Mostra altre opzioni». Spento torna il menu di Windows 11. Esplora file va riavviato: te lo chiedo.', - leva(s.stato.menu11.classico, async (v) => { - s.stato.menu11 = await chiedi('classico', { attivo: v }); - proponiRiavvio(v ? 'Il menu completo arriva quando riparte Esplora file.' : 'Il menu di Windows 11 torna quando riparte Esplora file.'); - }))] - : []), - h('div.imp-sezione', null, 'AVATAR'), - riga('Avatar sul desktop', 'Un oggetto piccolo (una musicassetta, poi un VHS, un floppy…) che sta in un angolo, ogni tanto fa un movimento e si trasforma. Non dà fastidio: sta fermo quando hai un programma a schermo intero. Ci trascini sopra dei file e ti chiede: aprire, convertire o comprimere. Si sposta col mouse, tasto destro per il menu.', - leva(!!imp.avatarAttivo, (v) => { salva({ avatarAttivo: v }); apriImpostazioni(); })), - ...(imp.avatarAttivo ? [riga('Parte con Windows', 'L\'avatar si accende da solo quando accedi, senza aprire finestre.', leva(!!imp.avatarAvvio, (v) => salva({ avatarAvvio: v })))] : []), - ...(imp.avatarAttivo ? [riga('Cambio automatico del personaggio', "Acceso, ogni tanto l'avatar si trasforma da solo. Spento, resta quello che hai scelto (tasto destro sull'avatar → Scegli il personaggio).", leva(imp.avatarCambioAuto !== false, (v) => salva({ avatarCambioAuto: v })))] : []), - h('div.imp-sezione', null, 'ALTRO'), - riga('Spingi al massimo', 'FFmpeg a priorità normale: un po\' più veloce, ma mentre converte il PC si sente.', leva(imp.alMassimo, (v) => salva({ alMassimo: v }))), - riga('Suoni', 'Il clac dei tasti e il din-don alla fine. Di partenza sono spenti.', leva(imp.suoniAccesi, (v) => { salva({ suoniAccesi: v }); accendiSuoni(v); })), - riga('Apri la cartella alla fine', 'Quando ha finito, apre Esplora file col file convertito già selezionato.', leva(imp.apriCartella, (v) => salva({ apriCartella: v }))), - h('div.imp-piede', null, - h('span', null, `DaP Convertitore ${s.stato.versione} · DaProd`), - h('button.link', { onclick: () => chiedi('registro') }, 'Apri il registro'), - h('button.link', { onclick: () => void apriNovita() }, 'Novità e aggiornamenti')), + h('div.imp-colonne', null, + h('div.imp-col', null, + riga('La scritta nel nome', 'Foto.jpg diventa «Foto (convertito).webp». Puoi cambiarla.', scritta), + riga('L\'originale nel Cestino da solo', 'Spento: l\'originale resta, e lo butti tu col cestino accanto al risultato. Acceso: quando il convertito ne prende il posto (MOV → MP4, PNG → JPG…) l\'originale va nel Cestino da solo. Mai quando ne tiri fuori un pezzo (l\'audio, il testo, le pagine) né su chiavette e dischi di rete.', + leva(imp.cestinoDaSolo, (v) => { salva({ cestinoDaSolo: v }); ui.piede(); })), + h('div.imp-sezione', null, 'SISTEMA'), + sistema, + riga('Scegliere i tipi da aprire col lettore', 'La lista dei tipi di file (foto, video, musica, PDF…) con un interruttore ciascuno: «Aggiusta tutto» usa questa scelta.', + h('button.tasto', { onclick: () => { clac(); apriPredefinite(); } }, 'Scegli i tipi')), + ...(s.stato.menu11?.windows11 + ? [riga('Mostra tutti i menu del tasto destro', 'Su Windows 11 il tasto destro apre subito il menu completo, con tutte le voci a un clic e senza «Mostra altre opzioni». Spento torna il menu di Windows 11. Esplora file va riavviato: te lo chiedo.', + leva(s.stato.menu11.classico, async (v) => { + s.stato.menu11 = await chiedi('classico', { attivo: v }); + proponiRiavvio(v ? 'Il menu completo arriva quando riparte Esplora file.' : 'Il menu di Windows 11 torna quando riparte Esplora file.'); + }))] + : []), + ), + h('div.imp-col', null, + h('div.imp-sezione', null, 'AVATAR'), + riga('Avatar sul desktop', 'Un oggetto piccolo (una musicassetta, poi un VHS, un floppy…) che sta in un angolo, ogni tanto fa un movimento e si trasforma. Non dà fastidio: sta fermo quando hai un programma a schermo intero. Ci trascini sopra dei file e ti chiede: aprire, convertire o comprimere. Si sposta col mouse, tasto destro per il menu.', + leva(!!imp.avatarAttivo, (v) => { salva({ avatarAttivo: v }); apriImpostazioni(); })), + ...(imp.avatarAttivo ? [riga('Parte con Windows', 'L\'avatar si accende da solo quando accedi, senza aprire finestre.', leva(!!imp.avatarAvvio, (v) => salva({ avatarAvvio: v })))] : []), + ...(imp.avatarAttivo ? [riga('Cambio automatico del personaggio', "Acceso, ogni tanto l'avatar si trasforma da solo. Spento, resta quello che hai scelto (tasto destro sull'avatar → Scegli il personaggio).", leva(imp.avatarCambioAuto !== false, (v) => salva({ avatarCambioAuto: v })))] : []), + h('div.imp-sezione', null, 'ALTRO'), + riga('Spingi al massimo', 'FFmpeg a priorità normale: un po\' più veloce, ma mentre converte il PC si sente.', leva(imp.alMassimo, (v) => salva({ alMassimo: v }))), + riga('Suoni', 'Il clac dei tasti e il din-don alla fine. Di partenza sono spenti.', leva(imp.suoniAccesi, (v) => { salva({ suoniAccesi: v }); accendiSuoni(v); })), + riga('Apri la cartella alla fine', 'Quando ha finito, apre Esplora file col file convertito già selezionato.', leva(imp.apriCartella, (v) => salva({ apriCartella: v }))), + h('div.imp-sezione', null, 'CARTELLA'), + riga('Dove finisce quello che faccio io', 'Screenshot, registrazioni e il resto che produce l\'app. Di partenza è Immagini/DaPConvertitore.', bloccaCartella), + h('div.imp-sezione', null, 'SCHERMO'), + riga('Screenshot', 'Clicca il riquadro chiaro e premi i tasti (si legge «Premi i tasti…»). Poi lo schermo si scurisce appena, scegli la zona e la foto va nella cartella. Tasto destro o Esc annulla. Vale anche quando DaP non è davanti.', + h('div.compatto-tasti', null, scorciatoia, h('button.tasto', { onclick: () => { clac(); cassetto.remove(); void chiedi('cattura'); } }, 'Prova'))), + h('div.imp-piede', null, + h('span', null, `DaP Convertitore ${s.stato.versione} · DaProd`), + h('button.link', { onclick: () => chiedi('registro') }, 'Apri il registro'), + h('button.link', { onclick: () => void apriNovita() }, 'Novità e aggiornamenti')), + ), + ), )); + void chiedi<{ percorso: string; file: { nome: string; peso: number; percorso: string }[] }>('cartellaMia').then((r) => { + if (!dove.isConnected) return; + dove.textContent = r.percorso; + elenco.replaceChildren(...(r.file ?? []).map((f) => h('li', null, h('button', { type: 'button', title: f.percorso, onclick: () => void chiedi('mostra', { percorso: f.percorso }) }, f.nome)))); + }).catch(() => { if (dove.isConnected) dove.textContent = 'La cartella non si legge da qui.'; }); if (!vecchio) document.body.append(cassetto); else (cassetto.querySelector('.cassetto') as HTMLElement).scrollTop = scorri; } diff --git a/ui/src/app/novita.ts b/ui/src/app/novita.ts index 941f47b..27f3e99 100644 --- a/ui/src/app/novita.ts +++ b/ui/src/app/novita.ts @@ -9,16 +9,19 @@ import { s } from './stato'; export interface DatiNovita { versione: string; testo: string | null; nuova: boolean } -/** Un markdown piccolo piccolo: elenchi (anche su più righe), **grassetto** e `codice`. */ +/** Un markdown piccolo piccolo: elenchi (anche su più righe), **grassetto**, `codice` e [testo](https://…). */ function markdown(md: string): HTMLElement { const box = h('div.novita-testo'); const inline = (t: string) => { const el = h('span'); - const re = /\*\*([^*]+)\*\*|`([^`]+)`/g; + const re = /\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)|\*\*([^*]+)\*\*|`([^`]+)`/g; let k = 0, m: RegExpExecArray | null; while ((m = re.exec(t))) { if (m.index > k) el.append(t.slice(k, m.index)); - el.append(m[1] ? h('b', null, m[1]) : h('code', null, m[2])); + if (m[1]) { + const url = m[2]; + el.append(h('button.link', { type: 'button', onclick: () => void chiedi('link', { url }) }, m[1])); + } else el.append(m[3] ? h('b', null, m[3]) : h('code', null, m[4])); k = re.lastIndex; } if (k < t.length) el.append(t.slice(k)); diff --git a/ui/src/app/pannelli/index.ts b/ui/src/app/pannelli/index.ts index 5c07936..2fc1383 100644 --- a/ui/src/app/pannelli/index.ts +++ b/ui/src/app/pannelli/index.ts @@ -1,14 +1,67 @@ // Le regolazioni di ogni formato: il pannello giusto per il formato scelto. -import type { Categoria, Formato } from '../../ponte'; -import { h } from '../../util'; -import { s, eVideoVero } from '../stato'; -import { gruppo, bottoni, interruttore } from '../controlli'; +import type { Categoria, Formato, InfoFile } from '../../ponte'; +import { h, peso } from '../../util'; +import { s, eVideoVero, fileDi } from '../stato'; +import { gruppo, bottoni, interruttore, faderPeso } from '../controlli'; +import { sezioneScheda } from './scheda'; import { regolazioniVideo } from './video'; import { regolazioniImmagine } from './immagine'; import { eFormatoArchivio, regolazioniArchivio, regolazioniEstrai } from './archivio'; export function regolazioni(c: Categoria, f?: Formato): Node { + const n = corpoRegolazioni(c, f); + if (f && n instanceof HTMLElement) { + const extra = sezioneScheda(c, f); + if (extra) n.append(extra); + } + return n; +} + +/** Il brano (o il video da cui si tira l'audio) di cui si stima il peso. */ +function sorgenteAudio(): InfoFile | undefined { + const attivo = s.fileAttivo ? s.file.get(s.fileAttivo) : undefined; + if (attivo && (attivo.categoria === 'audio' || attivo.categoria === 'video')) return attivo; + return fileDi('audio')[0] ?? fileDi('video')[0]; +} + +/** Lo slider del peso finale, sempre visibile: dai byte si ricava il kbit/s (o i bit, se non si perde niente). */ +function sliderPesoAudio(senzaPerdite: boolean, kbps: number[], partenza: number) { + const o = s.opzioni.audio; + const file = sorgenteAudio(); + const dur = file?.dettagli?.durata || 0; + const secondi = dur > 0 ? dur : 180; + const circa = dur <= 0 ? 'circa ' : ''; + if (senzaPerdite) { + const canali = Math.max(1, file?.dettagli?.canali || 2); + const byteDi = (bit: number) => secondi * 44100 * canali * (bit / 8); + const min = byteDi(16); + const max = Math.max(min + 1, byteDi(24)); + const bit = o.bit >= 24 ? 24 : 16; + const etichetta = h('div.peso-ora', null, `${circa}${peso(byteDi(bit))} · ${bit} bit`); + const fader = faderPeso(min, max, byteDi(bit), (b) => { + o.bit = b >= (min + max) / 2 ? 24 : 16; + etichetta.textContent = `${circa}${peso(byteDi(o.bit))} · ${o.bit} bit`; + }, peso(max, 0)); + return gruppo('PESO FINALE', fader, etichetta); + } + const scala = kbps.length ? kbps : [64, 320]; + const minK = scala[0]; + const maxK = scala[scala.length - 1]; + const byteDi = (k: number) => (secondi * k * 1000) / 8; + const attuale = o.kbps || partenza || minK; + const min = byteDi(minK); + const max = Math.max(min + 1, byteDi(maxK)); + const etichetta = h('div.peso-ora', null, `${circa}${peso(byteDi(attuale))} · ${attuale} kbit/s`); + const fader = faderPeso(min, max, Math.min(max, Math.max(min, byteDi(attuale))), (b) => { + const k = Math.round((b * 8) / secondi / 1000); + o.kbps = Math.max(minK, Math.min(maxK, k)); + etichetta.textContent = `${circa}${peso(byteDi(o.kbps))} · ${o.kbps} kbit/s`; + }, peso(max, 0)); + return gruppo('PESO FINALE', fader, etichetta); +} + +function corpoRegolazioni(c: Categoria, f?: Formato): Node { if (!f) return h('div'); const o = s.opzioni; if (eVideoVero(f)) return regolazioniVideo(f); @@ -23,6 +76,7 @@ export function regolazioni(c: Categoria, f?: Formato): Node { const kbps = { '.mp3': [128, 192, 256, 320], '.m4a': [128, 192, 256, 320], '.opus': [64, 96, 128, 160, 192], '.ogg': [128, 192, 256, 320], '.wma': [128, 192, 256] }[f.estensione] ?? []; const partenza = { '.mp3': 256, '.m4a': 256, '.opus': 160, '.ogg': 192, '.wma': 192 }[f.estensione] ?? 0; return h('div.regolazioni', null, + sliderPesoAudio(senzaPerdite, kbps, partenza), senzaPerdite ? gruppo('PROFONDITÀ', bottoni([{ v: 16, testo: '16 bit', nota: 'CD' }, { v: 24, testo: '24 bit', nota: 'studio' }], o.audio.bit, (v) => (o.audio.bit = v))) : gruppo('QUALITÀ', bottoni(kbps.map((v) => ({ v, testo: `${v}`, nota: 'kbit/s' })), o.audio.kbps || partenza, (v) => (o.audio.kbps = v))), diff --git a/ui/src/app/pannelli/scheda.ts b/ui/src/app/pannelli/scheda.ts new file mode 100644 index 0000000..fefd9f6 --- /dev/null +++ b/ui/src/app/pannelli/scheda.ts @@ -0,0 +1,161 @@ +// La sezione richiudibile «Info del file»: quello che si corregge finisce nel file convertito. +// L'originale non si tocca. I campi sono solo quelli che il formato di arrivo sa tenere. + +import { chiedi } from '../../ponte'; +import type { Categoria, Formato, OpzioniScheda } from '../../ponte'; +import { h } from '../../util'; +import { icone } from '../../icone'; +import { clac } from '../../suoni'; +import { s } from '../stato'; + +interface Letta { + titolo: string; artista: string; album: string; anno: string; traccia: string; + commento: string; autore: string; descrizione: string; dataScatto: string; + copertina: string | null; campi: string[]; +} + +const ETICHETTE: Record = { + titolo: 'Titolo', artista: 'Artista', album: 'Album', anno: 'Anno', traccia: 'Traccia', + commento: 'Commento', autore: 'Autore', descrizione: 'Descrizione', data: 'Data dello scatto', +}; + +/** Resta aperta anche quando la piastra si ridisegna (un clic su un formato). */ +let aperta = false; + +function va(c: Categoria, f: Formato) { + if (c === 'audio') return true; + if (c === 'video' && ['.mp4', '.mkv', '.mov', '.webm', '.mp3', '.wav', '.flac', '.m4a', '.ogg', '.opus', '.wma'].includes(f.estensione)) return true; + if (c === 'immagine' && ['.jpg', '.jpeg', '.tif', '.tiff', '.png', '.webp', '.heic', '.bmp'].includes(f.estensione)) return true; + return false; +} + +export function sezioneScheda(c: Categoria, f: Formato): HTMLElement | null { + if (!va(c, f)) return null; + const corpo = h('div.corpo-scheda'); + const el = h(`div.scheda-file${aperta ? '.aperta' : ''}`); + el.append( + h('button.testa-scheda', { type: 'button', title: 'Apri o chiudi le info del file', onclick: () => { + clac(); + aperta = !el.classList.contains('aperta'); + el.classList.toggle('aperta', aperta); + if (aperta) void riempi(); + } }, 'INFO DEL FILE', h('span.freccia', { html: icone.giu })), + corpo, + ); + if (aperta) void riempi(); + return el; + + async function riempi() { + const fa = s.fileAttivo ? s.file.get(s.fileAttivo) : undefined; + if (!fa) { corpo.replaceChildren(h('p.scheda-nota', null, 'Scegli un file nella coda.')); return; } + const id = fa.id; + corpo.replaceChildren(h('p.scheda-nota', null, 'Leggo…')); + let letti: Letta | null = null; + try { letti = await chiedi('schedaFile', { id, formato: f.id }); } + catch (e) { corpo.replaceChildren(h('p.scheda-nota', null, (e as Error).message)); return; } + if (s.fileAttivo !== id) return; + const campi = letti.campi ?? []; + const gia = s.schede.get(id); + const nota = h('p.scheda-nota', null, campi.length + ? 'Queste info finiscono nel file convertito. L\'originale resta com\'è.' + : 'Questo formato non conserva titolo, artista, data o copertina. Non si inventano campi che poi si perdono.'); + if (!campi.length) { corpo.replaceChildren(nota); return; } + + const valori: Record = { + titolo: gia?.scrivi ? gia.titolo ?? '' : letti.titolo, + artista: gia?.scrivi ? gia.artista ?? '' : letti.artista, + album: gia?.scrivi ? gia.album ?? '' : letti.album, + anno: gia?.scrivi ? gia.anno ?? '' : letti.anno, + traccia: gia?.scrivi ? gia.traccia ?? '' : letti.traccia, + commento: gia?.scrivi ? gia.commento ?? '' : letti.commento, + autore: gia?.scrivi ? gia.autore ?? '' : letti.autore, + descrizione: gia?.scrivi ? gia.descrizione ?? '' : letti.descrizione, + data: gia?.scrivi ? gia.dataScatto ?? '' : letti.dataScatto, + }; + const campiTesto = campi.filter((x) => x !== 'copertina'); + const griglia = h('div.scheda-campi'); + const input: Record = {}; + for (const nome of campiTesto) { + const campo = h('input.campo', { value: valori[nome] ?? '', spellcheck: false, 'aria-label': ETICHETTE[nome] ?? nome }); + campo.addEventListener('input', () => tocca()); + input[nome] = campo; + griglia.append(h('label', null, ETICHETTE[nome] ?? nome, campo)); + } + + let copertina = gia?.scrivi ? gia.copertina ?? null : null; + const anteprima = h('img', { alt: '' }); + const dida = h('span.scheda-dida'); + function mostraAnteprima() { + const url = copertina && copertina !== 'nessuna' && !copertina.startsWith('generata:') && !copertina.includes('\\') && !copertina.includes('/') + ? null + : copertina && (copertina.startsWith('data:') ? copertina : null); + if (copertina === 'nessuna') { anteprima.hidden = true; dida.textContent = 'Senza copertina'; } + else if (copertina?.startsWith('generata:')) { anteprima.hidden = true; dida.textContent = 'Una disegnata, scelta qui sotto'; } + else if (url) { anteprima.src = url; anteprima.hidden = false; dida.textContent = ''; } + else if (copertina && (copertina.includes('\\') || copertina.includes('/'))) { anteprima.hidden = true; dida.textContent = copertina.split(/[/\\]/).pop() ?? 'Immagine scelta'; } + else if (letti?.copertina) { anteprima.src = letti.copertina; anteprima.hidden = false; dida.textContent = 'Quella del file'; } + else { anteprima.hidden = true; dida.textContent = 'Nessuna copertina'; } + } + mostraAnteprima(); + + const rigaCover = campi.includes('copertina') ? h('div.scheda-cover', null, + anteprima, + h('div', null, + dida, + h('div.scheda-cover-tasti', null, + h('button.tasto.piccolo', { type: 'button', onclick: () => { clac(); copertina = null; mostraAnteprima(); tocca(); segnaVariante(); } }, 'Tieni'), + h('button.tasto.piccolo', { type: 'button', onclick: () => void scegliFile() }, 'Scegli…'), + h('button.tasto.piccolo', { type: 'button', onclick: () => { clac(); copertina = 'nessuna'; mostraAnteprima(); tocca(); segnaVariante(); } }, 'Togli'), + ))) : null; + + const varianti = campi.includes('copertina') ? h('div.scheda-varianti') : null; + corpo.replaceChildren(...[nota, campiTesto.length ? griglia : null, rigaCover, varianti].filter((x): x is HTMLElement => !!x)); + + function stato(): OpzioniScheda { + return { + scrivi: true, + titolo: input.titolo?.value ?? '', + artista: input.artista?.value ?? '', + album: input.album?.value ?? '', + anno: input.anno?.value ?? '', + traccia: input.traccia?.value ?? '', + commento: input.commento?.value ?? '', + autore: input.autore?.value ?? '', + descrizione: input.descrizione?.value ?? '', + dataScatto: input.data?.value ?? '', + copertina, + }; + } + function tocca() { s.schede.set(id, stato()); } + function segnaVariante() { + varianti?.querySelectorAll('button').forEach((b) => b.classList.toggle('su', copertina === `generata:${(b as HTMLElement).dataset.n}`)); + } + + async function scegliFile() { + clac(); + try { + const percorso = await chiedi('scegliImmagine'); + if (!percorso) return; + copertina = percorso; + mostraAnteprima(); + tocca(); + segnaVariante(); + } catch (e) { dida.textContent = (e as Error).message; } + } + + if (varianti) { + try { + const urls = await chiedi('copertine', { titolo: input.titolo?.value || fa.nome.replace(/\.[^.]+$/, '') }); + if (s.fileAttivo !== id) return; + urls.forEach((url, n) => { + varianti.append(h('button', { + type: 'button', title: 'Usa questa copertina disegnata', dataset: { n: String(n) }, + style: { backgroundImage: `url(${url})` }, + onclick: () => { clac(); copertina = `generata:${n}`; mostraAnteprima(); tocca(); segnaVariante(); }, + })); + }); + segnaVariante(); + } catch { /* le disegnate non sono arrivate: restano tieni, scegli e togli */ } + } + } +} diff --git a/ui/src/app/pannelli/video.ts b/ui/src/app/pannelli/video.ts index 348b431..955d322 100644 --- a/ui/src/app/pannelli/video.ts +++ b/ui/src/app/pannelli/video.ts @@ -7,7 +7,7 @@ import { h, peso, pesoDisplay, numero, clamp, MB, GB } from '../../util'; import { icone } from '../../icone'; import { Lancetta } from '../../grafica'; import { clac } from '../../suoni'; -import { s, ui, fileDi, sceltaPer, eVideoVero } from '../stato'; +import { s, ui, fileDi, sceltaPer, eVideoVero, scelteDaRicordare } from '../stato'; import { gruppo, bottoni, cursore, faderPeso, mostraPeso } from '../controlli'; let lancettaQualita: Lancetta | null = null; @@ -113,7 +113,13 @@ export function regolazioniVideo(f: Formato) { ...(haAmd ? [{ v: 'amd', testo: 'AMD' }] : []), ...(haIntel ? [{ v: 'intel', testo: 'Intel' }] : []), { v: 'cpu', testo: 'CPU', nota: 'più lenta' }, - ], o.motore, (v) => { o.motore = v; s.piano = null; })), + ], o.motore, (v) => { + o.motore = v; + s.stato.impostazioni.codificaCon = v === 'cpu' ? 'cpu' : 'gpu'; + void chiedi('impostazioni', { codificaCon: s.stato.impostazioni.codificaCon, scelte: scelteDaRicordare() }); + s.piano = null; + ui.testa(); + })), h('div.sotto-gruppo', null, h('label', null, 'AUDIO'), bottoni([{ v: 'si', testo: 'Tienilo' }, { v: 'no', testo: 'Toglilo' }], o.senzaAudio ? 'no' : 'si', (v) => { o.senzaAudio = v === 'no'; s.piano = null; })), )) : null; diff --git a/ui/src/app/stato.ts b/ui/src/app/stato.ts index edea16a..757f885 100644 --- a/ui/src/app/stato.ts +++ b/ui/src/app/stato.ts @@ -1,5 +1,5 @@ // Lo stato della piastra e le domande che si fanno sempre sullo stato. Una cosa sola, condivisa da tutti i pezzi. -import type { Carico, Categoria, Formato, InfoFile, Lavoro, Opzioni, Piano, StimaImmagine, Stato } from '../ponte'; +import type { Carico, Categoria, Formato, InfoFile, Lavoro, Opzioni, OpzioniScheda, Piano, StimaImmagine, Stato } from '../ponte'; export const opzioniDiPartenza = (): Opzioni => ({ video: { modo: 'peso', pesoByte: 0, qualita: 70, codec: 'h264', lato: 0, motore: 'auto', senzaAudio: false, audioKbps: 0, fps: 0, gifLarghezza: 480, gifFps: 15 }, @@ -24,12 +24,16 @@ export const s = { piano: null as Piano | null, /** La stima del peso della foto scelta (quanto pesa, a che qualità ci si arriva), con la chiave che dice per quale foto e formato. */ stimaFoto: null as (StimaImmagine & { chiave: string }) | null, + /** Le info corrette per ogni file della coda: si scrivono nel convertito di quel file. */ + schede: new Map(), carico: { cpu: 0, encoder: 0, decoder: 0, grafica: 0 } as Carico, giro: [] as string[], impostazioniAperte: false, aggiornamento: null as string | null, /** La scelta fatta dall'avatar (formato e preset), da applicare appena i file sono arrivati. */ sceltaRichiesta: null as { formato: string; preset?: string | null } | null, + /** Il file del lettore da cui si è aperta la modifica. */ + torna: null as string | null, }; export const nomeCat = (c: string) => s.stato.categorie.find((x) => x.id === c)?.nome ?? c; @@ -47,6 +51,16 @@ export const sceltaPer = (c: Categoria): Formato | undefined => { }; export const eVideoVero = (f?: Formato) => !!f && f.categoria === 'video' && ['.mp4', '.mkv', '.webm', '.mov'].includes(f.estensione); +/** Quello che la bolla e il pannello video devono scrivere, se no la scheda scelta si perde chiudendo l'app. */ +export function scelteDaRicordare() { + return { + video: { ...s.opzioni.video, pesoByte: 0 }, + audio: s.opzioni.audio, + immagine: s.opzioni.immagine, + pdf: s.opzioni.pdf, + }; +} + /** * I pezzi che disegnano si chiamano fra loro (il pannello delle regolazioni ridisegna la piastra, le impostazioni * ridisegnano il piede…). Per non far girare gli import in tondo parlano tramite questo: main.ts li collega all'avvio. @@ -60,4 +74,5 @@ export const ui = { rapido: () => {}, impostazioni: () => {}, nuovoGiro: () => {}, + testa: () => {}, }; diff --git a/ui/src/finto.ts b/ui/src/finto.ts index 0a2e9ea..69a918e 100644 --- a/ui/src/finto.ts +++ b/ui/src/finto.ts @@ -34,18 +34,22 @@ const quadro = (a: string, b: string, testo: string) => { return c.toDataURL('image/jpeg', 0.8); }; +let codificaCon: 'gpu' | 'cpu' | null = null; + const esempi: InfoFile[] = [ { id: 'F1', percorso: 'C:\\Users\\cammo\\Videos\\Matrimonio Napoli 4K.mov', nome: 'Matrimonio Napoli 4K.mov', cartella: 'C:\\Users\\cammo\\Videos', estensione: '.mov', categoria: 'video', nomeCategoria: 'Video', peso: 7_840_000_000, eDirectory: false, formati: formati.filter((x) => x.categoria === 'video').map((x) => x.id) }, { id: 'F2', percorso: 'C:\\Users\\cammo\\Pictures\\Tramonto Posillipo.heic', nome: 'Tramonto Posillipo.heic', cartella: 'C:\\Users\\cammo\\Pictures', estensione: '.heic', categoria: 'immagine', nomeCategoria: 'Immagini', peso: 3_120_000, eDirectory: false, formati: formati.filter((x) => x.categoria === 'immagine').map((x) => x.id) }, { id: 'F3', percorso: 'C:\\Users\\cammo\\Documents\\Preventivo DaProd.pdf', nome: 'Preventivo DaProd.pdf', cartella: 'C:\\Users\\cammo\\Documents', estensione: '.pdf', categoria: 'pdf', nomeCategoria: 'PDF', peso: 482_000, eDirectory: false, formati: formati.filter((x) => x.categoria === 'pdf').map((x) => x.id) }, { id: 'F4', percorso: 'C:\\Users\\cammo\\Desktop\\server DaProd.log', nome: 'server DaProd.log', cartella: 'C:\\Users\\cammo\\Desktop', estensione: '.log', categoria: 'testo', nomeCategoria: 'Testi', peso: 2_480_000, eDirectory: false, formati: formati.filter((x) => x.categoria === 'testo').map((x) => x.id) }, + { id: 'F5', percorso: 'C:\\Users\\cammo\\Music\\Poco dopo lo zero.mp3', nome: 'Poco dopo lo zero.mp3', cartella: 'C:\\Users\\cammo\\Music', estensione: '.mp3', categoria: 'audio', nomeCategoria: 'Audio', peso: 7_430_000, eDirectory: false, formati: formati.filter((x) => x.categoria === 'audio').map((x) => x.id) }, ]; const dettagli: Record = { F1: { durata: 1834, larghezza: 3840, altezza: 2160, fps: 25, codec: 'hevc', hdr: true, bitrate: 33_800_000, audio: 'aac', canali: 2, tracceAudio: 1, sottotitoli: 0 }, F2: { larghezza: 4032, altezza: 3024 }, F3: { pagine: 4 }, + F5: { durata: 326, audio: 'mp3', canali: 2, bitrate: 192000 }, }; -const anteprime: Record = { F1: ['#3b1d6e', '#ff3df2', 'NAPOLI'], F2: ['#ff9f43', '#3b1d6e', 'TRAMONTO'], F3: ['#f4f1fa', '#c9c2da', 'PDF'] }; +const anteprime: Record = { F1: ['#3b1d6e', '#ff3df2', 'NAPOLI'], F2: ['#ff9f43', '#3b1d6e', 'TRAMONTO'], F3: ['#f4f1fa', '#c9c2da', 'PDF'], F5: ['#1a1030', '#ffd54a', 'MUSICA'] }; let lavori: Lavoro[] = []; let nl = 0; @@ -112,12 +116,13 @@ export async function rispondi(cmd: string, args: any, emetti: (e: string, d: an regolaPredefiniti: { supportata: true, attiva: false, diAltri: false, impostati: 0, totale: 40 }, apriConGruppi: [{ id: 'Video', nome: 'Video', esempi: '.mp4 .mkv .mov' }, { id: 'Audio', nome: 'Audio', esempi: '.mp3 .flac .wav' }, { id: 'Immagine', nome: 'Immagine', esempi: '.jpg .png .heic' }, { id: 'Pdf', nome: 'Documento PDF', esempi: '.pdf' }], categorie: [{ id: 'video', nome: 'Video' }, { id: 'audio', nome: 'Audio' }, { id: 'immagine', nome: 'Immagini' }, { id: 'pdf', nome: 'PDF' }, { id: 'documento', nome: 'Documenti' }, { id: 'testo', nome: 'Testi' }, { id: 'archivio', nome: 'Archivi' }], - impostazioni: { scritta: 'convertito', menu: true, alMassimo: false, suoniAccesi: false, apriCartella: false, cestinoDaSolo: false, apriCon: true, menu11Chiesto: false, formati: {} }, + impostazioni: { scritta: 'convertito', menu: true, alMassimo: false, suoniAccesi: false, apriCartella: false, cestinoDaSolo: false, apriCon: true, menu11Chiesto: false, formati: {}, codificaCon, scorciatoiaSchermo: 'Ctrl+Maiusc+S' }, modo, file: modo === 'rapido' ? [esempi[0]] : esempi, lavori: [], office: { libreOffice: true, word: false, setteZip: true }, menu11: { supportato: true, registrato: false, fidato: false, chiesto: false, windows11: true, classico: false }, + torna: new URLSearchParams(location.search).get('torna') ? 'C:\\Users\\cammo\\Videos\\Matrimonio Napoli 4K.mov' : null, } satisfies Stato; } case 'piano': { @@ -171,12 +176,73 @@ export async function rispondi(cmd: string, args: any, emetti: (e: string, d: an if (c === 'video' || c === 'audio') return { tipo: 'tempo', voci: 12, totale: 240, punti: Array.from({ length: 12 }, (_, n) => 10 + n * 20) }; return { tipo: 'singola', voci: 1, totale: 1, punti: [0] }; } - case 'fonteAnteprima': - return { url: null }; // nel browser non c'è un file vero da suonare: lo scrub usa i fotogrammi finti - case 'scrubAnteprima': + case 'novita': + return { + versione: '2.2.8', nuova: false, + testo: '- **Le icone dei file sono rifatte.** A 16 pixel si leggono.\n- In arrivo, senza fretta: i tagli piccoli. Il montaggio vero resta [DaProd Editor Video](https://github.com/cammo22/DaProdEditorVideo). I dettagli sono in `docs/ROADMAP.md`.', + }; + case 'impostazioni': + if (args.codificaCon === 'gpu' || args.codificaCon === 'cpu') codificaCon = args.codificaCon; + return true; + case 'cartellaMia': + return { percorso: 'C:\\Users\\cammo\\Pictures\\DaPConvertitore', file: [{ nome: 'schermo.png', peso: 120000, percorso: 'C:\\Users\\cammo\\Pictures\\DaPConvertitore\\schermo.png' }] }; + case 'scegliCartellaMia': + return { percorso: 'D:\\DaP' }; + case 'schedaFile': { + const file = esempi.find((e) => e.id === args.id); + const est = formati.find((x) => x.id === args.formato)?.estensione ?? ''; + const campi = est === '.mp3' || est === '.m4a' || est === '.flac' ? ['titolo', 'artista', 'album', 'anno', 'traccia', 'copertina'] + : est === '.ogg' || est === '.opus' || est === '.wma' ? ['titolo', 'artista', 'album', 'anno', 'traccia'] + : est === '.mp4' || est === '.mov' || est === '.mkv' ? ['titolo', 'commento'] + : est === '.jpg' || est === '.tif' || est === '.tiff' ? ['data', 'descrizione', 'autore'] : []; + const audio = file?.categoria === 'audio'; + return { + titolo: audio ? 'Poco dopo lo zero' : file?.categoria === 'video' ? 'Matrimonio Napoli' : '', + artista: audio ? 'doprod22' : '', album: audio ? 'Notte' : '', anno: audio ? '2026' : '', traccia: audio ? '1' : '', + commento: file?.categoria === 'video' ? 'Le nozze' : '', autore: '', descrizione: file?.categoria === 'immagine' ? 'Tramonto a Posillipo' : '', + dataScatto: file?.categoria === 'immagine' ? '2024-06-01' : '', copertina: null, campi, + }; + } + case 'copertine': + return ['#3b1d6e', '#ff3df2', '#ffd54a', '#120c1c', '#5a2bbf', '#5dffb4'].map((colore, n) => quadro(colore, '#120c1c', String(n + 1))); + case 'scegliImmagine': + return null; + case 'fonteAnteprima': { + const c = esempi.find((x) => x.id === args.id)?.categoria; + if (c === 'audio') return { url: tonoWav() }; + return { url: null }; // nel browser non c'è un file vero da suonare: lo scrub del video usa i fotogrammi finti + } + case 'scrubAnteprima': { + const c = esempi.find((x) => x.id === args.id)?.categoria; + if (c === 'audio' && args.t == null) return { url: ondaFinta() }; return { url: quadro('#3b1d6e', '#ff3df2', `${Math.round(Number(args.t ?? 0))} s`) }; + } case 'voceAnteprima': return { url: quadro('#3b1d6e', '#ff3df2', String(Number(args.n) + 1)) }; + case 'salvaPng': + case 'salvaQuadro': + return { nome: 'fotogramma.png', percorso: 'C:\\Users\\cammo\\Pictures\\DaPConvertitore\\fotogramma.png' }; + case 'storico': + return { + recenti: [ + { quando: new Date().toISOString(), nome: 'schermo 2026-11-09.png', formato: 'Screenshot', uscita: 'C:\\Users\\cammo\\Pictures\\DaPConvertitore\\schermo.png', pesoPrima: 0, pesoDopo: 180000, categoria: 'immagine' }, + { quando: new Date(Date.now() - 3600_000).toISOString(), nome: 'registrazione 2026-11-09.mp4', formato: 'Registrazione', uscita: 'C:\\Users\\cammo\\Pictures\\DaPConvertitore\\registrazione.mp4', pesoPrima: 0, pesoDopo: 40_000_000, categoria: 'video' }, + ], + totali: { conversioni: 12, byteRisparmiati: 50_000_000 }, + }; + case 'url': + return quadro('#1d1236', '#ffd54a', ' '); + case 'miniatura': { + const c = document.createElement('canvas'); + c.width = 44; c.height = 44; + const g = c.getContext('2d')!; + g.fillStyle = '#3b1d6e'; g.fillRect(0, 0, 44, 44); + g.fillStyle = '#ffd54a'; g.fillRect(8, 8, 28, 28); + const data = c.toDataURL('image/png'); + return { png: data.slice(data.indexOf(',') + 1) }; + } + case 'tornaLettore': + return true; default: return true; } @@ -208,6 +274,41 @@ function simula(l: Lavoro, emetti: (e: string, d: any) => void) { }, 120); } +/** Un brano corto, giusto per premere play nell'anteprima del browser. */ +function tonoWav() { + const sr = 8000, sec = 4, n = sr * sec; + const buf = new ArrayBuffer(44 + n * 2); + const v = new DataView(buf); + const scrivi = (o: number, t: string) => { for (let i = 0; i < t.length; i++) v.setUint8(o + i, t.charCodeAt(i)); }; + scrivi(0, 'RIFF'); v.setUint32(4, 36 + n * 2, true); scrivi(8, 'WAVE'); scrivi(12, 'fmt '); + v.setUint32(16, 16, true); v.setUint16(20, 1, true); v.setUint16(22, 1, true); + v.setUint32(24, sr, true); v.setUint32(28, sr * 2, true); v.setUint16(32, 2, true); v.setUint16(34, 16, true); + scrivi(36, 'data'); v.setUint32(40, n * 2, true); + for (let i = 0; i < n; i++) { + const t = i / sr; + const env = Math.min(1, t * 6) * Math.min(1, (sec - t) * 3); + v.setInt16(44 + i * 2, Math.round(Math.sin(2 * Math.PI * 440 * t) * 0.28 * env * 32767), true); + } + let bin = ''; + for (const b of new Uint8Array(buf)) bin += String.fromCharCode(b); + return 'data:audio/wav;base64,' + btoa(bin); +} + +/** L'onda intera del brano, al posto della colonna dei pezzi. */ +function ondaFinta() { + const c = document.createElement('canvas'); + c.width = 720; c.height = 220; + const g = c.getContext('2d')!; + g.clearRect(0, 0, 720, 220); + for (let i = 0; i < 160; i++) { + const alto = 20 + Math.abs(Math.sin(i / 7) * 70) + (i % 9) * 4; + const x = 16 + i * 4.3; + g.fillStyle = i < 40 ? '#5dffb4' : i < 100 ? '#ffd54a' : '#ff3df2'; + g.fillRect(x, 110 - alto / 2, 3, alto); + } + return c.toDataURL('image/png'); +} + /** Un registro lungo (40.000 righe, qualcuna lunghissima) per provare lo scorrimento e la ricerca dell'anteprima. */ function registroFinto() { // ?enorme: due milioni di righe, oltre l'altezza massima di un elemento (lo scorrimento va in scala) diff --git a/ui/src/icone.ts b/ui/src/icone.ts index 429a170..4c44682 100644 --- a/ui/src/icone.ts +++ b/ui/src/icone.ts @@ -12,6 +12,7 @@ export const icone = { confronta: i(''), ingranaggio: i(''), play: i(''), + pausa: i(''), ferma: i(''), ok: i(''), novita: i(''), diff --git a/ui/src/lettore/audio.ts b/ui/src/lettore/audio.ts index b6162dd..337c2a1 100644 --- a/ui/src/lettore/audio.ts +++ b/ui/src/lettore/audio.ts @@ -27,10 +27,15 @@ export async function monta(c: Contesto): Promise { // il muto sta dopo l'analizzatore: lo spettro balla anche a volume zero let zitto = memoria.leggi('muto') ?? false; - // ——— la copertina: se non c'è, una mattonella col formato ——— + // ——— la copertina: se non c'è, una mattonella col formato. Col mouse sopra: Modifica e Download ——— const copertina = info.copertina ? h('div.a-cover', { style: { backgroundImage: `url(${info.copertina})` } }) : h('div.a-cover.vuota', null, h('b', null, estensione || 'AUDIO'), h('small', null, a0 ? a0.codec.toUpperCase().replace('PCM_', 'PCM ') : '')); + const boxCover = h('div.a-cover-box', null, + copertina, + h('div.a-cover-tasti', null, + h('button', { type: 'button', title: 'Cambia la copertina', onclick: (e: Event) => { e.stopPropagation(); void modifica(); } }, 'Modifica'), + h('button', { type: 'button', title: 'Salva la copertina nella cartella del brano', onclick: (e: Event) => { e.stopPropagation(); void scarica(); } }, 'Download'))); // ——— la parte di destra ——— const onda = h('canvas.a-onda'); @@ -40,7 +45,7 @@ export async function monta(c: Contesto): Promise { let ripeti = memoria.leggi('ripeti') ?? false; /** Di partenza suona solo il brano scelto; «Di seguito» fa suonare anche gli altri della cartella. */ let seguito = memoria.leggi('seguito') ?? false; - const bSeguito = h(`button.a-seguito.solo-fratelli${seguito ? '.su' : ''}`, { title: 'Suona anche gli altri brani della cartella, uno dopo l\'altro (T)', onclick: () => cambiaSeguito() }, h('i.led'), 'Di seguito'); + const bSeguito = h(`button.a-seguito.solo-fratelli${seguito ? '.su' : ''}`, { title: 'Suona anche gli altri brani della cartella, uno dopo l\'altro (T)', onclick: () => cambiaSeguito() }, h('i.led'), 'Riproduci coda'); const bRipeti = h(`button.a-b${ripeti ? '.su' : ''}`, { title: 'Ripeti il brano (R)', html: ic.ripeti, onclick: () => cambiaRipeti() }); const vol = h('input.v-vol', { type: 'range', min: 0, max: 1, step: 0.01, value: audio.volume }); vol.style.setProperty('--p', `${audio.volume * 100}%`); @@ -58,7 +63,7 @@ export async function monta(c: Contesto): Promise { info.copertina ? h('div.a-fondo', { style: { backgroundImage: `url(${info.copertina})` } }) : h('div.a-fondo.vuoto'), h('div.a-scheda', null, h('div.a-sinistra', null, - copertina, + boxCover, h('div.a-tecnica', null, ...tecnica.map((x) => h('span', null, x)))), h('div.a-destra', null, h('div.a-titoli', null, @@ -229,7 +234,7 @@ export async function monta(c: Contesto): Promise { memoria.scrivi('seguito', seguito); bSeguito.classList.toggle('su', seguito); sc.el.querySelector('.a-seguito-s')?.classList.toggle('su', seguito); - c.hud(seguito ? 'Di seguito: suona anche gli altri brani' : 'Solo questo brano', ic.elenco); + c.hud(seguito ? 'Riproduci coda: suona anche gli altri brani' : 'Solo questo brano', ic.elenco); } function cambiaRipeti() { ripeti = !ripeti; @@ -256,10 +261,10 @@ export async function monta(c: Contesto): Promise { void audio.play().catch(() => { /* aspetta un clic */ }); // ——— la scaletta: i brani della cartella (il componente è in scaletta.ts) ——— - /** La riga «Di seguito» sotto il titolo della scaletta. */ + /** La riga «Riproduci coda» sotto il titolo della scaletta. */ function riga() { return h(`button.a-seguito-s${seguito ? '.su' : ''}`, { title: 'Suona anche gli altri brani, uno dopo l\'altro (T)', onclick: () => cambiaSeguito() }, - h('i.led'), 'Di seguito', h('small', null, seguito ? 'suona anche gli altri' : 'suona solo quello scelto')); + h('i.led'), 'Riproduci coda', h('small', null, seguito ? 'suona anche gli altri' : 'suona solo quello scelto')); } const tasti: Tasto[] = [ @@ -273,10 +278,74 @@ export async function monta(c: Contesto): Promise { { k: ['p'], etichetta: 'P', cosa: 'Brano prima (o da capo)', fai: prima }, { k: ['r'], etichetta: 'R', cosa: 'Ripeti il brano', fai: cambiaRipeti }, { k: ['l'], etichetta: 'L', cosa: 'Scaletta', fai: () => sc.gira() }, - { k: ['t'], etichetta: 'T', cosa: 'Di seguito: suona anche gli altri brani', fai: () => cambiaSeguito() }, + { k: ['t'], etichetta: 'T', cosa: 'Riproduci coda: suona anche gli altri brani', fai: () => cambiaSeguito() }, { k: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], etichetta: '0 … 9', cosa: 'Vai al 0%, 10%… 90%', fai: (e) => { audio.currentTime = (+e.key / 10) * (audio.duration || 0); } }, ]; + async function scarica() { + try { + const r = await chiedi<{ nome: string }>('salvaCopertina'); + c.hud(`Salvata: ${r.nome}`); + } catch (e) { c.hud((e as Error).message); } + } + + function mostraCopertina(url: string) { + copertina.classList.remove('vuota'); + copertina.style.backgroundImage = `url(${url})`; + copertina.replaceChildren(); + const fondo = stanza.querySelector('.a-fondo') as HTMLElement | null; + if (fondo) { + fondo.classList.remove('vuoto'); + fondo.style.backgroundImage = `url(${url})`; + } + void tintaDa(url).then((col) => { if (col) stanza.style.setProperty('--cop', col); }); + } + + async function modifica() { + const velo = h('div.a-scelta'); + const griglia = h('div.a-varianti'); + const box = h('div.a-scelta-box', null, + h('h2', null, 'Copertina'), + h('p', null, 'MP3, M4A e FLAC la tengono dentro il file. Gli altri: la salvo accanto. Se qualcosa va storto, il brano resta com\'è.'), + h('div.a-scelta-fila', null, + h('button', { type: 'button', onclick: () => { void scarica(); velo.remove(); } }, 'Salva nella cartella'), + h('button', { type: 'button', onclick: () => void carica() }, 'Carica un\'immagine')), + h('p.a-oppure', null, 'Oppure una disegnata'), + griglia, + h('button.a-chiudi', { type: 'button', onclick: () => velo.remove() }, 'Chiudi')); + velo.append(box); + velo.addEventListener('click', (e) => { if (e.target === velo) velo.remove(); }); + stanza.append(velo); + + async function carica() { + try { + const r = await chiedi<{ copertina: string | null; nota: string | null } | null>('scegliCopertina'); + if (!r) return; + if (r.copertina) mostraCopertina(r.copertina); + if (r.nota) c.hud(r.nota); + velo.remove(); + } catch (e) { c.hud((e as Error).message); } + } + async function scegli(n: number) { + try { + const r = await chiedi<{ copertina: string | null; nota: string | null }>('mettiCopertina', { variante: n, titolo }); + if (r.copertina) mostraCopertina(r.copertina); + if (r.nota) c.hud(r.nota); + velo.remove(); + } catch (e) { c.hud((e as Error).message); } + } + try { + const urls = await chiedi('copertine', { titolo }); + urls.forEach((url, n) => { + griglia.append(h('button', { + type: 'button', title: 'Usa questa', + style: { backgroundImage: `url(${url})` }, + onclick: () => void scegli(n), + })); + }); + } catch (e) { c.hud((e as Error).message); } + } + return { tasti, info: () => [artista, tempo(info.durata)].filter(Boolean).join(' · '), diff --git a/ui/src/lettore/lettore.css b/ui/src/lettore/lettore.css index 83132af..3896511 100644 --- a/ui/src/lettore/lettore.css +++ b/ui/src/lettore/lettore.css @@ -262,7 +262,24 @@ kbd { display: inline-grid; place-items: center; min-width: 24px; height: 23px; .a-fondo.vuoto { background: radial-gradient(700px 480px at 25% 35%, color-mix(in srgb, var(--cop) 24%, transparent), transparent 70%), radial-gradient(600px 420px at 85% 75%, rgba(255, 61, 242, 0.12), transparent); filter: none; opacity: 1; } .a-scheda { position: relative; z-index: 1; width: min(1080px, 100%); display: grid; grid-template-columns: minmax(180px, min(36vh, 360px)) minmax(0, 1fr); gap: clamp(22px, 4vw, 56px); align-items: center; } .a-sinistra { display: grid; gap: 14px; } +.a-cover-box { position: relative; } .a-cover { width: 100%; aspect-ratio: 1; border-radius: 18px; background-size: cover; background-position: center; box-shadow: 0 30px 70px rgba(0, 0, 0, 0.6), 0 0 0 1px rgba(255, 255, 255, 0.08); transition: transform 0.6s var(--liscio), box-shadow 0.6s; } +.a-cover-tasti { position: absolute; left: 12px; right: 12px; bottom: 12px; display: flex; gap: 8px; opacity: 0; transform: translateY(6px); transition: opacity 0.15s, transform 0.15s; pointer-events: none; } +.a-cover-box:hover .a-cover-tasti, .a-cover-box:focus-within .a-cover-tasti { opacity: 1; transform: none; pointer-events: auto; } +.a-cover-tasti button { flex: 1; height: 34px; border-radius: 999px; background: rgba(12, 10, 18, 0.86); color: #fff; border: 1px solid rgba(255, 255, 255, 0.28); font: 800 11px var(--marchio); letter-spacing: 0.08em; text-transform: uppercase; } +.a-cover-tasti button:hover { background: #ffd54a; color: #1a1405; border-color: #ffd54a; } +.a-scelta { position: absolute; inset: 0; z-index: 6; display: grid; place-items: center; background: rgba(5, 4, 8, 0.62); } +.a-scelta-box { width: min(520px, 92%); background: #16141f; border: 1px solid rgba(255, 255, 255, 0.12); border-radius: 16px; padding: 18px 18px 16px; display: grid; gap: 12px; box-shadow: 0 24px 60px rgba(0, 0, 0, 0.45); } +.a-scelta-box h2 { margin: 0; font: 800 18px var(--ui); } +.a-scelta-box p { margin: 0; color: var(--testo2); font-size: 13.5px; line-height: 1.45; } +.a-scelta-fila { display: flex; flex-wrap: wrap; gap: 8px; } +.a-scelta-fila button, .a-chiudi { height: 34px; padding: 0 14px; border-radius: 999px; background: rgba(255, 255, 255, 0.06); color: #fff; border: 1px solid rgba(255, 255, 255, 0.16); font: 700 13px var(--ui); } +.a-scelta-fila button:first-child { background: #ffd54a; color: #1a1405; border-color: #ffd54a; } +.a-oppure { font: 800 11px var(--marchio) !important; letter-spacing: 0.14em; color: #ffd54a !important; } +.a-varianti { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; } +.a-varianti button { aspect-ratio: 1; border-radius: 10px; background: #0c0a12 center/cover no-repeat; border: 2px solid transparent; } +.a-varianti button:hover { border-color: #ffd54a; } +.a-scelta-box .a-chiudi { width: auto; min-width: 96px; height: 36px; padding: 0 18px; border-radius: 999px; justify-self: end; } .a-stanza.suona .a-cover { transform: scale(1.02); box-shadow: 0 34px 80px rgba(0, 0, 0, 0.65), 0 0 64px color-mix(in srgb, var(--cop) 30%, transparent), 0 0 0 1px rgba(255, 255, 255, 0.1); } .a-cover.vuota { display: grid; place-content: center; justify-items: center; gap: 6px; background: radial-gradient(circle at 30% 25%, #ff7bf6, #8a2cff 70%); } .a-cover.vuota b { font: 900 clamp(22px, 4vh, 40px) var(--marchio); color: #fffbe0; letter-spacing: 0.04em; } @@ -537,7 +554,7 @@ kbd { display: inline-grid; place-items: center; min-width: 24px; height: 23px; @media (max-width: 760px) { .a-scheda { grid-template-columns: 1fr; } - .a-cover { width: min(56vw, 34vh); margin: 0 auto; } + .a-cover-box { width: min(56vw, 34vh); margin: 0 auto; } .l-foglietto-corpo { grid-template-columns: 1fr; } .l-converti { padding: 0 9px; font-size: 0; gap: 0; } .c-tavolo.con-indice { grid-template-columns: 1fr; } diff --git a/ui/src/lettore/main.ts b/ui/src/lettore/main.ts index 9d0db56..47bdbfd 100644 --- a/ui/src/lettore/main.ts +++ b/ui/src/lettore/main.ts @@ -55,7 +55,6 @@ function disegnaBarra() { s.aggiornamento ? h('button.l-chip-agg', { title: `Installa la ${s.aggiornamento} e riapre`, onclick: () => void chiedi('aggiorna') }, h('i'), `Aggiornamento ${s.aggiornamento} disponibile`) : null, h('div.l-azioni', null, ...(s.vista?.azioni ?? []).map((a) => h('button.l-icona', { title: a.titolo, html: a.icona, onclick: a.fai })), - f.rapide.length ? h('button.l-icona.fai-subito', { title: 'Fai subito: le conversioni rapide (U)', html: ic.fulmine, onclick: (e: Event) => faiSubito(e.currentTarget as HTMLElement) }) : null, f.convertibile ? h('button.l-converti', { title: 'Converti (Ctrl+E)', onclick: () => void chiedi('converti') }, h('span', { html: ic.converti }), 'Converti') : null, h('button.l-icona', { title: 'Apri con… (un altro programma)', html: ic.apriCon, onclick: () => void chiedi('apriCon') }), h('button.l-icona', { title: 'Mostra nella cartella', html: ic.cartella, onclick: () => void chiedi('mostra') }), @@ -272,7 +271,9 @@ async function cestino() { function faiSubito(ancora?: HTMLElement) { const f = s.scheda; if (!f?.rapide.length) return; - menuSu(ancora ?? (document.querySelector('.fai-subito') as HTMLElement), f.rapide.map((r) => ({ + const dove = ancora ?? (document.querySelector('.l-converti') as HTMLElement | null) ?? (document.querySelector('.l-azioni') as HTMLElement | null); + if (!dove) return; + menuSu(dove, f.rapide.map((r) => ({ testo: r.etichetta, fai: () => { void chiedi('rapida', { azione: r.id }).then(() => hud(`${r.etichetta}…`, ic.fulmine)).catch((e) => hud((e as Error).message)); }, }))); diff --git a/ui/src/lettore/video.ts b/ui/src/lettore/video.ts index 24da554..1f639e0 100644 --- a/ui/src/lettore/video.ts +++ b/ui/src/lettore/video.ts @@ -55,6 +55,7 @@ export async function monta(c: Contesto): Promise { info.sottotitoli.some((x) => x.testo) || info.esterni.length ? bSub : null, bTracce, h('button.v-b.solo-fratelli', { title: 'Scaletta dei video della cartella (E)', html: ic.elenco, onclick: () => sc.gira() }), + h('button.v-b.testo', { title: 'Copertina del video (miniatura)', onclick: () => void modificaCopertina() }, 'Copertina'), h('button.v-b', { title: 'Salva il fotogramma (S)', html: ic.foto, onclick: () => void fotogramma() }), document.pictureInPictureEnabled ? h('button.v-b', { title: 'Finestrella sempre sopra (P)', html: ic.pip, onclick: () => void pip() }) : null, h('button.v-b', { title: 'Schermo intero (F)', html: ic.schermo, onclick: () => schermoIntero() }))); @@ -215,6 +216,63 @@ export async function monta(c: Contesto): Promise { } catch (e) { c.stato(null); c.hud((e as Error).message, ic.forbici); } } + + async function scaricaCopertina() { + try { + const r = await chiedi<{ nome: string }>('salvaCopertina'); + c.hud(`Salvata: ${r.nome}`, ic.foto); + } catch (e) { c.hud((e as Error).message, ic.foto); } + } + async function modificaCopertina() { + const velo = h('div.a-scelta'); + const griglia = h('div.a-varianti'); + const titolo = f.nome.replace(/\.[^.]+$/, ''); + const box = h('div.a-scelta-box', null, + h('h2', null, 'Copertina'), + h('p', null, 'MP4, MOV e MKV la tengono dentro: è la miniatura, anche in Esplora file. Gli altri: la salvo accanto. Se qualcosa va storto, il video resta com\'è.'), + h('div.a-scelta-fila', null, + h('button', { type: 'button', onclick: () => { void scaricaCopertina(); velo.remove(); } }, 'Salva nella cartella'), + h('button', { type: 'button', onclick: () => void caricaCopertina() }, 'Carica un\'immagine'), + h('button', { type: 'button', onclick: () => void questoFotogramma() }, 'Questo fotogramma')), + h('p.a-oppure', null, 'Oppure una disegnata'), + griglia, + h('button.a-chiudi', { type: 'button', onclick: () => velo.remove() }, 'Chiudi')); + velo.append(box); + velo.addEventListener('click', (e) => { if (e.target === velo) velo.remove(); }); + sala.append(velo); + async function caricaCopertina() { + try { + const r = await chiedi<{ copertina: string | null; nota: string | null } | null>('scegliCopertina'); + if (!r) return; + if (r.nota) c.hud(r.nota, ic.foto); + velo.remove(); + } catch (e) { c.hud((e as Error).message, ic.foto); } + } + async function questoFotogramma() { + if (!video.videoWidth) { c.hud('Il video non è ancora pronto', ic.foto); return; } + const cv = h('canvas', { width: video.videoWidth, height: video.videoHeight }); + try { + cv.getContext('2d')!.drawImage(video, 0, 0); + const r = await chiedi<{ nota: string | null }>('copertinaPng', { png: cv.toDataURL('image/png') }); + if (r.nota) c.hud(r.nota, ic.foto); + velo.remove(); + } catch (e) { c.hud((e as Error).message, ic.foto); } + } + async function scegli(n: number) { + try { + const r = await chiedi<{ nota: string | null }>('mettiCopertina', { variante: n, titolo }); + if (r.nota) c.hud(r.nota, ic.foto); + velo.remove(); + } catch (e) { c.hud((e as Error).message, ic.foto); } + } + try { + const urls = await chiedi('copertine', { titolo }); + urls.forEach((url, n) => { + griglia.append(h('button', { type: 'button', title: 'Usa questa', style: { backgroundImage: `url(${url})` }, onclick: () => void scegli(n) })); + }); + } catch (e) { c.hud((e as Error).message, ic.foto); } + } + // ——— sottotitoli: dentro il video (testo) o accanto (.srt, .vtt, .ass) ——— type Sub = { nome: string; carica: () => Promise }; const sub: Sub[] = [ @@ -495,6 +553,7 @@ export async function monta(c: Contesto): Promise { { titolo: 'Gira a sinistra (Maiusc R)', icona: ic.ruotaSx, fai: () => ruota(-90) }, { titolo: 'Gira a destra (R)', icona: ic.ruotaDx, fai: () => ruota(90) }, { titolo: "Taglia un pezzo: Z segna l'inizio, X la fine", icona: ic.forbici, fai: () => segna(da === null ? 'da' : 'a') }, + { titolo: 'Copertina (miniatura del video)', icona: ic.foto, fai: () => void modificaCopertina() }, ], info: () => { const v = info.video; diff --git a/ui/src/main.ts b/ui/src/main.ts index 2e2ebd8..6440937 100644 --- a/ui/src/main.ts +++ b/ui/src/main.ts @@ -14,7 +14,7 @@ import { icone, iconaCategoria, coloreCategoria } from './icone'; import { clac, accendiSuoni } from './suoni'; import { disegnaHome } from './app/home'; import { apriNovita, type DatiNovita } from './app/novita'; -import { s, ui, nomeCat, formato, fileDi, categoriePresenti, sceltaPer, eVideoVero } from './app/stato'; +import { s, ui, nomeCat, formato, fileDi, categoriePresenti, sceltaPer, eVideoVero, scelteDaRicordare } from './app/stato'; import { app, testa, coda, banco, piede, corpo, logoSvg, mostraAvviso, conservaVista } from './app/scheletro'; import { regolazioni } from './app/pannelli'; import { aggiornaPiano, pesoObiettivo } from './app/pannelli/video'; @@ -33,8 +33,104 @@ function cpuCorta(n: string) { return n.replace(/\(R\)|\(TM\)|CPU|Processor/gi, '').replace(/with Radeon.*$/i, '').replace(/@.*$/, '').replace(/^(AMD|Intel)\s+/i, '').replace(/Core\s+/i, '').replace(/\s+/g, ' ').trim(); } -function disegnaTesta() { +function gpuCorta(n: string) { + return n.replace(/NVIDIA |GeForce |AMD |Radeon |Intel\(R\) |Intel /gi, '').replace(/\(TM\)|\(R\)/gi, '').replace(/\s+/g, ' ').trim(); +} + +/** La bolla unica: scheda video o processore, quella con cui si codifica. */ +function usaGpu() { + const hw = s.stato.hardware; + const scelto = s.stato.impostazioni.codificaCon; + if (scelto === 'cpu') return false; + if (scelto === 'gpu') return !!hw?.acceleratore; + return !!hw?.acceleratore && s.opzioni.video.motore !== 'cpu'; +} + +interface Unita { motore: string; titolo: string; nota: string; gpu: boolean } + +/** Schede con un encoder vero, poi il processore. Due schede della stessa marca condividono l'encoder. */ +function unitaDisponibili(hw: NonNullable): Unita[] { + const marche: { marca: string; suf: string; motore: string; etichetta: string }[] = [ + { marca: 'nvidia', suf: '_nvenc', motore: 'nvidia', etichetta: 'NVENC' }, + { marca: 'amd', suf: '_amf', motore: 'amd', etichetta: 'AMF' }, + { marca: 'intel', suf: '_qsv', motore: 'intel', etichetta: 'Quick Sync' }, + ]; + const out: Unita[] = []; + for (const m of marche) { + if (!hw.encoder.some((e) => e.endsWith(m.suf))) continue; + const schede = hw.gpu.filter((g) => g.marca === m.marca); + const lista = schede.length ? schede : [{ nome: m.etichetta, marca: m.marca, vram: 0, driver: '' }]; + for (const g of lista) out.push({ motore: m.motore, titolo: gpuCorta(g.nome) || g.nome, nota: m.etichetta, gpu: true }); + } + out.push({ motore: 'cpu', titolo: cpuCorta(hw.cpu) || 'Processore', nota: `${hw.thread} thread`, gpu: false }); + return out; +} + +function marcaAttiva(hw: NonNullable): string { + const m = s.opzioni.video.motore; + if (m === 'nvidia' || m === 'amd' || m === 'intel' || m === 'cpu') return m; + if (hw.encoder.some((e) => e.endsWith('_nvenc'))) return 'nvidia'; + if (hw.encoder.some((e) => e.endsWith('_amf'))) return 'amd'; + if (hw.encoder.some((e) => e.endsWith('_qsv'))) return 'intel'; + return 'cpu'; +} + +function scegliUnita(u: Unita) { + clac(); + document.querySelector('.menu-motore')?.remove(); + s.stato.impostazioni.codificaCon = u.gpu ? 'gpu' : 'cpu'; + s.opzioni.video.motore = u.motore; + void chiedi('impostazioni', { codificaCon: s.stato.impostazioni.codificaCon, scelte: scelteDaRicordare() }); + s.piano = null; + disegnaTesta(); + if (s.vista === 'scegli' && s.stato.modo === 'finestra') ui.scegli(); +} + +function apriMenuMotore(ancora: HTMLElement) { + const gia = document.querySelector('.menu-motore'); + if (gia) { gia.remove(); return; } + const hw = s.stato.hardware; + if (!hw) return; + clac(); + const gpu = usaGpu(); + const marca = gpu ? marcaAttiva(hw) : 'cpu'; + const voci = unitaDisponibili(hw); + let segnata = false; + const menu = h('div.menu-motore', { role: 'menu' }); + for (const u of voci) { + const attiva = !segnata && u.motore === marca && u.gpu === gpu; + if (attiva) segnata = true; + menu.append(h(`button${attiva ? '.su' : ''}`, { type: 'button', role: 'menuitem', onclick: () => scegliUnita(u) }, + h(`i.led${u.gpu ? '.verde' : '.ambra'}`), + h('span', null, h('b', null, u.titolo), h('small', null, attiva ? `${u.nota} · in uso` : u.nota)))); + } + document.body.append(menu); + const r = ancora.getBoundingClientRect(); + menu.style.top = `${Math.round(r.bottom + 6)}px`; + menu.style.right = `${Math.max(8, Math.round(window.innerWidth - r.right))}px`; + const chiudi = (e: Event) => { + if (menu.contains(e.target as Node) || ancora.contains(e.target as Node)) return; + menu.remove(); + document.removeEventListener('pointerdown', chiudi, true); + }; + setTimeout(() => document.addEventListener('pointerdown', chiudi, true), 0); +} + +function bollaMotore() { const hw = s.stato.hardware; + if (!hw) return h('span.chip', null, h('i.led.lampeggia'), 'Guardo la macchina…'); + const gpu = usaGpu(); + const marca = gpu ? marcaAttiva(hw) : 'cpu'; + const scelta = unitaDisponibili(hw).find((u) => u.motore === marca && u.gpu === gpu) ?? unitaDisponibili(hw).at(-1)!; + const testo = scelta.gpu ? `${scelta.titolo} · ${scelta.nota}` : `${scelta.titolo} · ${hw.thread} thread`; + return h(`button.chip.motore${gpu ? '.gpu' : '.cpu'}`, { + type: 'button', + title: 'Scegli la scheda video o il processore', + onclick: (e: Event) => apriMenuMotore(e.currentTarget as HTMLElement), + }, h(`i.led${gpu ? '.verde' : '.ambra'}`), testo); +} + +function disegnaTesta() { testa.replaceChildren( h('div.marchio', null, h('span.logo', { html: logoSvg }), @@ -43,10 +139,10 @@ function disegnaTesta() { h('div.trascina', { 'data-regione': 'trascina' }), h('div.chip-hw', null, s.aggiornamento ? h('button.chip.agg', { title: `Installa la ${s.aggiornamento} e riapre il convertitore`, onclick: () => { clac(true); void chiedi('aggiorna', { installa: true }); } }, h('i.led.verde'), `Aggiornamento ${s.aggiornamento} disponibile`) : null, - hw?.acceleratore ? h('span.chip.gpu', { title: hw.gpu.map((g) => g.nome).join(' · ') }, h('i.led.verde'), hw.acceleratore) : h('span.chip', null, h('i.led'), 'Solo CPU'), - hw ? h('span.chip', { title: hw.cpu }, h('i.led.ambra'), `${cpuCorta(hw.cpu)} · ${hw.thread} thread`) : h('span.chip', null, h('i.led.lampeggia'), 'Guardo la macchina…'), + bollaMotore(), ), h('div.finestra', null, + s.torna ? h('button.btn-fin.indietro', { title: 'Torna al lettore e chiudi questa finestra', onclick: () => { clac(); void chiedi('tornaLettore'); } }, h('span.indietro-ico', { html: icone.freccia }), 'Indietro') : null, h('button.btn-fin.nov', { title: 'Novità e aggiornamenti', onclick: () => void apriNovita(), html: icone.novita }), h(`button.btn-fin.av${s.stato.impostazioni.avatarAttivo ? '.su' : ''}`, { title: s.stato.impostazioni.avatarAttivo ? "Spegni l'avatar" : "Accendi l'avatar", onclick: () => accendiAvatar(!s.stato.impostazioni.avatarAttivo), html: icone.avatar }), h('button.btn-fin', { title: 'Impostazioni', onclick: () => apriImpostazioni() , html: icone.ingranaggio }), @@ -303,6 +399,8 @@ function elementiDaConvertire() { const peso = c === 'immagine' && conQualita(f) && o.immagine.modo === 'peso' ? pesoVolutoFoto(id) : 0; o.immagine.pesoMaxByte = peso; if (peso) o.immagine.qualita = QUALITA_PER_PESO; + const sch = s.schede.get(id); + if (sch?.scrivi) o.scheda = { ...sch }; el.push({ ids: [id], formato: f.id, opzioni: o }); } } @@ -314,7 +412,7 @@ async function converti() { if (!elementi.length) return; clac(true); for (const c of categoriePresenti()) { const f = sceltaPer(c); if (f) s.stato.impostazioni.formati[c] = f.id; } - void chiedi('impostazioni', { formati: s.stato.impostazioni.formati, scelte: { video: { ...s.opzioni.video, pesoByte: 0 }, audio: s.opzioni.audio, immagine: s.opzioni.immagine, pdf: s.opzioni.pdf } }); + void chiedi('impostazioni', { formati: s.stato.impostazioni.formati, scelte: scelteDaRicordare() }); const ids = await chiedi('converti', { elementi }); s.giro = ids; s.vista = 'lavoro'; @@ -351,10 +449,13 @@ function opzioniSalvate() { if (!sc) return; for (const k of ['video', 'audio', 'immagine', 'pdf'] as const) if (sc[k]) Object.assign(s.opzioni[k], sc[k]); if (s.opzioni.video.modo === 'auto') s.opzioni.video.modo = 'peso'; + // la bolla in alto è la scelta che si ricorda: vince su un motore vecchio salvato in senso contrario + if (s.stato.impostazioni.codificaCon === 'cpu') s.opzioni.video.motore = 'cpu'; + else if (s.stato.impostazioni.codificaCon === 'gpu' && s.opzioni.video.motore === 'cpu') s.opzioni.video.motore = 'auto'; } async function avvia() { - Object.assign(ui, { tutto: disegnaTutto, scegli: disegnaScegli, piede: disegnaPiede, coda: disegnaCoda, fatto: disegnaFatto, rapido: disegnaRapido, impostazioni: apriImpostazioni, nuovoGiro }); + Object.assign(ui, { tutto: disegnaTutto, scegli: disegnaScegli, piede: disegnaPiede, coda: disegnaCoda, fatto: disegnaFatto, rapido: disegnaRapido, impostazioni: apriImpostazioni, nuovoGiro, testa: disegnaTesta }); await avviaFinto(); avviaIncolla(); ascolta('file', (f: InfoFile) => { @@ -402,6 +503,8 @@ async function avvia() { strumenti.enc?.valore(c.encoder / 100); strumenti.dec?.valore(c.decoder / 100); }); + ascolta('apriImpostazioni', () => apriImpostazioni()); + ascolta('torna', (d: { percorso?: string | null }) => { s.torna = d.percorso || null; disegnaTesta(); }); ascolta('avatar', (d: { si: boolean }) => { s.stato.impostazioni.avatarAttivo = d.si; disegnaTesta(); @@ -413,6 +516,7 @@ async function avvia() { s.piano = null; disegnaTutto(); }); + ascolta('recenti', () => { if (s.vista === 'scegli' && !s.attiva) disegnaScegli(); }); ascolta('modo', (m: { modo: 'finestra' | 'rapido' }) => { s.stato.modo = m.modo; app.classList.toggle('rapido', m.modo === 'rapido'); @@ -425,6 +529,7 @@ async function avvia() { s.stato = await chiedi('stato'); s.aggiornamento = s.stato.aggiornamento ?? null; + s.torna = s.stato.torna ?? null; accendiSuoni(s.stato.impostazioni.suoniAccesi); // dopo un aggiornamento le novità si aprono da sole, una volta if (s.stato.modo === 'finestra') void chiedi('novita').then((n) => { if (n?.nuova) setTimeout(() => void apriNovita(n), 1200); }).catch(() => {}); diff --git a/ui/src/ponte.ts b/ui/src/ponte.ts index 5014aeb..f793900 100644 --- a/ui/src/ponte.ts +++ b/ui/src/ponte.ts @@ -80,6 +80,12 @@ export interface Impostazioni { avatarCambioAuto?: boolean; /** I gruppi scelti per «Aprire tutto con DaProd» (null = tutti). */ gruppiPredefiniti?: string[] | null; + /** Con cosa codificare i video: la scheda o il processore. Si ricorda. */ + codificaCon?: 'gpu' | 'cpu' | null; + /** Cartella dove finiscono screenshot, registrazioni e il resto che fa l'app. Vuota = Immagini/DaPConvertitore. */ + cartellaMia?: string | null; + /** Scorciatoia globale dello screenshot, per esempio «Ctrl+Maiusc+S». */ + scorciatoiaSchermo?: string | null; formati: Record; scelte?: Record | null; } @@ -152,6 +158,8 @@ export interface Stato { /** La mini interfaccia accanto all'avatar, e la scelta già fatta da lì («Comprimi»). */ compatto?: boolean; scelta?: { formato: string; preset?: string | null } | null; + /** Si è arrivati dal lettore: «Indietro» sulla barra bianca riapre quel file. */ + torna?: string | null; } /** La regola delle app predefinite di Windows e quanti tipi hanno davvero il lettore come programma (UserChoice). */ @@ -195,7 +203,21 @@ export interface StimaImmagine { peso: number; qualita: number; scala: number; m export interface OpzioniPdf { dpi: number } /** Compressione degli archivi: -1 solo archiviare, 0 il livello di partenza del formato, 1…9 (7-Zip). */ export interface OpzioniArchivio { livello: number; /** Solo in memoria: serve per aprire un archivio cifrato o, in ZIP e 7Z, per cifrarlo. */ password?: string } -export interface Opzioni { video: OpzioniVideo; audio: OpzioniAudio; immagine: OpzioniImmagine; pdf: OpzioniPdf; archivio: OpzioniArchivio } +/** Le info corrette nella sezione «Info del file»: finiscono nel file convertito. La copertina è un percorso, «nessuna» o «generata:n». */ +export interface OpzioniScheda { + scrivi: boolean; + titolo?: string | null; + artista?: string | null; + album?: string | null; + anno?: string | null; + traccia?: string | null; + commento?: string | null; + autore?: string | null; + descrizione?: string | null; + dataScatto?: string | null; + copertina?: string | null; +} +export interface Opzioni { video: OpzioniVideo; audio: OpzioniAudio; immagine: OpzioniImmagine; pdf: OpzioniPdf; archivio: OpzioniArchivio; scheda?: OpzioniScheda } type Ascoltatore = (dati: any) => void; diff --git a/ui/src/stile.css b/ui/src/stile.css index acca360..87d2de3 100644 --- a/ui/src/stile.css +++ b/ui/src/stile.css @@ -83,6 +83,7 @@ code { font: 600 12px 'Cascadia Mono', Consolas, monospace; color: var(--oro); b .trascina { flex: 1; align-self: stretch; } .chip-hw { display: flex; gap: 8px; } .chip { display: inline-flex; align-items: center; gap: 7px; height: 26px; padding: 0 11px; border-radius: 13px; background: #101016; border: 1px solid var(--bordo); color: var(--testo2); font: 700 12px var(--ui); letter-spacing: 0.02em; white-space: nowrap; } +button.chip { cursor: pointer; font: 700 12px var(--ui); letter-spacing: 0.02em; } .chip.gpu { color: var(--testo); } .chip.agg { color: var(--oro); border-color: rgba(255, 213, 74, 0.45); background: #1d1a10; cursor: pointer; animation: respira 2.4s ease-in-out infinite; } .chip.agg:hover { background: #2a2414; } @@ -94,7 +95,7 @@ code { font: 600 12px 'Cascadia Mono', Consolas, monospace; color: var(--oro); b .btn-fin.chiudi:hover { background: #c42b4a; color: #fff; } /* ——— corpo ——— */ -.corpo { display: grid; grid-template-columns: 318px minmax(0, 1fr); min-height: 0; } +.corpo { display: grid; grid-template-columns: 236px minmax(0, 1fr); min-height: 0; } .titolo-sezione { display: flex; align-items: center; justify-content: space-between; font: 700 11px var(--marchio); letter-spacing: 0.22em; color: var(--testo2); margin: 2px 2px 10px; } .titolo-sezione .conta { font: 700 12px var(--ui); letter-spacing: 0.03em; color: var(--testo3); } @@ -103,21 +104,21 @@ code { font: 600 12px 'Cascadia Mono', Consolas, monospace; color: var(--oro); b .lista { display: flex; flex-direction: column; gap: 7px; overflow-y: auto; min-height: 0; margin: 0 -4px; padding: 0 4px 6px; flex: 1; } .scheda { --tinta: var(--oro); - position: relative; display: grid; grid-template-columns: 74px minmax(0, 1fr) auto; gap: 10px; align-items: center; - padding: 7px 8px 7px 7px; border-radius: 9px; background: var(--metallo); border: 1px solid var(--bordo); + position: relative; display: grid; grid-template-columns: 44px minmax(0, 1fr) auto; gap: 7px; align-items: center; + padding: 4px 6px 4px 5px; border-radius: 8px; background: var(--metallo); border: 1px solid var(--bordo); box-shadow: 0 2px 6px rgba(0, 0, 0, 0.35); cursor: pointer; transition: border-color 0.15s, transform 0.15s, opacity 0.15s; } .scheda::before { content: ''; position: absolute; left: -1px; top: 10px; bottom: 10px; width: 3px; border-radius: 2px; background: var(--tinta); box-shadow: 0 0 8px var(--tinta); opacity: 0.85; } .scheda:hover { border-color: var(--bordo-forte); } .scheda.attiva { border-color: color-mix(in srgb, var(--tinta) 60%, transparent); box-shadow: 0 0 0 1px color-mix(in srgb, var(--tinta) 30%, transparent), 0 4px 16px rgba(0, 0, 0, 0.45); } .scheda.spenta { opacity: 0.55; } -.figurina { position: relative; width: 74px; height: 46px; border-radius: 6px; overflow: hidden; background: #0d0c12; display: grid; place-items: center; border: 1px solid rgba(0, 0, 0, 0.6); } +.figurina { position: relative; width: 44px; height: 30px; border-radius: 5px; overflow: hidden; background: #0d0c12; display: grid; place-items: center; border: 1px solid rgba(0, 0, 0, 0.6); } .figurina img { width: 100%; height: 100%; object-fit: cover; } .figurina .icona-cat svg { width: 22px; height: 22px; color: var(--tinta); opacity: 0.85; } .figurina .est { position: absolute; left: 3px; bottom: 3px; font: 800 9px var(--ui); letter-spacing: 0.04em; padding: 0 4px; border-radius: 3px; background: rgba(0, 0, 0, 0.72); color: var(--tinta); } .scheda .testo { min-width: 0; } -.scheda .nome { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font: 700 14px var(--ui); color: var(--testo); } -.scheda .meta { font: 600 12px var(--ui); color: var(--testo2); margin-top: 1px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.scheda .nome { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font: 700 12.5px var(--ui); color: var(--testo); } +.scheda .meta { font: 600 11px var(--ui); color: var(--testo2); margin-top: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .scheda .togli { width: 24px; height: 24px; display: grid; place-items: center; border-radius: 6px; color: var(--testo3); opacity: 0; transition: opacity 0.15s; } .scheda .togli svg { width: 14px; height: 14px; } .scheda:hover .togli { opacity: 1; } @@ -146,10 +147,10 @@ code { font: 600 12px 'Cascadia Mono', Consolas, monospace; color: var(--oro); b .scheda-cat.su .led { background: var(--tinta); box-shadow: 0 0 8px var(--tinta); } /* le cassette dei formati */ -.cassette { display: grid; grid-template-columns: repeat(auto-fill, minmax(124px, 1fr)); gap: 10px; margin-bottom: 18px; } +.cassette { display: grid; grid-template-columns: repeat(auto-fill, minmax(92px, 1fr)); gap: 6px; margin-bottom: 12px; } .cassetta { --tinta: var(--oro); - position: relative; height: 88px; padding: 12px 12px 10px; border-radius: 10px; text-align: left; + position: relative; height: 54px; padding: 7px 8px 6px; border-radius: 8px; text-align: left; background: radial-gradient(circle at 30% 82%, #0b0a0f 0 5px, transparent 5.5px), radial-gradient(circle at 70% 82%, #0b0a0f 0 5px, transparent 5.5px), @@ -160,9 +161,9 @@ code { font: 600 12px 'Cascadia Mono', Consolas, monospace; color: var(--oro); b transition: transform 0.12s, border-color 0.15s, box-shadow 0.15s; } .cassetta .striscia { position: absolute; left: 0; right: 0; top: 0; height: 3px; background: var(--tinta); opacity: 0.55; } -.cassetta .etichetta { font: 900 21px var(--marchio); letter-spacing: 0.03em; color: var(--testo); line-height: 1.1; } -.cassetta .descr { font: 600 12.5px var(--ui); color: var(--testo2); line-height: 1.15; max-width: 92%; } -.cassetta .led { position: absolute; right: 10px; top: 12px; } +.cassetta .etichetta { font: 900 14px var(--marchio); letter-spacing: 0.03em; color: var(--testo); line-height: 1.05; } +.cassetta .descr { font: 600 10.5px var(--ui); color: var(--testo2); line-height: 1.15; max-width: 92%; } +.cassetta .led { position: absolute; right: 7px; top: 7px; } .cassetta:hover { transform: translateY(-1px); border-color: var(--bordo-forte); } .cassetta:active { transform: translateY(2px); box-shadow: 0 1px 0 #050508; } .cassetta.scelta { border-color: color-mix(in srgb, var(--tinta) 70%, transparent); box-shadow: 0 3px 0 #050508, 0 0 0 1px color-mix(in srgb, var(--tinta) 35%, transparent), 0 0 24px color-mix(in srgb, var(--tinta) 22%, transparent); } @@ -198,6 +199,14 @@ code { font: 600 12px 'Cascadia Mono', Consolas, monospace; color: var(--oro); b .tasto.su { color: var(--oro); background: linear-gradient(180deg, #34312a, #24221d); border-color: rgba(255, 213, 74, 0.35); box-shadow: 0 2px 0 #050508, 0 0 12px rgba(255, 213, 74, 0.12), inset 0 0 8px rgba(255, 213, 74, 0.08); } .tasto.su small { color: rgba(255, 213, 74, 0.6); } .tasto:disabled { opacity: 0.35; } +.campo-scorciatoia { + display: inline-flex; align-items: center; justify-content: center; flex: none; + height: 34px; min-width: 132px; padding: 0 12px; border-radius: 8px; + background: #fff8e6; border: 1px solid #e0a020; color: #1a1408; + font-family: var(--ui); font-weight: 700; font-size: 13.5px; line-height: 1; letter-spacing: 0; + white-space: nowrap; +} +.campo-scorciatoia.ascolta { background: #2a1230; color: #ffd54a; border-color: #ff3df2; } .tasto.piccolo { height: 30px; padding: 0 10px; font-size: 13px; } .interruttore { display: inline-flex; align-items: center; gap: 10px; padding: 6px 12px 6px 6px; border-radius: 9px; background: var(--gomma); border: 1px solid var(--bordo); color: var(--testo2); font: 700 13.5px var(--ui); text-align: left; } @@ -421,6 +430,23 @@ input[type='range'] { -webkit-appearance: none; appearance: none; background: tr .campo:focus { border-color: var(--oro); } .imp-sezione { font: 700 10.5px var(--marchio); letter-spacing: 0.22em; color: var(--oro); padding: 14px 0 2px; } .cassetto { max-height: calc(100vh - 52px); overflow-y: auto; } +/* Impostazioni: larga, due colonne, la testata ferma (il corpo scorre da solo se non ci sta) */ +.velo.impostazioni > .cassetto { width: min(1080px, calc(100vw - 36px)); overflow: hidden; padding: 0 0 12px; gap: 0; } +.velo.impostazioni > .cassetto > .confronto-testa { position: relative; top: auto; margin: 0; flex: none; padding: 14px 18px 12px; background: #17151f; border-radius: 14px 14px 0 0; } +.imp-colonne { display: grid; grid-template-columns: minmax(0, 1.15fr) minmax(0, 0.85fr); gap: 2px 28px; align-items: start; overflow: auto; max-height: calc(100vh - 120px); padding: 4px 18px 8px; } +.imp-col { min-width: 0; } +.imp-dove { margin: 0; color: var(--oro); font: 600 12.5px/1.4 var(--ui); word-break: break-all; } +.imp-file { list-style: none; margin: 6px 0 0; padding: 0; display: grid; gap: 2px; } +.imp-file button { width: 100%; text-align: left; padding: 3px 0; color: var(--testo2); font: 600 12.5px var(--ui); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.imp-file button:hover { color: var(--oro); } +.peso-ora { font: 700 13px var(--ui); color: var(--testo); } +.menu-motore { position: fixed; z-index: 80; min-width: 240px; max-width: 340px; padding: 6px; border-radius: 12px; background: rgba(22, 20, 29, 0.98); border: 1px solid var(--bordo-forte); box-shadow: var(--ombra); display: grid; gap: 2px; } +.menu-motore button { display: flex; align-items: center; gap: 10px; padding: 8px 10px; border-radius: 8px; color: var(--testo); text-align: left; } +.menu-motore button:hover, .menu-motore button.su { background: rgba(255, 213, 74, 0.12); } +.menu-motore button span { display: grid; min-width: 0; } +.menu-motore button b { font: 700 14px var(--ui); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.menu-motore button small { color: var(--testo3); font: 600 12px var(--ui); } +.menu-motore button.su b { color: var(--oro); } /* la X (e il titolo) restano sempre in vista quando si scorre */ .cassetto > .confronto-testa { position: sticky; top: 0; z-index: 3; margin: -14px -16px 6px; padding: 12px 16px 10px; background: var(--pann2); border-radius: 14px 14px 0 0; border-bottom: 1px solid rgba(255, 255, 255, 0.08); } /* il simbolo dell'avatar: oro se acceso, spento e barrato se no */ @@ -466,9 +492,11 @@ body.nel-browser #app { width: min(1080px, 100vw); height: min(720px, 100vh); bo body.nel-browser #app.rapido { width: 480px; height: 190px; } @media (max-width: 900px) { - .corpo { grid-template-columns: 250px minmax(0, 1fr); } + .corpo, .corpo.con-anteprima { grid-template-columns: 210px minmax(0, 1fr); } + .corpo.con-linguetta { grid-template-columns: 210px minmax(0, 1fr) 34px; } .quadro { grid-template-columns: 1fr; } .piastra { grid-template-columns: 1fr; } + .imp-colonne { grid-template-columns: 1fr; } } /* ——— 1.1: un velo sopra l'altro non fa più buio (il secondo è trasparente) ——— */ @@ -499,7 +527,12 @@ body.nel-browser #app.rapido { width: 480px; height: 190px; } .testa .chip.agg:hover { background: #ffeaa6; } .testa .led { box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.25); } .testa .led.verde { box-shadow: 0 0 6px var(--verde); } +.testa button.chip.motore { color: #1f1c28; } +.testa button.chip.motore:hover { background: #fff; border-color: #9a90b0; } .testa .btn-fin { color: #4a4659; } +.testa .btn-fin.indietro { width: auto; display: inline-flex; align-items: center; gap: 6px; padding: 0 12px 0 8px; color: #1f1c28; font: 700 13px var(--ui); } +.testa .btn-fin.indietro .indietro-ico { display: grid; transform: scaleX(-1); } +.testa .btn-fin.indietro .indietro-ico svg { width: 16px; height: 16px; } .testa .btn-fin:hover { background: rgba(0, 0, 0, 0.08); color: #14121a; } .testa .btn-fin.chiudi:hover { background: #c42b4a; color: #fff; } @@ -531,8 +564,8 @@ body.nel-browser #app.rapido { width: 480px; height: 190px; } .menu-destro small { color: var(--testo3); font: 600 12px var(--ui); } /* ——— 1.8.0: l'anteprima a destra, come in VS Code ——— */ -.corpo.con-anteprima { grid-template-columns: 318px minmax(0, 1fr) var(--ap-larghezza, 400px); } -.corpo.con-linguetta { grid-template-columns: 318px minmax(0, 1fr) 34px; } +.corpo.con-anteprima { grid-template-columns: 236px minmax(0, 1fr) var(--ap-larghezza, 400px); } +.corpo.con-linguetta { grid-template-columns: 236px minmax(0, 1fr) 34px; } .anteprima[hidden], .ap-linguetta[hidden], .ap-cerca[hidden], .ap-avviso[hidden] { display: none !important; } .anteprima { position: relative; display: flex; flex-direction: column; min-height: 0; min-width: 0; @@ -592,8 +625,8 @@ body.nel-browser #app.rapido { width: 480px; height: 190px; } .ap-linguetta-testo { writing-mode: vertical-rl; font: 700 10px var(--marchio); letter-spacing: 0.24em; } @media (max-width: 900px) { - .corpo.con-anteprima { grid-template-columns: 250px minmax(0, 1fr) min(var(--ap-larghezza, 400px), 40vw); } - .corpo.con-linguetta { grid-template-columns: 250px minmax(0, 1fr) 34px; } + .corpo.con-anteprima { grid-template-columns: 210px minmax(0, 1fr) min(var(--ap-larghezza, 400px), 40vw); } + .corpo.con-linguetta { grid-template-columns: 210px minmax(0, 1fr) 34px; } } /* ——— 1.9.0: la minimappa e la colonna delle figurine ——— */ @@ -607,6 +640,55 @@ body.nel-browser #app.rapido { width: 480px; height: 190px; } .cl-segnaposto.manca { opacity: 0.45; } .cl-etichetta { font: 700 12.5px var(--ui); color: var(--testo2); min-height: 16px; } .cl-strisce { flex: none; width: 104px; overflow-y: auto; overflow-x: hidden; padding: 8px 8px; display: flex; flex-direction: column; gap: 8px; border-left: 1px solid #1d1b25; background: rgba(15, 14, 20, 0.7); outline: 0; } +/* un brano: play, volume e la timeline stanno sotto la copertina e l'onda, non in una colonna a destra */ +.cl-suono { display: none; } +.ap-colonna.audio { flex-direction: column; } +.ap-colonna.audio .cl-strisce { display: none; } +.ap-colonna.audio .cl-etichetta { display: none; } +.ap-colonna.audio .cl-grande { width: 100%; justify-content: flex-end; gap: 8px; padding-bottom: 6px; } +.ap-colonna.audio .cl-barra { height: 16px; cursor: pointer; } +.ap-colonna.audio .cl-suono { display: flex; flex: none; width: auto; flex-direction: row; align-items: center; justify-content: flex-start; gap: 14px; padding: 8px 14px 12px; border-left: 0; border-top: 1px solid #1d1b25; background: rgba(15, 14, 20, 0.7); } +/* un video in modifica: niente colonna di fotogrammi a destra; i controlli stanno sotto, la barra è il punto in cui cercare */ +.ap-colonna.video { flex-direction: column; } +.ap-colonna.video .cl-strisce { display: none; } +.ap-colonna.video .cl-etichetta { display: none; } +.ap-colonna.video .cl-grande { width: 100%; justify-content: flex-end; gap: 8px; padding-bottom: 6px; } +.ap-colonna.video .cl-barra { height: 20px; border-radius: 10px; cursor: pointer; background: #2a2736; box-shadow: inset 0 0 0 1px rgba(255, 213, 74, 0.4); } +.ap-colonna.video .cl-suono { display: flex; flex: none; width: auto; flex-wrap: wrap; flex-direction: row; align-items: center; gap: 12px; padding: 8px 14px 12px; border-top: 1px solid #1d1b25; background: rgba(15, 14, 20, 0.7); } +.ap-colonna:focus { outline: none; } +.cl-quadro { display: none; height: 36px; padding: 0 12px; border-radius: 9px; color: #1a1408; background: #ffd54a; font: 800 13px var(--ui); } +.ap-colonna.video .cl-quadro { display: inline-flex; align-items: center; } +.cl-tasti { display: none; } +.ap-colonna.video .cl-tasti { display: block; flex: 1 1 120px; min-width: 0; font: 600 12px var(--ui); color: #d9d4e6; } +.ap-colonna.audio .cl-vol { width: 120px; } +.ap-colonna.audio .cl-play { width: 42px; height: 42px; } +.cl-play { width: 54px; height: 54px; border-radius: 50%; display: grid; place-items: center; color: #102a1d; background: radial-gradient(circle at 35% 30%, #b9ffe0, #5dffb4 62%, #1c9a62); box-shadow: 0 6px 18px rgba(93, 255, 180, 0.28); } +.cl-play svg { width: 22px; height: 22px; } +.cl-play:hover { filter: brightness(1.06); } +.cl-tempo { font: 700 13px var(--ui); color: var(--testo); font-variant-numeric: tabular-nums; } +.cl-vol { width: 100%; height: 16px; accent-color: #5dffb4; cursor: pointer; } +.cl-vol::-webkit-slider-runnable-track { height: 4px; border-radius: 4px; background: #3a3648; } +.cl-vol::-webkit-slider-thumb { margin-top: -5px; } +.cl-vol-etichetta { font: 700 10px var(--marchio); letter-spacing: 0.16em; color: var(--testo3); } +.scheda-file { margin-top: 4px; border: 1px solid var(--bordo); border-radius: 12px; background: rgba(0, 0, 0, 0.22); } +.scheda-file > .testa-scheda { width: 100%; display: flex; align-items: center; gap: 8px; padding: 10px 12px; color: var(--testo); font: 800 12px var(--marchio); letter-spacing: 0.14em; } +.scheda-file .freccia { margin-left: auto; width: 16px; height: 16px; display: grid; } +.scheda-file .freccia svg { width: 16px; height: 16px; } +.scheda-file.aperta .freccia { transform: rotate(180deg); } +.scheda-file .corpo-scheda { display: none; padding: 0 12px 12px; } +.scheda-file.aperta .corpo-scheda { display: grid; gap: 10px; } +.scheda-nota { margin: 0; font: 600 12.5px/1.45 var(--ui); color: var(--testo2); } +.scheda-campi { display: grid; grid-template-columns: 1fr 1fr; gap: 8px 10px; } +.scheda-campi label { display: grid; gap: 4px; font: 700 11px var(--ui); color: var(--testo3); min-width: 0; } +.scheda-campi .campo { width: 100%; } +.scheda-cover { display: flex; gap: 12px; align-items: center; } +.scheda-cover img { width: 72px; height: 72px; object-fit: cover; border-radius: 10px; background: #0b0a0f; } +.scheda-cover img[hidden] { display: none; } +.scheda-dida { display: block; margin-bottom: 6px; font: 600 12.5px var(--ui); color: var(--testo2); } +.scheda-cover-tasti { display: flex; flex-wrap: wrap; gap: 6px; } +.scheda-varianti { display: grid; grid-template-columns: repeat(auto-fill, minmax(68px, 1fr)); gap: 6px; } +.scheda-varianti button { aspect-ratio: 1; border-radius: 8px; background: #0b0a0f center/cover no-repeat; border: 2px solid transparent; } +.scheda-varianti button.su, .scheda-varianti button:hover { border-color: var(--oro); } .cl-strisce.sola { width: 96px; } .cl-voce { position: relative; flex: none; display: block; width: 100%; padding: 0; border-radius: 5px; border: 2px solid transparent; background: none; cursor: pointer; } .cl-mini { min-height: 56px; border-radius: 3px; overflow: hidden; background: #1a1823; display: grid; place-items: center; } @@ -638,8 +720,9 @@ body.nel-browser #app.rapido { width: 480px; height: 190px; } /* Impostazioni: il blocco «Aggiusta tutto» */ .imp-sistema { display: flex; flex-direction: column; gap: 12px; padding: 16px; margin: 6px 0 10px; border: 1px solid var(--bordo); border-radius: 14px; background: rgba(255, 255, 255, 0.03); } -.imp-sistema-testa { display: flex; gap: 18px; align-items: center; justify-content: space-between; } -.imp-sistema-testa p { margin: 4px 0 0; color: var(--testo2); font-size: 13px; line-height: 1.45; max-width: 52ch; } +.imp-sistema-testa { display: flex; gap: 12px; align-items: flex-start; justify-content: space-between; flex-wrap: wrap; } +.imp-sistema-testa p { margin: 4px 0 0; color: var(--testo2); font-size: 13px; line-height: 1.4; } +.imp-riga { padding: 8px 0; } .tasto.grande { padding: 14px 22px; font-size: 15px; white-space: nowrap; } .imp-stati { list-style: none; margin: 0; padding: 0; display: grid; gap: 6px; } .imp-stati li { display: flex; align-items: baseline; gap: 10px; font-size: 14px; color: var(--testo2); } @@ -661,7 +744,12 @@ body.nel-browser #app.rapido { width: 480px; height: 190px; } .strada em { font-style: normal; color: var(--testo3); font-size: 12px; line-height: 1.35; } .recenti { display: flex; flex-direction: column; gap: 4px; } .recenti-vuoto { color: var(--testo3); font-size: 13px; margin: 2px 0; } -.recente { display: flex; align-items: center; gap: 12px; padding: 8px 10px; border-radius: 10px; background: rgba(255, 255, 255, 0.025); } +.recente { display: flex; align-items: center; gap: 12px; padding: 8px 10px; border-radius: 10px; background: rgba(255, 255, 255, 0.025); cursor: pointer; } +.recente:hover { background: rgba(255, 255, 255, 0.05); } +.recente-foto-box { width: 44px; height: 44px; flex: none; border-radius: 8px; overflow: hidden; background: rgba(255, 255, 255, 0.04); display: grid; } +.recente-foto-box .recente-icona, .recente-foto { grid-area: 1 / 1; } +.recente-foto { width: 44px; height: 44px; object-fit: cover; } +.recente-foto-box .recente-icona { display: grid; place-items: center; } .recente-icona svg { width: 20px; height: 20px; color: var(--tinta); } .recente-testo { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 1px; } .recente-testo b { font-size: 14px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } @@ -688,16 +776,20 @@ body.nel-browser #app.rapido { width: 480px; height: 190px; } } .avviso { color: #ffe3e8; border-color: rgba(255, 77, 109, 0.4) !important; background: rgba(42, 18, 25, 0.5) !important; } -/* novità e aggiornamenti */ -.novita-cassetto { width: min(640px, 100%); } -.novita-testo { max-height: min(56vh, 460px); overflow-y: auto; padding-right: 6px; } +/* novità e aggiornamenti: la testata non scorre, il testo sì (niente sticky che ci passa sotto) */ +.novita-cassetto { width: min(680px, calc(100vw - 48px)); overflow: hidden; padding: 0 0 14px; gap: 0; } +.novita-cassetto > .confronto-testa { position: relative; top: auto; margin: 0; flex: none; padding: 14px 16px 12px; background: #17151f; border-radius: 14px 14px 0 0; } +.novita-testo { max-height: min(58vh, 480px); overflow-y: auto; padding: 14px 16px 6px; } .novita-testo ul { list-style: none; margin: 0; padding: 0; display: grid; gap: 10px; } .novita-testo li { position: relative; padding-left: 16px; font-size: 14px; line-height: 1.5; color: var(--testo2); } .novita-testo li::before { content: ''; position: absolute; left: 0; top: 0.62em; width: 6px; height: 6px; border-radius: 50%; background: var(--oro); box-shadow: 0 0 8px rgba(255, 213, 74, 0.6); } .novita-testo b { color: var(--testo); } .novita-testo code { font-size: 12.5px; color: var(--oro); } +.novita-testo .link { font: 700 14px var(--ui); vertical-align: baseline; } .novita-stato { color: var(--verde); font-size: 13px; } -.btn-fin.nov svg { color: var(--oro); } +/* la barra è bianca: la stellina delle novità sta scura, se no non si legge */ +.btn-fin.nov svg { color: #2c2840; } +.testa .btn-fin.nov:hover svg { color: #14121a; } /* la mini interfaccia accanto all'avatar: la stessa del convertitore, senza la lista dei file e senza l'anteprima */ #app.compatto .corpo { grid-template-columns: minmax(0, 1fr) !important; } @@ -742,10 +834,10 @@ body.nel-browser #app.rapido { width: 480px; height: 190px; } /* le cassette: i due fori stanno nella loro fascia in basso, il testo sopra (al massimo due righe) */ .cassetta { - height: auto; min-height: 88px; padding-bottom: 24px; + height: auto; min-height: 58px; padding-bottom: 16px; background: - radial-gradient(circle at 30% calc(100% - 12px), #0b0a0f 0 5px, transparent 5.5px), - radial-gradient(circle at 70% calc(100% - 12px), #0b0a0f 0 5px, transparent 5.5px), + radial-gradient(circle at 30% calc(100% - 9px), #0b0a0f 0 4px, transparent 4.5px), + radial-gradient(circle at 70% calc(100% - 9px), #0b0a0f 0 4px, transparent 4.5px), linear-gradient(180deg, #2c2b35 0%, #1f1e26 60%, #1a1920 100%); } .cassetta .descr { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }