Compare commits

...
8 Commits
14 changed files with 1075 additions and 156 deletions

No files matched your search

+9 -7
View File
@@ -38,6 +38,7 @@
"Gerarchia: premi la freccia accanto alla maniglia per aprire un gruppo. Il rientro, il carattere e la tonalita indicano se una riga e figlia, nipote o di livello successivo.", "Gerarchia: premi la freccia accanto alla maniglia per aprire un gruppo. Il rientro, il carattere e la tonalita indicano se una riga e figlia, nipote o di livello successivo.",
"Selezione multipla: attiva il flag sulle righe desiderate. Esempio: seleziona tre poligoni per esportare solo quelli oppure per bloccarli con una sola operazione.", "Selezione multipla: attiva il flag sulle righe desiderate. Esempio: seleziona tre poligoni per esportare solo quelli oppure per bloccarli con una sola operazione.",
"Rinomina e attributi: Rinomina modifica il nome mostrato e salvato nei progetti e nei file esportati; Attributi apre un editor multilinea per consultare o correggere i dati associati.", "Rinomina e attributi: Rinomina modifica il nome mostrato e salvato nei progetti e nei file esportati; Attributi apre un editor multilinea per consultare o correggere i dati associati.",
"Colori: espandi un padre o un figlio e usa gli editor di linea e riempimento. Puoi scegliere il colore, prelevarlo con il contagocce se supportato, oppure inserire e copiare i valori HEX, RGB e HSL; sul padre viene applicato a tutto il gruppo.",
"Blocco: il lucchetto impedisce modifiche e spostamenti involontari. Sblocca l'oggetto prima di usare la matita o gli strumenti geometrici.", "Blocco: il lucchetto impedisce modifiche e spostamenti involontari. Sblocca l'oggetto prima di usare la matita o gli strumenti geometrici.",
"Sposta nel gruppo cambia l'appartenenza. Esempio: trasferisci un poligono da Disegni e POI a Progetti e dati importati, oppure in un nuovo sottogruppo chiamato Rilievo nord.", "Sposta nel gruppo cambia l'appartenenza. Esempio: trasferisci un poligono da Disegni e POI a Progetti e dati importati, oppure in un nuovo sottogruppo chiamato Rilievo nord.",
"Sposta geometria cambia invece le coordinate dell'oggetto, per esempio 100 metri verso nord; non modifica il gruppo di appartenenza.", "Sposta geometria cambia invece le coordinate dell'oggetto, per esempio 100 metri verso nord; non modifica il gruppo di appartenenza.",
@@ -48,15 +49,15 @@
[ [
"Compila i campi nell'ordine Regione, Comune, Foglio e Particella: ogni scelta carica l'elenco necessario al campo successivo.", "Compila i campi nell'ordine Regione, Comune, Foglio e Particella: ogni scelta carica l'elenco necessario al campo successivo.",
"Esempio: scegli Campania, il Comune, il foglio 12 e la particella 345, poi premi Mostra particella sulla mappa.", "Esempio: scegli Campania, il Comune, il foglio 12 e la particella 345, poi premi Mostra particella sulla mappa.",
"Il confine ufficiale viene evidenziato in rosso. Se Centra e zooma quando seleziono un oggetto e attivo nelle Impostazioni, la mappa lo inquadra automaticamente.", "Il confine ufficiale viene evidenziato sulla mappa. Se Centra e zooma quando seleziono un oggetto e attivo nelle Impostazioni, la mappa lo inquadra automaticamente.",
"Se la particella e gia presente tra disegni, progetti o file GeoJSON, KML e KMZ, l'app riconosce il riferimento catastale o la geometria e riutilizza l'oggetto esistente senza duplicarlo.", "Se la particella e gia presente tra disegni, progetti o file GeoJSON, KML e KMZ, l'app riconosce il riferimento catastale o la geometria e riutilizza l'oggetto esistente senza duplicarlo.",
"Se un oggetto gia presente era nascosto, viene reso nuovamente visibile. La visibilita generale dei contorni rossi e dei dati importati resta controllabile dal pannello Layer.", "Se un oggetto gia presente era nascosto, viene reso nuovamente visibile. La visibilita generale dei contorni evidenziati e dei dati importati resta controllabile dal pannello Layer.",
"Quando il servizio ufficiale non restituisce subito il confine, attendi il completamento indicato nel pannello e riprova mantenendo gli stessi dati selezionati." "Quando il servizio ufficiale non restituisce subito il confine, attendi il completamento indicato nel pannello e riprova mantenendo gli stessi dati selezionati."
], ],
"data" => "data" =>
[ [
"Importazione: premi Carica KML, KMZ o GeoJSON e scegli il file dal dispositivo. I nomi e gli attributi riconosciuti vengono mantenuti.", "Importazione: premi Carica KML, KMZ o GeoJSON e scegli il file dal dispositivo. I nomi e gli attributi riconosciuti vengono mantenuti.",
"Per KML e KMZ, Includi anche il layer del foglio importa pure cornici e riquadri generali; disattivalo quando vuoi conservare soltanto le particelle riconosciute.", "Per KML e KMZ, Includi anche il layer del foglio conserva le cornici presenti nel file. Mostra cornice/layer del foglio recupera inoltre dal servizio ufficiale una cornice distinta per ciascun foglio delle particelle, senza creare un unico riquadro tra fogli lontani.",
"Usa Mostra dati importati e Mostra cornice per controllare separatamente la visibilita. Inquadra dati porta la mappa sull'estensione completa del file.", "Usa Mostra dati importati e Mostra cornice per controllare separatamente la visibilita. Inquadra dati porta la mappa sull'estensione completa del file.",
"Disegno: premi Mostra strumenti sulla mappa, torna alla mappa e scegli linea, poligono, rettangolo, cerchio o POI nella barra Leaflet.", "Disegno: premi Mostra strumenti sulla mappa, torna alla mappa e scegli linea, poligono, rettangolo, cerchio o POI nella barra Leaflet.",
"Modifica ed eliminazione possono agire sull'oggetto selezionato o su tutti i disegni. Prima seleziona sulla mappa la linea o il poligono interessato, poi scegli l'ambito dal piccolo comando accanto alla matita o al cestino.", "Modifica ed eliminazione possono agire sull'oggetto selezionato o su tutti i disegni. Prima seleziona sulla mappa la linea o il poligono interessato, poi scegli l'ambito dal piccolo comando accanto alla matita o al cestino.",
@@ -76,18 +77,19 @@
], ],
"projects" => "projects" =>
[ [
"Nuovo progetto: inserisci un nome, scegli se includere i contorni catastali rossi e premi Salva progetto. Vengono conservati oggetti, gruppi, nomi, attributi e opzioni di visualizzazione.", "Nuovo progetto: inserisci un nome, scegli se includere i contorni catastali evidenziati e premi Salva progetto. Vengono conservati oggetti, gruppi, nomi, attributi e opzioni di visualizzazione.",
"Aggiornamento: dopo aver aperto un progetto, usa di nuovo Salva progetto con lo stesso nome per aggiornarlo. Se nelle Impostazioni attivi Aggiorna automaticamente il progetto aperto, le modifiche vengono registrate dopo 3 secondi di inattivita.", "Aggiornamento: dopo aver aperto un progetto, usa di nuovo Salva progetto con lo stesso nome per aggiornarlo. Se nelle Impostazioni attivi Aggiorna automaticamente il progetto aperto, le modifiche vengono registrate dopo 3 secondi di inattivita.",
"Cartelle: seleziona un progetto, scrivi per esempio Cantieri 2026 e premi Sposta per organizzarlo nell'archivio; questa operazione non sposta le geometrie sulla mappa.", "Cartelle: seleziona un progetto, scrivi per esempio Cantieri 2026 e premi Sposta per organizzarlo nell'archivio; questa operazione non sposta le geometrie sulla mappa.",
"Duplica crea una copia modificabile, utile prima di una variante importante o quando ricevi un progetto in sola lettura.", "Rinomina cambia il nome del progetto selezionato senza alterarne contenuti e revisioni. Duplica crea invece una copia modificabile, utile prima di una variante importante o quando ricevi un progetto in sola lettura.",
"Archivia nasconde logicamente i lavori conclusi senza eliminarli; Ripristina li riporta tra quelli attivi. Elimina rimuove invece il progetto dall'archivio.", "Archivia nasconde logicamente i lavori conclusi senza eliminarli; Ripristina li riporta tra quelli attivi. Elimina rimuove invece il progetto dall'archivio.",
"Condividi modificabile consente al destinatario di continuare il lavoro; Condividi in sola lettura protegge l'originale e richiede una duplicazione per modificarlo.", "Condividi modificabile consente al destinatario di continuare il lavoro; Condividi in sola lettura protegge l'originale e richiede una duplicazione per modificarlo.",
"Revisioni: seleziona una data e usa Apri revisione per consultarne lo stato oppure Confronta per vedere le differenze con la versione corrente.", "Revisioni: la prima viene creata quando salvi per la seconda volta un progetto gia esistente. L'elenco si aggiorna anche dopo i salvataggi automatici; seleziona una data e usa Apri revisione oppure Confronta.",
"Backup: Crea backup raccoglie tutti i progetti in un file trasferibile. Ripristina backup ricarica un archivio completo; Importa progetto aggiunge invece un singolo progetto condiviso." "Backup: Crea backup raccoglie tutti i progetti in un file trasferibile. Ripristina backup ricarica un archivio completo; Importa progetto aggiunge invece un singolo progetto condiviso."
], ],
"tools" => "tools" =>
[ [
"Tabella oggetti: apre una vista ordinata di particelle, file importati e disegni. Usa i flag per selezionare piu righe e il lucchetto per proteggerle dalle modifiche.", "Tabella oggetti: apre una vista ordinata di particelle, file importati e disegni. Usa i flag per selezionare piu righe, il lucchetto per proteggerle e la matita per modificare i metadati.",
"Copia metadati: nella maschera Metadati oggetto scegli Copia da e l'oggetto sorgente. Attiva Importa anche i valori per copiare nomi e contenuti; disattivalo per creare soltanto gli stessi campi, lasciandoli vuoti o mantenendo i valori gia presenti.",
"Coordinate WGS84 e UTM: scegli un punto sulla mappa per leggere latitudine e longitudine oppure le coordinate metriche UTM, utili per rilievi e confronti tecnici.", "Coordinate WGS84 e UTM: scegli un punto sulla mappa per leggere latitudine e longitudine oppure le coordinate metriche UTM, utili per rilievi e confronti tecnici.",
"Registro operazioni: mostra in ordine cronologico disegni, modifiche, rinomine, spostamenti ed eliminazioni, cosi puoi capire cosa e cambiato durante la sessione.", "Registro operazioni: mostra in ordine cronologico disegni, modifiche, rinomine, spostamenti ed eliminazioni, cosi puoi capire cosa e cambiato durante la sessione.",
"Cestino: Ripristina ultima rimozione recupera l'elemento eliminato piu recente. Svuota cestino elimina definitivamente tutti gli elementi rimossi e non consente ulteriori recuperi.", "Cestino: Ripristina ultima rimozione recupera l'elemento eliminato piu recente. Svuota cestino elimina definitivamente tutti gli elementi rimossi e non consente ulteriori recuperi.",
+168 -9
View File
@@ -10,6 +10,7 @@
@inject MapExportService MapExportService @inject MapExportService MapExportService
@inject CloudSyncService CloudSyncService @inject CloudSyncService CloudSyncService
@inject AppUpdateService AppUpdateService @inject AppUpdateService AppUpdateService
@inject IncomingFileService IncomingFiles
@implements IAsyncDisposable @implements IAsyncDisposable
<PageTitle>LME Mappe Catastali</PageTitle> <PageTitle>LME Mappe Catastali</PageTitle>
@@ -81,7 +82,7 @@
<input type="checkbox" @bind="ShowSelectedParcels" @bind:after="ApplySelectedParcelsVisibility" /> <input type="checkbox" @bind="ShowSelectedParcels" @bind:after="ApplySelectedParcelsVisibility" />
<span> <span>
<strong>Particelle catastali evidenziate</strong> <strong>Particelle catastali evidenziate</strong>
<small>Contorni rossi ottenuti da ricerca o GPS</small> <small>Contorni ottenuti da ricerca o GPS</small>
</span> </span>
</label> </label>
<label class="map-layer-option"> <label class="map-layer-option">
@@ -219,7 +220,7 @@
<input type="checkbox" @bind="ShowImportedSheetLayer" @bind:after="ApplyImportedSheetLayerVisibility" /> <input type="checkbox" @bind="ShowImportedSheetLayer" @bind:after="ApplyImportedSheetLayerVisibility" />
<span>Mostra cornice/layer del foglio importato</span> <span>Mostra cornice/layer del foglio importato</span>
</label> </label>
<small class="field-help">La cornice grande resta separata dalle particelle e puo essere nascosta anche nei progetti salvati.</small> <small class="field-help">Carica dal servizio ufficiale una cornice distinta per ogni foglio delle particelle; le cornici restano separate, trasferibili e salvabili nel progetto.</small>
<label class="toggle-line project-save-option"> <label class="toggle-line project-save-option">
<input type="checkbox" @bind="ShowImportedMeasurements" @bind:after="ApplyImportedMeasurementsVisibility" /> <input type="checkbox" @bind="ShowImportedMeasurements" @bind:after="ApplyImportedMeasurementsVisibility" />
<span>Mostra misure dei file caricati</span> <span>Mostra misure dei file caricati</span>
@@ -292,7 +293,7 @@
</label> </label>
<label class="toggle-line project-save-option"> <label class="toggle-line project-save-option">
<input type="checkbox" @bind="ExportCadastral" @bind:after="SaveFlagPreferences" /> <input type="checkbox" @bind="ExportCadastral" @bind:after="SaveFlagPreferences" />
<span>Particelle catastali rosse e GPS</span> <span>Particelle catastali evidenziate e GPS</span>
</label> </label>
<label class="toggle-line project-save-option"> <label class="toggle-line project-save-option">
<input type="checkbox" @bind="ExportDrawings" @bind:after="SaveFlagPreferences" /> <input type="checkbox" @bind="ExportDrawings" @bind:after="SaveFlagPreferences" />
@@ -327,7 +328,7 @@
</label> </label>
<label class="toggle-line project-save-option"> <label class="toggle-line project-save-option">
<input type="checkbox" @bind="IncludeCadastralParcels" @bind:after="SaveFlagPreferences" /> <input type="checkbox" @bind="IncludeCadastralParcels" @bind:after="SaveFlagPreferences" />
<span>Includi le particelle catastali rosse</span> <span>Includi le particelle catastali evidenziate</span>
</label> </label>
<button class="primary-command" @onclick="SaveProject" disabled="@(ProjectBusy || string.IsNullOrWhiteSpace(NewProjectName))">Salva progetto</button> <button class="primary-command" @onclick="SaveProject" disabled="@(ProjectBusy || string.IsNullOrWhiteSpace(NewProjectName))">Salva progetto</button>
</section> </section>
@@ -354,6 +355,7 @@
</label> </label>
<div class="project-command-stack"> <div class="project-command-stack">
<button class="secondary-command" @onclick="UpdateProjectFolder" disabled="@(ProjectBusy || string.IsNullOrWhiteSpace(SelectedProjectId))">Sposta</button> <button class="secondary-command" @onclick="UpdateProjectFolder" disabled="@(ProjectBusy || string.IsNullOrWhiteSpace(SelectedProjectId))">Sposta</button>
<button class="secondary-command" @onclick="RenameProject" disabled="@(ProjectBusy || string.IsNullOrWhiteSpace(SelectedProjectId) || SelectedProject?.IsReadOnly == true)">Rinomina</button>
<button class="secondary-command" @onclick="DuplicateProject" disabled="@(ProjectBusy || string.IsNullOrWhiteSpace(SelectedProjectId))">Duplica</button> <button class="secondary-command" @onclick="DuplicateProject" disabled="@(ProjectBusy || string.IsNullOrWhiteSpace(SelectedProjectId))">Duplica</button>
<button class="secondary-command" @onclick="ToggleProjectArchive" disabled="@(ProjectBusy || string.IsNullOrWhiteSpace(SelectedProjectId))">@(SelectedProject?.IsArchived == true ? "Ripristina" : "Archivia")</button> <button class="secondary-command" @onclick="ToggleProjectArchive" disabled="@(ProjectBusy || string.IsNullOrWhiteSpace(SelectedProjectId))">@(SelectedProject?.IsArchived == true ? "Ripristina" : "Archivia")</button>
<button class="secondary-command" @onclick='() => ShareProject(false)' disabled="@(ProjectBusy || string.IsNullOrWhiteSpace(SelectedProjectId))">Condividi modificabile</button> <button class="secondary-command" @onclick='() => ShareProject(false)' disabled="@(ProjectBusy || string.IsNullOrWhiteSpace(SelectedProjectId))">Condividi modificabile</button>
@@ -373,6 +375,14 @@
} }
</select> </select>
</label> </label>
@if (!string.IsNullOrWhiteSpace(SelectedProjectId) && ProjectVersions.Count == 0)
{
<small class="field-help">Non ci sono ancora revisioni: la prima viene creata quando salvi nuovamente un progetto già esistente.</small>
}
else if (ProjectVersions.Count > 0)
{
<small class="field-help">@ProjectVersions.Count revisioni disponibili, ordinate dalla più recente.</small>
}
<div class="button-row"> <div class="button-row">
<button class="secondary-command" @onclick="LoadProjectVersion" disabled="@(string.IsNullOrWhiteSpace(SelectedVersionId))">Apri revisione</button> <button class="secondary-command" @onclick="LoadProjectVersion" disabled="@(string.IsNullOrWhiteSpace(SelectedVersionId))">Apri revisione</button>
<button class="secondary-command" @onclick="CompareProjectVersion" disabled="@(string.IsNullOrWhiteSpace(SelectedVersionId))">Confronta</button> <button class="secondary-command" @onclick="CompareProjectVersion" disabled="@(string.IsNullOrWhiteSpace(SelectedVersionId))">Confronta</button>
@@ -688,6 +698,7 @@
private bool SyncBusy { get; set; } private bool SyncBusy { get; set; }
private string SyncStatus { get; set; } = "Sincronizzazione non configurata."; private string SyncStatus { get; set; } = "Sincronizzazione non configurata.";
private bool UpdateBusy { get; set; } private bool UpdateBusy { get; set; }
private bool MapReady { get; set; }
private string UpdateStatus { get; set; } = $"Versione installata: {AppUpdateService.CurrentVersion}"; private string UpdateStatus { get; set; } = $"Versione installata: {AppUpdateService.CurrentVersion}";
private string UpdateDownloadUrl { get; set; } = string.Empty; private string UpdateDownloadUrl { get; set; } = string.Empty;
private string UpdateReleaseNotes { get; set; } = string.Empty; private string UpdateReleaseNotes { get; set; } = string.Empty;
@@ -745,6 +756,7 @@
protected override async Task OnInitializedAsync() protected override async Task OnInitializedAsync()
{ {
IncomingFiles.FileAvailable += OnIncomingFileAvailable;
LoadFlagPreferences(); LoadFlagPreferences();
try try
@@ -788,12 +800,14 @@
{ {
MapCallbackReference = DotNetObjectReference.Create(this); MapCallbackReference = DotNetObjectReference.Create(this);
await JS.InvokeVoidAsync("lmeMap.init", MapCallbackReference); await JS.InvokeVoidAsync("lmeMap.init", MapCallbackReference);
MapReady = true;
await ApplyFlagPreferencesToMapAsync(); await ApplyFlagPreferencesToMapAsync();
await ApplyAdvancedOptions(); await ApplyAdvancedOptions();
await CenterOnInitialLocationAsync(); await CenterOnInitialLocationAsync();
await MigrateLegacyProjectAsync(); await MigrateLegacyProjectAsync();
var offlineCount = await JS.InvokeAsync<int>("lmeMap.getOfflineTileStats"); var offlineCount = await JS.InvokeAsync<int>("lmeMap.getOfflineTileStats");
OfflineStatus = offlineCount == 0 ? "Nessuna tessera salvata." : $"{offlineCount} tessere disponibili offline."; OfflineStatus = offlineCount == 0 ? "Nessuna tessera salvata." : $"{offlineCount} tessere disponibili offline.";
await ProcessIncomingFilesAsync();
await InvokeAsync(StateHasChanged); await InvokeAsync(StateHasChanged);
} }
} }
@@ -904,6 +918,7 @@
await JS.InvokeVoidAsync("lmeMap.clearLegacyProjectSnapshot"); await JS.InvokeVoidAsync("lmeMap.clearLegacyProjectSnapshot");
await RefreshProjectsAsync(); await RefreshProjectsAsync();
SelectedProjectId = migrated.Id; SelectedProjectId = migrated.Id;
await RefreshProjectVersionsAsync(true);
await InvokeAsync(StateHasChanged); await InvokeAsync(StateHasChanged);
} }
catch catch
@@ -1298,6 +1313,10 @@
return InvokeAsync(StateHasChanged); return InvokeAsync(StateHasChanged);
} }
[JSInvokable]
public Task<string> GetOfficialCadastralSheetsNear(double latitude, double longitude) =>
OfficialCadastreService.GetSheetsNearAsync(latitude, longitude);
[JSInvokable] [JSInvokable]
public Task OnMapChanged(string action) public Task OnMapChanged(string action)
{ {
@@ -1361,6 +1380,7 @@
{ {
SelectedProjectId = string.Empty; SelectedProjectId = string.Empty;
} }
await RefreshProjectVersionsAsync();
ProjectArchiveMessage = Projects.Count == 0 ProjectArchiveMessage = Projects.Count == 0
? "Nessun progetto salvato." ? "Nessun progetto salvato."
: $"{Projects.Count} {(Projects.Count == 1 ? "progetto salvato" : "progetti salvati")} nell'archivio interno."; : $"{Projects.Count} {(Projects.Count == 1 ? "progetto salvato" : "progetti salvati")} nell'archivio interno.";
@@ -1375,10 +1395,18 @@
{ {
SelectedProjectId = args.Value?.ToString() ?? string.Empty; SelectedProjectId = args.Value?.ToString() ?? string.Empty;
ProjectFolder = SelectedProject?.Folder ?? string.Empty; ProjectFolder = SelectedProject?.Folder ?? string.Empty;
SelectedVersionId = string.Empty; await RefreshProjectVersionsAsync(true);
}
private async Task RefreshProjectVersionsAsync(bool resetSelection = false)
{
ProjectVersions = string.IsNullOrWhiteSpace(SelectedProjectId) ProjectVersions = string.IsNullOrWhiteSpace(SelectedProjectId)
? [] ? []
: await ProjectStorageService.GetVersionsAsync(SelectedProjectId); : await ProjectStorageService.GetVersionsAsync(SelectedProjectId);
if (resetSelection || ProjectVersions.All(version => version.Id != SelectedVersionId))
{
SelectedVersionId = string.Empty;
}
} }
private Task UndoMapChange() => JS.InvokeVoidAsync("lmeMap.undoMapChange").AsTask(); private Task UndoMapChange() => JS.InvokeVoidAsync("lmeMap.undoMapChange").AsTask();
@@ -1400,9 +1428,44 @@
await RefreshProjectsAsync(); await RefreshProjectsAsync();
SelectedProjectId = copy.Id; SelectedProjectId = copy.Id;
ProjectFolder = copy.Folder; ProjectFolder = copy.Folder;
await RefreshProjectVersionsAsync(true);
await JS.InvokeVoidAsync("lmeMap.showInfo", $"Progetto duplicato: {copy.Name}."); await JS.InvokeVoidAsync("lmeMap.showInfo", $"Progetto duplicato: {copy.Name}.");
} }
private async Task RenameProject()
{
if (SelectedProject is not { } project) return;
var requestedName = await JS.InvokeAsync<string?>("lmeMap.promptProjectName", project.Name);
if (string.IsNullOrWhiteSpace(requestedName)
|| string.Equals(requestedName.Trim(), project.Name, StringComparison.CurrentCulture))
{
return;
}
ProjectBusy = true;
try
{
var renamed = await ProjectStorageService.RenameAsync(project.Id, requestedName);
await RefreshProjectsAsync();
SelectedProjectId = renamed.Id;
await RefreshProjectVersionsAsync();
NewProjectName = renamed.Name;
if (!HasUnsavedChanges)
{
ExportFileName = renamed.Name;
}
await JS.InvokeVoidAsync("lmeMap.showInfo", $"Progetto rinominato: {renamed.Name}.");
}
catch (Exception error)
{
await JS.InvokeVoidAsync("lmeMap.showInfo", $"Progetto non rinominato: {error.GetBaseException().Message}");
}
finally
{
ProjectBusy = false;
}
}
private async Task UpdateProjectFolder() private async Task UpdateProjectFolder()
{ {
if (SelectedProject is null) return; if (SelectedProject is null) return;
@@ -1434,7 +1497,11 @@
private async Task RestoreBackup() private async Task RestoreBackup()
{ {
var file = await FilePicker.Default.PickAsync(new PickOptions { PickerTitle = "Scegli backup LME" }); var file = await FilePicker.Default.PickAsync(new PickOptions
{
PickerTitle = "Scegli backup LME (.lmebackup.zip)",
FileTypes = BackupPickerFileTypes
});
if (file is null) return; if (file is null) return;
var path = await CopyPickedFileToCacheAsync(file); var path = await CopyPickedFileToCacheAsync(file);
var count = await ProjectStorageService.RestoreBackupAsync(path); var count = await ProjectStorageService.RestoreBackupAsync(path);
@@ -1444,12 +1511,17 @@
private async Task ImportProject() private async Task ImportProject()
{ {
var file = await FilePicker.Default.PickAsync(new PickOptions { PickerTitle = "Scegli progetto LME" }); var file = await FilePicker.Default.PickAsync(new PickOptions
{
PickerTitle = "Scegli progetto LME (.lmeproject.json)",
FileTypes = ProjectPickerFileTypes
});
if (file is null) return; if (file is null) return;
var path = await CopyPickedFileToCacheAsync(file); var path = await CopyPickedFileToCacheAsync(file);
var imported = await ProjectStorageService.ImportProjectAsync(path); var imported = await ProjectStorageService.ImportProjectAsync(path);
await RefreshProjectsAsync(); await RefreshProjectsAsync();
SelectedProjectId = imported.Id; SelectedProjectId = imported.Id;
await RefreshProjectVersionsAsync(true);
await JS.InvokeVoidAsync("lmeMap.showInfo", $"Progetto importato: {imported.Name}."); await JS.InvokeVoidAsync("lmeMap.showInfo", $"Progetto importato: {imported.Name}.");
} }
@@ -1462,6 +1534,91 @@
return path; return path;
} }
private void OnIncomingFileAvailable()
{
if (MapReady) _ = InvokeAsync(ProcessIncomingFilesAsync);
}
private async Task ProcessIncomingFilesAsync()
{
while (IncomingFiles.TryDequeue(out var incoming) && incoming is not null)
{
try
{
var lowerName = incoming.FileName.ToLowerInvariant();
if (lowerName.EndsWith(".kml", StringComparison.Ordinal)
|| lowerName.EndsWith(".kmz", StringComparison.Ordinal)
|| lowerName.EndsWith(".geojson", StringComparison.Ordinal)
|| await IsGeoJsonAsync(incoming.Path))
{
var content = Convert.ToBase64String(await File.ReadAllBytesAsync(incoming.Path));
await JS.InvokeAsync<string>("lmeMap.importExternalGisFile", incoming.FileName, content, incoming.ContentType);
continue;
}
if (lowerName.EndsWith(".zip", StringComparison.Ordinal))
{
var count = await ProjectStorageService.RestoreBackupAsync(incoming.Path);
await RefreshProjectsAsync();
await JS.InvokeVoidAsync("lmeMap.showInfo", $"Backup aperto: {count} progetti ripristinati.");
continue;
}
if (lowerName.EndsWith(".json", StringComparison.Ordinal))
{
var imported = await ProjectStorageService.ImportProjectAsync(incoming.Path);
await RefreshProjectsAsync();
SelectedProjectId = imported.Id;
await RefreshProjectVersionsAsync(true);
await JS.InvokeVoidAsync("lmeMap.showInfo", $"Progetto aperto: {imported.Name}.");
continue;
}
await JS.InvokeVoidAsync("lmeMap.showInfo", $"Formato non riconosciuto: {incoming.FileName}.");
}
catch (Exception error)
{
await JS.InvokeVoidAsync("lmeMap.showInfo", $"Impossibile aprire {incoming.FileName}: {error.GetBaseException().Message}");
}
finally
{
try { File.Delete(incoming.Path); } catch { }
}
}
}
private static async Task<bool> IsGeoJsonAsync(string path)
{
if (!Path.GetExtension(path).Equals(".json", StringComparison.OrdinalIgnoreCase)) return false;
try
{
await using var stream = File.OpenRead(path);
using var document = await System.Text.Json.JsonDocument.ParseAsync(stream);
if (!document.RootElement.TryGetProperty("type", out var typeProperty)) return false;
var type = typeProperty.GetString();
return type is "Feature" or "FeatureCollection" or "Point" or "MultiPoint"
or "LineString" or "MultiLineString" or "Polygon" or "MultiPolygon"
or "GeometryCollection";
}
catch { return false; }
}
private static readonly FilePickerFileType ProjectPickerFileTypes = new(new Dictionary<DevicePlatform, IEnumerable<string>>
{
[DevicePlatform.Android] = ["application/json", "text/json", "text/plain", "application/octet-stream"],
[DevicePlatform.WinUI] = [".json"],
[DevicePlatform.iOS] = ["public.json", "public.data"],
[DevicePlatform.macOS] = ["public.json", "public.data"]
});
private static readonly FilePickerFileType BackupPickerFileTypes = new(new Dictionary<DevicePlatform, IEnumerable<string>>
{
[DevicePlatform.Android] = ["application/zip", "application/x-zip-compressed", "application/octet-stream"],
[DevicePlatform.WinUI] = [".zip"],
[DevicePlatform.iOS] = ["public.zip-archive", "public.data"],
[DevicePlatform.macOS] = ["public.zip-archive", "public.data"]
});
private async Task LoadProjectVersion() private async Task LoadProjectVersion()
{ {
if (SelectedProject is null || string.IsNullOrWhiteSpace(SelectedVersionId)) return; if (SelectedProject is null || string.IsNullOrWhiteSpace(SelectedVersionId)) return;
@@ -1550,6 +1707,7 @@
existing?.Id); existing?.Id);
await RefreshProjectsAsync(); await RefreshProjectsAsync();
SelectedProjectId = saved.Id; SelectedProjectId = saved.Id;
await RefreshProjectVersionsAsync();
NewProjectName = saved.Name; NewProjectName = saved.Name;
await JS.InvokeVoidAsync("lmeMap.setProjectReadOnly", false); await JS.InvokeVoidAsync("lmeMap.setProjectReadOnly", false);
await JS.InvokeVoidAsync("lmeMap.markProjectSaved"); await JS.InvokeVoidAsync("lmeMap.markProjectSaved");
@@ -1558,8 +1716,8 @@
await JS.InvokeVoidAsync( await JS.InvokeVoidAsync(
"lmeMap.showInfo", "lmeMap.showInfo",
IncludeCadastralParcels IncludeCadastralParcels
? $"Progetto salvato: {saved.Name}, incluse le particelle rosse." ? $"Progetto salvato: {saved.Name}, incluse le particelle catastali evidenziate."
: $"Progetto salvato: {saved.Name}, senza particelle rosse."); : $"Progetto salvato: {saved.Name}, senza particelle catastali evidenziate.");
} }
catch (Exception error) catch (Exception error)
{ {
@@ -2061,6 +2219,7 @@
public ValueTask DisposeAsync() public ValueTask DisposeAsync()
{ {
IncomingFiles.FileAvailable -= OnIncomingFileAvailable;
CancelCatalogWork(); CancelCatalogWork();
LocationService.StopTracking(); LocationService.StopTracking();
GpsLookupCancellation?.Cancel(); GpsLookupCancellation?.Cancel();
+13 -5
View File
@@ -1,8 +1,8 @@
<Project Sdk="Microsoft.NET.Sdk.Razor"> <Project Sdk="Microsoft.NET.Sdk.Razor">
<PropertyGroup> <PropertyGroup>
<TargetFrameworks>net9.0-android;net9.0-ios;net9.0-maccatalyst</TargetFrameworks> <TargetFrameworks>net10.0-android;net10.0-ios;net10.0-maccatalyst</TargetFrameworks>
<TargetFrameworks Condition="$([MSBuild]::IsOSPlatform('windows'))">$(TargetFrameworks);net9.0-windows10.0.19041.0</TargetFrameworks> <TargetFrameworks Condition="$([MSBuild]::IsOSPlatform('windows'))">$(TargetFrameworks);net10.0-windows10.0.19041.0</TargetFrameworks>
<!-- Uncomment to also build the tizen app. You will need to install tizen by following this: https://github.com/Samsung/Tizen.NET --> <!-- Uncomment to also build the tizen app. You will need to install tizen by following this: https://github.com/Samsung/Tizen.NET -->
<!-- <TargetFrameworks>$(TargetFrameworks);net9.0-tizen</TargetFrameworks> --> <!-- <TargetFrameworks>$(TargetFrameworks);net9.0-tizen</TargetFrameworks> -->
@@ -28,8 +28,8 @@
<ApplicationId>com.companyname.lmemappecatastaliapp</ApplicationId> <ApplicationId>com.companyname.lmemappecatastaliapp</ApplicationId>
<!-- Versions --> <!-- Versions -->
<ApplicationDisplayVersion>0.4.3</ApplicationDisplayVersion> <ApplicationDisplayVersion>0.4.9</ApplicationDisplayVersion>
<ApplicationVersion>38</ApplicationVersion> <ApplicationVersion>44</ApplicationVersion>
<Version>$(ApplicationDisplayVersion)</Version> <Version>$(ApplicationDisplayVersion)</Version>
<!-- To develop, package, and publish an app to the Microsoft Store, see: https://aka.ms/MauiTemplateUnpackaged --> <!-- To develop, package, and publish an app to the Microsoft Store, see: https://aka.ms/MauiTemplateUnpackaged -->
@@ -43,6 +43,14 @@
<SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'tizen'">6.5</SupportedOSPlatformVersion> <SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'tizen'">6.5</SupportedOSPlatformVersion>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)' == 'Release' and $([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'android'">
<AndroidTargetSdkVersion>36</AndroidTargetSdkVersion>
<AndroidPackageFormat>aab</AndroidPackageFormat>
<AndroidUseAapt2>true</AndroidUseAapt2>
<AndroidCreatePackagePerAbi>false</AndroidCreatePackagePerAbi>
<RunAOTCompilation>true</RunAOTCompilation>
</PropertyGroup>
<ItemGroup> <ItemGroup>
<!-- App Icon --> <!-- App Icon -->
<MauiIcon Include="Resources\AppIcon\appicon.svg" ForegroundFile="Resources\AppIcon\appiconfg.svg" Color="#075E54" /> <MauiIcon Include="Resources\AppIcon\appicon.svg" ForegroundFile="Resources\AppIcon\appiconfg.svg" Color="#075E54" />
@@ -64,7 +72,7 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.Maui.Controls" Version="$(MauiVersion)" /> <PackageReference Include="Microsoft.Maui.Controls" Version="$(MauiVersion)" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebView.Maui" Version="$(MauiVersion)" /> <PackageReference Include="Microsoft.AspNetCore.Components.WebView.Maui" Version="$(MauiVersion)" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="9.0.9" /> <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="10.0.12" />
<PackageReference Include="Parquet.Net" Version="6.1.0" /> <PackageReference Include="Parquet.Net" Version="6.1.0" />
</ItemGroup> </ItemGroup>
+1
View File
@@ -26,6 +26,7 @@ public static class MauiProgram
builder.Services.AddSingleton<MapExportService>(); builder.Services.AddSingleton<MapExportService>();
builder.Services.AddSingleton<CloudSyncService>(); builder.Services.AddSingleton<CloudSyncService>();
builder.Services.AddSingleton<AppUpdateService>(); builder.Services.AddSingleton<AppUpdateService>();
builder.Services.AddSingleton(IncomingFileService.Shared);
#if DEBUG #if DEBUG
builder.Services.AddBlazorWebViewDeveloperTools(); builder.Services.AddBlazorWebViewDeveloperTools();
+67 -2
View File
@@ -1,10 +1,75 @@
using Android.App; using Android.App;
using Android.Content;
using Android.Content.PM; using Android.Content.PM;
using Android.Database;
using Android.OS; using Android.OS;
using Android.Provider;
using LMEMappeCatastaliApp.Services;
namespace LMEMappeCatastaliApp; namespace LMEMappeCatastaliApp;
[Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)] [Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, LaunchMode = LaunchMode.SingleTop, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)]
[IntentFilter([Intent.ActionView], Categories = [Intent.CategoryDefault, Intent.CategoryBrowsable], DataMimeType = "application/json")]
[IntentFilter([Intent.ActionView], Categories = [Intent.CategoryDefault, Intent.CategoryBrowsable], DataMimeType = "application/geo+json")]
[IntentFilter([Intent.ActionView], Categories = [Intent.CategoryDefault, Intent.CategoryBrowsable], DataMimeType = "application/geojson")]
[IntentFilter([Intent.ActionView], Categories = [Intent.CategoryDefault, Intent.CategoryBrowsable], DataMimeType = "application/vnd.google-earth.kml+xml")]
[IntentFilter([Intent.ActionView], Categories = [Intent.CategoryDefault, Intent.CategoryBrowsable], DataMimeType = "application/vnd.google-earth.kmz")]
[IntentFilter([Intent.ActionView], Categories = [Intent.CategoryDefault, Intent.CategoryBrowsable], DataMimeType = "application/xml")]
[IntentFilter([Intent.ActionView], Categories = [Intent.CategoryDefault, Intent.CategoryBrowsable], DataMimeType = "text/xml")]
[IntentFilter([Intent.ActionView], Categories = [Intent.CategoryDefault, Intent.CategoryBrowsable], DataMimeType = "application/zip")]
[IntentFilter([Intent.ActionView], Categories = [Intent.CategoryDefault, Intent.CategoryBrowsable], DataMimeType = "application/x-zip-compressed")]
[IntentFilter([Intent.ActionView], Categories = [Intent.CategoryDefault, Intent.CategoryBrowsable], DataMimeType = "application/octet-stream")]
public class MainActivity : MauiAppCompatActivity public class MainActivity : MauiAppCompatActivity
{ {
protected override void OnCreate(Bundle? savedInstanceState)
{
base.OnCreate(savedInstanceState);
QueueViewedFile(Intent);
}
protected override void OnNewIntent(Intent? intent)
{
base.OnNewIntent(intent);
Intent = intent;
QueueViewedFile(intent);
}
private void QueueViewedFile(Intent? intent)
{
if (intent?.Action == Android.Content.Intent.ActionView && intent.Data is not null)
{
_ = CopyViewedFileAsync(intent);
}
}
private async Task CopyViewedFileAsync(Intent intent)
{
try
{
var uri = intent.Data!;
var fileName = ReadDisplayName(uri) ?? $"file-{Guid.NewGuid():N}";
fileName = string.Concat(fileName.Select(character => Path.GetInvalidFileNameChars().Contains(character) ? '_' : character));
var directory = Path.Combine(FileSystem.CacheDirectory, "Incoming");
Directory.CreateDirectory(directory);
var path = Path.Combine(directory, $"{Guid.NewGuid():N}-{fileName}");
await using var input = ContentResolver!.OpenInputStream(uri)
?? throw new IOException("Impossibile leggere il file selezionato.");
await using var output = File.Create(path);
await input.CopyToAsync(output);
IncomingFileService.Shared.Enqueue(new IncomingFile(path, fileName, intent.Type));
}
catch (Exception error)
{
System.Diagnostics.Debug.WriteLine($"Apertura file LME non riuscita: {error}");
}
}
private string? ReadDisplayName(Android.Net.Uri uri)
{
if (uri.Scheme == ContentResolver.SchemeFile) return Path.GetFileName(uri.Path);
using ICursor? cursor = ContentResolver?.Query(uri, [IOpenableColumns.DisplayName], null, null, null);
if (cursor is null || !cursor.MoveToFirst()) return null;
var index = cursor.GetColumnIndex(IOpenableColumns.DisplayName);
return index >= 0 ? cursor.GetString(index) : null;
}
} }
+42
View File
@@ -2,6 +2,48 @@
App .NET MAUI Blazor Hybrid per Android, iOS, Mac Catalyst e Windows, pensata per consultare mappe catastali e lavorare sul campo con GPS. App .NET MAUI Blazor Hybrid per Android, iOS, Mac Catalyst e Windows, pensata per consultare mappe catastali e lavorare sul campo con GPS.
## Versione 0.4.9
- Linee e punti KML/KMZ vengono sempre importati, anche quando il documento viene riconosciuto come catastale; il filtro particelle separa soltanto i poligoni di foglio o cornice.
## Versione 0.4.8
- Aggiornamento a .NET 10 e target Android API 36.
- KML e KMZ generici conservano punti, linee e poligoni; il filtro particelle viene applicato soltanto ai file riconosciuti come catastali.
- Android propone LME tra le app disponibili per aprire KML, KMZ, GeoJSON, progetti JSON e backup ZIP.
- I selettori file Android mostrano correttamente progetti condivisi e backup con estensione composta.
## Versione 0.4.7
- La ricerca nel pannello Layer conserva correttamente posizione e selezione del cursore durante il filtraggio; digitando `pio` il testo non viene piu invertito in `oip`.
- L'elenco revisioni viene aggiornato dopo salvataggi manuali e automatici, rinomina, importazione e selezione del progetto.
- Il pannello Progetti mostra quante revisioni sono disponibili e spiega quando un progetto appena creato non possiede ancora versioni precedenti.
## Versione 0.4.6
- `Mostra cornice/layer del foglio` carica dal WFS ufficiale AdE il vero confine `CP:CadastralZoning` di ciascun foglio delle particelle.
- Le particelle appartenenti a fogli diversi producono cornici distinte, senza piu creare un unico rettangolo cumulativo tra aree lontane.
- Le cornici gia presenti nel progetto o trasferite in un altro gruppo vengono riconosciute e non vengono scaricate o duplicate.
- Ogni foglio e salvato come oggetto autonomo e puo essere rinominato, bloccato, rimosso o spostato in un altro gruppo dal pannello Layer.
- I vecchi riquadri cumulativi generati automaticamente vengono rimossi durante il caricamento e sostituiti dai fogli ufficiali.
## Versione 0.4.5
- Corretto il layout del pannello Layer sui telefoni e sui foldable: checkbox, lucchetto, ordinamento e freccia di espansione non si sovrappongono e restano allineati.
- La tabella oggetti include un comando dedicato per modificare i metadati di ciascun elemento.
- L'editor metadati permette di copiare i campi da un altro oggetto, scegliendo se importare anche i valori oppure soltanto i nomi.
- Il pannello Progetti consente di rinominare un progetto duplicato o esistente senza perdere contenuti, identita e revisioni.
- La barra Leaflet include una guida completa con istruzioni ed esempi concreti per disegno, modifica, eliminazione, riparazione, fori e confronto confini.
## Versione 0.4.4
- I comandi `Rinomina`, `Sposta nel gruppo` e `Rimuovi` occupano una riga completa e restano visibili anche nei pannelli Layer molto stretti.
- `Sposta nel gruppo` e disponibile per padri e figli di disegni, dati importati, cornici, fogli importati e particelle evidenziate dalla ricerca catastale.
- Editor distinti per linea e riempimento su gruppi e singoli oggetti, con contagocce dove supportato e valori modificabili HEX, RGB e HSL.
- Copia HEX per riutilizzare esattamente un colore su altri oggetti; stili conservati nei progetti e negli export.
- Rimossi dai menu i riferimenti al colore rosso fisso delle particelle catastali.
- Nei progetti in sola lettura anche il trasferimento tra gruppi viene correttamente disabilitato.
## Versione 0.4.3 ## Versione 0.4.3
- `Mostra particella sulla mappa` riattiva sempre il layer dei confini rossi e lo porta in primo piano. - `Mostra particella sulla mappa` riattiva sempre il layer dei confini rossi e lo porta in primo piano.
+20
View File
@@ -0,0 +1,20 @@
using System.Collections.Concurrent;
namespace LMEMappeCatastaliApp.Services;
public sealed class IncomingFileService
{
private readonly ConcurrentQueue<IncomingFile> _files = new();
public static IncomingFileService Shared { get; } = new();
public event Action? FileAvailable;
public void Enqueue(IncomingFile file)
{
_files.Enqueue(file);
MainThread.BeginInvokeOnMainThread(() => FileAvailable?.Invoke());
}
public bool TryDequeue(out IncomingFile? file) => _files.TryDequeue(out file);
}
public sealed record IncomingFile(string Path, string FileName, string? ContentType);
+1 -1
View File
@@ -85,7 +85,7 @@ public sealed class MapExportService
{ {
var root = new XElement("gpx", var root = new XElement("gpx",
new XAttribute("version", "1.1"), new XAttribute("version", "1.1"),
new XAttribute("creator", "LME Mappe Catastali 0.4.3"), new XAttribute("creator", "LME Mappe Catastali 0.4.7"),
new XAttribute(XNamespace.Xmlns + "xsi", "http://www.w3.org/2001/XMLSchema-instance"), new XAttribute(XNamespace.Xmlns + "xsi", "http://www.w3.org/2001/XMLSchema-instance"),
new XElement("metadata", new XElement("name", name))); new XElement("metadata", new XElement("name", name)));
foreach (var feature in features.EnumerateArray()) foreach (var feature in features.EnumerateArray())
+30 -2
View File
@@ -22,6 +22,34 @@ public sealed class OfficialCadastreService
double longitude, double longitude,
double radiusMeters, double radiusMeters,
CancellationToken cancellationToken = default) CancellationToken cancellationToken = default)
=> await GetFeaturesNearAsync(
latitude,
longitude,
radiusMeters,
"CP:CadastralParcel",
100,
cancellationToken);
public async Task<string> GetSheetsNearAsync(
double latitude,
double longitude,
double radiusMeters = 10,
CancellationToken cancellationToken = default)
=> await GetFeaturesNearAsync(
latitude,
longitude,
radiusMeters,
"CP:CadastralZoning",
20,
cancellationToken);
private async Task<string> GetFeaturesNearAsync(
double latitude,
double longitude,
double radiusMeters,
string typeName,
int count,
CancellationToken cancellationToken)
{ {
var meters = Math.Clamp(radiusMeters, 2, 30); var meters = Math.Clamp(radiusMeters, 2, 30);
var deltaLatitude = meters / 111_320d; var deltaLatitude = meters / 111_320d;
@@ -40,11 +68,11 @@ public sealed class OfficialCadastreService
["language"] = "ita", ["language"] = "ita",
["SERVICE"] = "WFS", ["SERVICE"] = "WFS",
["VERSION"] = "2.0.0", ["VERSION"] = "2.0.0",
["TYPENAMES"] = "CP:CadastralParcel", ["TYPENAMES"] = typeName,
["SRSNAME"] = "urn:ogc:def:crs:EPSG::6706", ["SRSNAME"] = "urn:ogc:def:crs:EPSG::6706",
["BBOX"] = bbox, ["BBOX"] = bbox,
["REQUEST"] = "GetFeature", ["REQUEST"] = "GetFeature",
["COUNT"] = "100" ["COUNT"] = count.ToString(CultureInfo.InvariantCulture)
}; };
var url = WfsEndpoint + "?" + string.Join("&", query.Select(item => var url = WfsEndpoint + "?" + string.Join("&", query.Select(item =>
+30
View File
@@ -147,6 +147,36 @@ public sealed class ProjectStorageService
finally { _gate.Release(); } finally { _gate.Release(); }
} }
public async Task<MapProjectSummary> RenameAsync(string projectId, string name)
{
var normalizedName = NormalizeName(name);
await _gate.WaitAsync();
try
{
var files = await ReadProjectFilesAsync();
var project = files.FirstOrDefault(item => item.Document.Id == projectId)
?? throw new FileNotFoundException("Il progetto selezionato non esiste piu'.");
if (project.Document.AccessMode == "readonly")
{
throw new InvalidOperationException("Il progetto e' in sola lettura. Duplicalo per modificarlo.");
}
if (files.Any(item => item.Document.Id != projectId
&& string.Equals(item.Document.Name, normalizedName, StringComparison.CurrentCultureIgnoreCase)))
{
throw new InvalidOperationException($"Esiste gia' un progetto chiamato '{normalizedName}'.");
}
project.Document.Name = normalizedName;
project.Document.UpdatedAt = DateTimeOffset.UtcNow;
await File.WriteAllTextAsync(
project.Path,
JsonSerializer.Serialize(project.Document, _jsonOptions),
new UTF8Encoding(false));
return project.Document.ToSummary();
}
finally { _gate.Release(); }
}
public async Task UpdateOrganizationAsync(string projectId, string? folder = null, bool? isArchived = null) public async Task UpdateOrganizationAsync(string projectId, string? folder = null, bool? isArchived = null)
{ {
await _gate.WaitAsync(); await _gate.WaitAsync();
+6
View File
@@ -0,0 +1,6 @@
{
"sdk": {
"version": "10.0.401",
"rollForward": "latestPatch"
}
}
+52
View File
@@ -0,0 +1,52 @@
param([string]$Configuration = "Release")
$ErrorActionPreference = "Stop"
$projectRoot = Split-Path -Parent $PSScriptRoot
$dotnet = Join-Path $env:USERPROFILE ".dotnet10\dotnet.exe"
$androidSdk = Join-Path $env:LOCALAPPDATA "Android\Sdk"
$keyStore = Join-Path $env:LOCALAPPDATA "Xamarin\Mono for Android\debug.keystore"
$outputDirectory = Join-Path $projectRoot "artifacts\android-test"
$projectPath = Join-Path $projectRoot "LMEMappeCatastaliApp.csproj"
[xml]$projectXml = Get-Content -Raw -LiteralPath $projectPath
$appVersion = ($projectXml.Project.PropertyGroup | Where-Object ApplicationDisplayVersion | Select-Object -First 1).ApplicationDisplayVersion
foreach ($requiredPath in @($dotnet, $androidSdk, $keyStore)) {
if (-not (Test-Path -LiteralPath $requiredPath)) { throw "Componente richiesto non trovato: $requiredPath" }
}
New-Item -ItemType Directory -Force -Path $outputDirectory | Out-Null
$packages = [System.Collections.Generic.List[System.IO.FileInfo]]::new()
foreach ($format in @("apk", "aab")) {
$publishArguments = @(
"publish", $projectPath,
"-f", "net10.0-android",
"-c", $Configuration,
"-p:AndroidSdkDirectory=$androidSdk",
"-p:AndroidPackageFormat=$format",
"-p:RunAOTCompilation=false",
"-p:AndroidKeyStore=true",
"-p:AndroidSigningKeyStore=$keyStore",
"-p:AndroidSigningKeyAlias=androiddebugkey",
"-p:AndroidSigningStorePass=android",
"-p:AndroidSigningKeyPass=android"
)
& $dotnet @publishArguments
if ($LASTEXITCODE -ne 0) { throw "Pubblicazione Android $format non riuscita." }
$publishDirectory = Join-Path $projectRoot "bin\$Configuration\net10.0-android\publish"
$package = Get-ChildItem -LiteralPath $publishDirectory -Filter "*-Signed.$format" -File |
Sort-Object LastWriteTime -Descending |
Select-Object -First 1
if ($null -eq $package) { throw "Nessun pacchetto $format firmato prodotto." }
$destination = Join-Path $outputDirectory "LME-Mappe-Catastali-$appVersion.$format"
Copy-Item -LiteralPath $package.FullName -Destination $destination -Force
$packages.Add((Get-Item -LiteralPath $destination))
}
$packages | ForEach-Object {
$hash = Get-FileHash -Algorithm SHA256 -LiteralPath $_.FullName
"$($hash.Hash.ToLowerInvariant()) $($_.Name)"
} | Set-Content -LiteralPath (Join-Path $outputDirectory "SHA256SUMS.txt") -Encoding ascii
$packages | Select-Object Name, Length, LastWriteTime
+152 -7
View File
@@ -484,6 +484,54 @@ input[type="checkbox"] {
padding: 1px; padding: 1px;
} }
.layer-color-editor {
grid-column: 1 / -1;
display: grid;
gap: 5px;
padding: 6px;
border: 1px solid #cbd5da;
border-radius: 4px;
background: rgba(255, 255, 255, 0.82);
}
.layer-color-editor > header {
display: grid;
grid-template-columns: minmax(0, 1fr) 46px auto;
align-items: center;
gap: 5px;
font-size: 10px;
}
.layer-color-editor > header input[type="color"] {
width: 46px;
min-height: 30px;
}
.layer-color-editor button {
min-height: 28px;
min-width: 0;
padding: 3px 6px;
font-size: 9px;
}
.layer-color-formats {
display: grid;
gap: 4px;
}
.layer-color-formats label {
grid-template-columns: 30px minmax(0, 1fr);
align-items: center;
}
.layer-color-formats input {
font-family: Consolas, "Courier New", monospace;
}
.layer-color-copy {
justify-self: stretch;
}
.layer-photo-picker { .layer-photo-picker {
position: relative; position: relative;
min-height: 32px; min-height: 32px;
@@ -570,11 +618,11 @@ input[type="checkbox"] {
.layer-manager-block > summary, .layer-manager-block > summary,
.layer-manager-object > summary { .layer-manager-object > summary {
display: grid; display: grid;
grid-template-columns: 28px 28px minmax(0, 1fr) 50px; grid-template-columns: 28px 28px minmax(0, 1fr) minmax(28px, auto);
grid-template-areas: grid-template-areas:
"handle expand title count" "handle expand title count"
". . visibility moves" "visibility lock moves moves"
". . actions moves"; "actions actions actions actions";
align-items: start; align-items: start;
gap: 6px; gap: 6px;
min-height: 38px; min-height: 38px;
@@ -585,7 +633,6 @@ input[type="checkbox"] {
.layer-expand-button { .layer-expand-button {
grid-area: expand; grid-area: expand;
grid-row: 1 / span 3;
align-self: center; align-self: center;
justify-self: center; justify-self: center;
width: 28px; width: 28px;
@@ -625,8 +672,9 @@ input[type="checkbox"] {
grid-area: actions; grid-area: actions;
display: grid; display: grid;
grid-template-columns: minmax(0, 1fr); grid-template-columns: minmax(0, 1fr);
width: min(130px, 100%); width: 100%;
gap: 4px; gap: 4px;
margin-top: 2px;
} }
.layer-manager-group > summary > input, .layer-manager-group > summary > input,
@@ -684,6 +732,7 @@ input[type="checkbox"] {
grid-area: moves; grid-area: moves;
display: inline-grid; display: inline-grid;
grid-template-columns: 24px 24px; grid-template-columns: 24px 24px;
justify-self: end;
gap: 2px; gap: 2px;
} }
@@ -729,12 +778,12 @@ input[type="checkbox"] {
} }
.layer-inline-lock { .layer-inline-lock {
grid-area: visibility; grid-area: lock;
justify-self: center; justify-self: center;
width: 28px; width: 28px;
min-width: 28px; min-width: 28px;
min-height: 24px; min-height: 24px;
margin-left: 26px; margin: 0;
padding: 0; padding: 0;
background: transparent; background: transparent;
color: var(--ink); color: var(--ink);
@@ -747,6 +796,7 @@ input[type="checkbox"] {
.project-readonly .leaflet-draw, .project-readonly .leaflet-draw,
.project-readonly .layer-rename-button, .project-readonly .layer-rename-button,
.project-readonly .layer-membership-button,
.project-readonly .layer-remove-button, .project-readonly .layer-remove-button,
.project-readonly .layer-inline-lock, .project-readonly .layer-inline-lock,
.project-readonly .layer-object-tools, .project-readonly .layer-object-tools,
@@ -997,6 +1047,49 @@ input[type="checkbox"] {
font-size: 12px; font-size: 12px;
} }
.attribute-copy-panel {
display: grid;
grid-template-columns: minmax(170px, 1fr) auto;
grid-template-areas:
"heading heading"
"source source"
"toggle action"
"hint hint";
align-items: end;
gap: 8px 12px;
padding: 10px;
border: 1px solid var(--line);
border-radius: 6px;
background: #f5f8f9;
}
.attribute-copy-panel > strong {
grid-area: heading;
}
.attribute-copy-panel > label:first-child {
grid-area: source;
min-width: 0;
}
.attribute-copy-panel > .toggle-line {
grid-area: toggle;
}
.attribute-copy-panel > button {
grid-area: action;
}
.attribute-copy-panel > label:first-child select {
width: 100%;
}
.attribute-copy-panel > small {
grid-area: hint;
color: var(--muted);
line-height: 1.4;
}
.attribute-editor-row { .attribute-editor-row {
display: grid; display: grid;
grid-template-columns: minmax(130px, 0.8fr) minmax(180px, 2fr) 36px; grid-template-columns: minmax(130px, 0.8fr) minmax(180px, 2fr) 36px;
@@ -1061,6 +1154,47 @@ input[type="checkbox"] {
text-decoration: none; text-decoration: none;
} }
.leaflet-help {
display: grid;
gap: 14px;
}
.leaflet-help > p {
margin: 0;
color: var(--muted);
line-height: 1.45;
}
.leaflet-help-list {
display: grid;
gap: 0;
margin: 0;
}
.leaflet-help-list > div {
display: grid;
grid-template-columns: 42px minmax(0, 1fr);
gap: 10px;
padding: 10px 0;
border-bottom: 1px solid var(--line);
}
.leaflet-help-list dt {
font-size: 20px;
font-weight: 900;
text-align: center;
}
.leaflet-help-list dd {
margin: 0;
line-height: 1.45;
}
.leaflet-help-list dd strong {
display: block;
margin-bottom: 2px;
}
.gps-overlay { .gps-overlay {
position: absolute; position: absolute;
top: 72px; top: 72px;
@@ -1611,6 +1745,17 @@ footer {
align-self: center; align-self: center;
} }
.attribute-copy-panel {
grid-template-columns: minmax(0, 1fr);
grid-template-areas:
"heading"
"source"
"toggle"
"action"
"hint";
align-items: stretch;
}
.gps-overlay { .gps-overlay {
top: 68px; top: 68px;
right: 8px; right: 8px;
+484 -123
View File
@@ -132,6 +132,7 @@ window.lmeMap = {
setProjectReadOnly, setProjectReadOnly,
restoreAutosave, restoreAutosave,
compareProjectSnapshots, compareProjectSnapshots,
promptProjectName,
setAdvancedOptions, setAdvancedOptions,
createMapExportGeoJson, createMapExportGeoJson,
createProjectSnapshot, createProjectSnapshot,
@@ -166,6 +167,7 @@ window.lmeMap = {
clearOfflineTiles, clearOfflineTiles,
getOfflineTileStats, getOfflineTileStats,
resize, resize,
importExternalGisFile,
showInfo: setInfo showInfo: setInfo
}; };
@@ -410,9 +412,7 @@ function displayOfficialParcel(xmlText, latitude, longitude, parcel, label, shou
? findParcelLayerByReference(targetGroup, ref) || restoreHiddenParcelLayerByReference(ref) ? findParcelLayerByReference(targetGroup, ref) || restoreHiddenParcelLayerByReference(ref)
: null; : null;
if (existingLayer) { if (existingLayer) {
if (typeof existingLayer.setStyle === "function") { applyStyleFromProperties(existingLayer);
existingLayer.setStyle({ color: "#ef4444", weight: 4, opacity: 1, fillColor: "#fbbf24", fillOpacity: 0.26 });
}
targetGroup.bringToFront(); targetGroup.bringToFront();
if (shouldFit) { if (shouldFit) {
fitLayer(existingLayer); fitLayer(existingLayer);
@@ -444,7 +444,12 @@ function displayOfficialParcel(xmlText, latitude, longitude, parcel, label, shou
feature.properties = { feature.properties = {
...(feature.properties || {}), ...(feature.properties || {}),
_lmeParcelReference: String(ref || label || normalizedParcel) _lmeParcelReference: String(ref || label || normalizedParcel),
_lmeColor: feature.properties?._lmeColor || "#ef4444",
_lmeFillColor: feature.properties?._lmeFillColor || "#fbbf24",
_lmeWeight: Number(feature.properties?._lmeWeight) || 4,
_lmeOpacity: Number.isFinite(Number(feature.properties?._lmeOpacity)) ? Number(feature.properties._lmeOpacity) : 1,
_lmeFillOpacity: Number.isFinite(Number(feature.properties?._lmeFillOpacity)) ? Number(feature.properties._lmeFillOpacity) : 0.26
}; };
const layer = L.geoJSON(feature, { const layer = L.geoJSON(feature, {
pane: normalizedParcel ? "selectedParcelsPane" : "gpsParcelsPane", pane: normalizedParcel ? "selectedParcelsPane" : "gpsParcelsPane",
@@ -733,29 +738,7 @@ function bindFileImport() {
if (file.size > 100 * 1024 * 1024) throw new Error("file superiore a 100 MB; suddividilo prima dell'importazione"); if (file.size > 100 * 1024 * 1024) throw new Error("file superiore a 100 MB; suddividilo prima dell'importazione");
setInfo(`Analisi di ${file.name} (${(file.size / 1024 / 1024).toFixed(1)} MB)...`); setInfo(`Analisi di ${file.name} (${(file.size / 1024 / 1024).toFixed(1)} MB)...`);
await new Promise(resolve => window.setTimeout(resolve, 20)); await new Promise(resolve => window.setTimeout(resolve, 20));
const result = await readGisFile(file); await importGisFile(file);
rememberMapChange();
const geojson = result.geojson;
const parcelLayer = addImportedFeatures(geojson);
const sheetGeojson = result.sheetGeojson || emptyFeatureCollection();
const sheetLayer = addImportedSheetFeatures(sheetGeojson);
applyImportedSheetVisibility();
fitLayer(geojson.features.length ? parcelLayer : sheetLayer);
refreshImportedMeasurements();
const featureCount = geojson.features.length;
const sheetCount = sheetGeojson.features.length;
const ignored = result.ignoredCount
? `; esclusi ${result.ignoredCount} elementi del foglio o non particella`
: "";
const includedSheets = sheetCount
? `; ${sheetCount} elementi foglio ${lmeState.importedSheetsVisible ? "visibili" : "nascosti"}`
: "";
const reprojected = result.reprojected ? "; coordinate Web Mercator convertite" : "";
const warnings = result.validationWarnings ? `; ${result.validationWarnings} geometrie da verificare` : "";
setInfo(`Caricato ${file.name}: ${featureCount} particelle/elementi${includedSheets}${ignored}${reprojected}${warnings}.`);
updateGpsInsideState();
refreshLayerManager();
finishMapChange();
} catch (error) { } catch (error) {
setInfo(`File non leggibile: ${error.message}`); setInfo(`File non leggibile: ${error.message}`);
} finally { } finally {
@@ -765,6 +748,41 @@ function bindFileImport() {
lmeState.fileImportBound = true; lmeState.fileImportBound = true;
} }
async function importExternalGisFile(fileName, base64Content, mimeType) {
const binary = atob(base64Content);
const bytes = new Uint8Array(binary.length);
for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);
const file = new File([bytes], fileName, { type: mimeType || "application/octet-stream" });
if (file.size > 100 * 1024 * 1024) throw new Error("file superiore a 100 MB; suddividilo prima dell'importazione");
setInfo(`Analisi di ${file.name} (${(file.size / 1024 / 1024).toFixed(1)} MB)...`);
await new Promise(resolve => window.setTimeout(resolve, 20));
return importGisFile(file);
}
async function importGisFile(file) {
const result = await readGisFile(file);
rememberMapChange();
const geojson = result.geojson;
const parcelLayer = addImportedFeatures(geojson);
const sheetGeojson = result.sheetGeojson || emptyFeatureCollection();
const sheetLayer = addImportedSheetFeatures(sheetGeojson);
applyImportedSheetVisibility();
fitLayer(geojson.features.length ? parcelLayer : sheetLayer);
refreshImportedMeasurements();
const featureCount = geojson.features.length;
const sheetCount = sheetGeojson.features.length;
const ignored = result.ignoredCount ? `; esclusi ${result.ignoredCount} elementi del foglio o non particella` : "";
const includedSheets = sheetCount ? `; ${sheetCount} elementi foglio ${lmeState.importedSheetsVisible ? "visibili" : "nascosti"}` : "";
const reprojected = result.reprojected ? "; coordinate Web Mercator convertite" : "";
const warnings = result.validationWarnings ? `; ${result.validationWarnings} geometrie da verificare` : "";
const message = `Caricato ${file.name}: ${featureCount} particelle/elementi${includedSheets}${ignored}${reprojected}${warnings}.`;
setInfo(message);
updateGpsInsideState();
refreshLayerManager();
finishMapChange();
return message;
}
async function readGisFile(file) { async function readGisFile(file) {
const lowerName = file.name.toLowerCase(); const lowerName = file.name.toLowerCase();
@@ -981,17 +999,27 @@ function normalizeKmlFiles(files) {
throw new Error("KML senza geometrie utilizzabili"); throw new Error("KML senza geometrie utilizzabili");
} }
if (!looksLikeCadastralKml(features)) {
return {
geojson: { type: "FeatureCollection", features },
sheetGeojson: emptyFeatureCollection(),
ignoredCount: 0,
reprojected: false
};
}
const polygonParts = splitKmlPolygonFeatures(features); const polygonParts = splitKmlPolygonFeatures(features);
const parcels = filterKmlParcelFeatures(polygonParts); const parcels = filterKmlParcelFeatures(polygonParts);
const parcelSet = new Set(parcels); const parcelSet = new Set(parcels);
const sheetParts = polygonParts.filter(feature => !parcelSet.has(feature)); const sheetParts = polygonParts.filter(feature => !parcelSet.has(feature));
const nonPolygonFeatures = features.filter(feature => geometryPolygons(feature.geometry).length === 0); const nonPolygonFeatures = features.filter(feature => geometryPolygons(feature.geometry).length === 0);
const optionalFeatures = [...sheetParts, ...nonPolygonFeatures]; const importedFeatures = [...parcels, ...nonPolygonFeatures];
if (!parcels.length && !(lmeState.includeKmlSheetLayer && optionalFeatures.length)) { const optionalFeatures = sheetParts;
if (!importedFeatures.length && !(lmeState.includeKmlSheetLayer && optionalFeatures.length)) {
throw new Error("nessuna particella trovata; attiva 'includi layer del foglio' per importare gli altri elementi"); throw new Error("nessuna particella trovata; attiva 'includi layer del foglio' per importare gli altri elementi");
} }
return { return {
geojson: { type: "FeatureCollection", features: parcels }, geojson: { type: "FeatureCollection", features: importedFeatures },
sheetGeojson: { sheetGeojson: {
type: "FeatureCollection", type: "FeatureCollection",
features: lmeState.includeKmlSheetLayer ? optionalFeatures : [] features: lmeState.includeKmlSheetLayer ? optionalFeatures : []
@@ -1001,6 +1029,22 @@ function normalizeKmlFiles(files) {
}; };
} }
function looksLikeCadastralKml(features) {
return features.some(feature => {
const properties = feature?.properties || {};
const name = String(properties.name || properties.Name || properties.LABEL || "").trim();
const context = [
name,
properties.layer,
properties.Layer,
properties.type,
properties.Tipo,
properties._lmeFolder
].filter(Boolean).join(" ").toLowerCase();
return /\b(particell|mappal|catast|foglio|parcel|cadastral)\w*/i.test(context);
});
}
function kmlTextToGeoJson(text, sourceName) { function kmlTextToGeoJson(text, sourceName) {
const xml = new DOMParser().parseFromString(text, "text/xml"); const xml = new DOMParser().parseFromString(text, "text/xml");
if (xml.getElementsByTagName("parsererror").length) { if (xml.getElementsByTagName("parsererror").length) {
@@ -1493,6 +1537,10 @@ function managedObjectCanRemove(record) {
return ["drawings", "imported", "importedSheets", "selectedParcels", "gpsParcels"].includes(record.categoryKey); return ["drawings", "imported", "importedSheets", "selectedParcels", "gpsParcels"].includes(record.categoryKey);
} }
function managedCategoryCanMove(categoryKey) {
return ["drawings", "imported", "importedSheets", "selectedParcels"].includes(categoryKey);
}
function layerManagerRowActions(renameButton, moveButton, removeButton) { function layerManagerRowActions(renameButton, moveButton, removeButton) {
if (!renameButton && !moveButton && !removeButton) { if (!renameButton && !moveButton && !removeButton) {
return ""; return "";
@@ -1607,7 +1655,7 @@ function managedMoveDestinations() {
function showMoveManagedRecordsDialog(records, subject) { function showMoveManagedRecordsDialog(records, subject) {
if (lmeState.readOnly) { setInfo("Il progetto e' in sola lettura."); return; } if (lmeState.readOnly) { setInfo("Il progetto e' in sola lettura."); return; }
if (!records.length || records.some(record => !["drawings", "imported"].includes(record.categoryKey))) { if (!records.length || records.some(record => !managedCategoryCanMove(record.categoryKey))) {
setInfo("Questo oggetto o gruppo non puo essere spostato."); setInfo("Questo oggetto o gruppo non puo essere spostato.");
return; return;
} }
@@ -1623,9 +1671,12 @@ function showMoveManagedRecordsDialog(records, subject) {
const categorySelect = form.elements.category; const categorySelect = form.elements.category;
const groupSelect = form.elements.group; const groupSelect = form.elements.group;
const newGroupInput = form.elements.newGroup; const newGroupInput = form.elements.newGroup;
const currentCategory = records.every(record => record.categoryKey === records[0].categoryKey) const sourceCategory = records.every(record => record.categoryKey === records[0].categoryKey)
? records[0].categoryKey ? records[0].categoryKey
: "drawings"; : "drawings";
const currentCategory = destinations.some(destination => destination.key === sourceCategory)
? sourceCategory
: "imported";
categorySelect.value = currentCategory; categorySelect.value = currentCategory;
const refreshGroups = () => { const refreshGroups = () => {
const destination = destinations.find(item => item.key === categorySelect.value); const destination = destinations.find(item => item.key === categorySelect.value);
@@ -1665,7 +1716,7 @@ function showMoveManagedRecordsDialog(records, subject) {
function moveManagedRecordsToGroup(records, targetCategory, targetSource, targetGroupName) { function moveManagedRecordsToGroup(records, targetCategory, targetSource, targetGroupName) {
if (lmeState.readOnly) { setInfo("Il progetto e' in sola lettura."); return; } if (lmeState.readOnly) { setInfo("Il progetto e' in sola lettura."); return; }
const movable = records.filter(record => ["drawings", "imported"].includes(record.categoryKey)); const movable = records.filter(record => managedCategoryCanMove(record.categoryKey));
if (!movable.length || !["drawings", "imported"].includes(targetCategory)) { if (!movable.length || !["drawings", "imported"].includes(targetCategory)) {
setInfo("Questo gruppo non puo essere spostato."); setInfo("Questo gruppo non puo essere spostato.");
return; return;
@@ -1808,7 +1859,7 @@ function renderLayerManagerCategory(category, records) {
const removeButton = managedCategoryCanRemove(category, records) const removeButton = managedCategoryCanRemove(category, records)
? `<button type="button" class="layer-remove-button" aria-label="Rimuovi gruppo dal progetto" title="Rimuovi dal progetto">Rimuovi</button>` ? `<button type="button" class="layer-remove-button" aria-label="Rimuovi gruppo dal progetto" title="Rimuovi dal progetto">Rimuovi</button>`
: ""; : "";
const moveButton = records.length && ["drawings", "imported"].includes(category.key) const moveButton = records.length && managedCategoryCanMove(category.key)
? `<button type="button" class="layer-membership-button" aria-label="Sposta gruppo in un altro gruppo" title="Sposta nel gruppo">Sposta nel gruppo</button>` ? `<button type="button" class="layer-membership-button" aria-label="Sposta gruppo in un altro gruppo" title="Sposta nel gruppo">Sposta nel gruppo</button>`
: ""; : "";
const rowActions = layerManagerRowActions(renameButton, moveButton, removeButton); const rowActions = layerManagerRowActions(renameButton, moveButton, removeButton);
@@ -1932,7 +1983,7 @@ function renderLayerManagerObject(record, index) {
const removeButton = managedObjectCanRemove(record) const removeButton = managedObjectCanRemove(record)
? `<button type="button" class="layer-remove-button" aria-label="Rimuovi oggetto dal progetto" title="Rimuovi dal progetto">Rimuovi</button>` ? `<button type="button" class="layer-remove-button" aria-label="Rimuovi oggetto dal progetto" title="Rimuovi dal progetto">Rimuovi</button>`
: ""; : "";
const moveButton = ["drawings", "imported"].includes(record.categoryKey) const moveButton = managedCategoryCanMove(record.categoryKey)
? `<button type="button" class="layer-membership-button" aria-label="Sposta oggetto in un altro gruppo" title="Sposta nel gruppo">Sposta nel gruppo</button>` ? `<button type="button" class="layer-membership-button" aria-label="Sposta oggetto in un altro gruppo" title="Sposta nel gruppo">Sposta nel gruppo</button>`
: ""; : "";
const rowActions = layerManagerRowActions(renameButton, moveButton, removeButton); const rowActions = layerManagerRowActions(renameButton, moveButton, removeButton);
@@ -2008,9 +2059,15 @@ function renderLayerSelectionToolbar() {
</div>`; </div>`;
const search = toolbar.querySelector("input"); const search = toolbar.querySelector("input");
search.addEventListener("input", () => { search.addEventListener("input", () => {
const selectionStart = search.selectionStart ?? search.value.length;
const selectionEnd = search.selectionEnd ?? selectionStart;
lmeState.managerSearchText = search.value; lmeState.managerSearchText = search.value;
refreshLayerManager(); refreshLayerManager();
requestAnimationFrame(() => document.querySelector(".layer-selection-toolbar input")?.focus()); const replacement = document.querySelector(".layer-selection-toolbar input");
if (replacement) {
replacement.focus({ preventScroll: true });
replacement.setSelectionRange(selectionStart, selectionEnd);
}
}); });
toolbar.querySelectorAll("button").forEach(button => button.addEventListener("click", () => { toolbar.querySelectorAll("button").forEach(button => button.addEventListener("click", () => {
const records = [...lmeState.managerSelectedObjectIds] const records = [...lmeState.managerSelectedObjectIds]
@@ -2033,16 +2090,26 @@ function renderLayerSelectionToolbar() {
function renderManagedGroupTools(records) { function renderManagedGroupTools(records) {
const tools = document.createElement("div"); const tools = document.createElement("div");
tools.className = "layer-group-tools"; tools.className = "layer-group-tools";
const properties = records[0]?.layer?.feature?.properties || {}; const firstLayer = records[0]?.layer;
const properties = firstLayer?.feature?.properties || {};
const lineColor = normalizedColor(properties._lmeColor || firstLayer?.options?.color, "#16806a");
const fillColor = normalizedColor(properties._lmeFillColor || firstLayer?.options?.fillColor, lineColor);
tools.innerHTML = `<strong>Azioni gruppo</strong><span class="layer-group-totals">${escapeHtml(managedGroupTotals(records))}</span><div class="layer-style-controls"> tools.innerHTML = `<strong>Azioni gruppo</strong><span class="layer-group-totals">${escapeHtml(managedGroupTotals(records))}</span><div class="layer-style-controls">
<label>Colore<input type="color" value="${normalizedColor(properties._lmeColor, "#16806a")}"></label> ${managedColorEditorMarkup("color", "Colore linea", lineColor)}
<label>Spessore<input type="range" min="1" max="10" step="1" value="${Number(properties._lmeWeight) || 3}"></label> ${managedColorEditorMarkup("fillColor", "Colore riempimento", fillColor)}
<label>Opacita<input type="range" min="0.1" max="1" step="0.1" value="${Number(properties._lmeOpacity) || 1}"></label></div> <label>Spessore<input type="range" data-field="weight" min="1" max="10" step="1" value="${Number(properties._lmeWeight) || Number(firstLayer?.options?.weight) || 3}"></label>
<label>Opacita<input type="range" data-field="opacity" min="0.1" max="1" step="0.1" value="${Number.isFinite(Number(properties._lmeOpacity)) ? Number(properties._lmeOpacity) : Number(firstLayer?.options?.opacity) || 1}"></label></div>
<div class="layer-compact-actions"><button type="button" data-group-action="select">Seleziona tutti</button><button type="button" data-group-action="lock">Blocca/sblocca</button><button type="button" data-group-action="labels">Etichette</button></div>`; <div class="layer-compact-actions"><button type="button" data-group-action="select">Seleziona tutti</button><button type="button" data-group-action="lock">Blocca/sblocca</button><button type="button" data-group-action="labels">Etichette</button></div>`;
const inputs = tools.querySelectorAll("input"); const applyCurrentStyle = () => {
inputs.forEach(input => input.addEventListener("change", () => { applyManagedStyle(records, {
applyManagedStyle(records, { color: inputs[0].value, weight: Number(inputs[1].value), opacity: Number(inputs[2].value) }); color: tools.querySelector("[data-color-picker='color']").value,
})); fillColor: tools.querySelector("[data-color-picker='fillColor']").value,
weight: Number(tools.querySelector("[data-field='weight']").value),
opacity: Number(tools.querySelector("[data-field='opacity']").value)
});
};
bindManagedColorEditors(tools, applyCurrentStyle);
tools.querySelectorAll("input[type='range']").forEach(input => input.addEventListener("change", applyCurrentStyle));
tools.querySelector("[data-group-action='select']").addEventListener("click", () => { tools.querySelector("[data-group-action='select']").addEventListener("click", () => {
records.forEach(record => lmeState.managerSelectedObjectIds.add(record.id)); refreshLayerManager(); records.forEach(record => lmeState.managerSelectedObjectIds.add(record.id)); refreshLayerManager();
}); });
@@ -2079,11 +2146,13 @@ function renderManagedObjectTools(record) {
const locked = Boolean(properties._lmeLocked); const locked = Boolean(properties._lmeLocked);
const tools = document.createElement("section"); const tools = document.createElement("section");
tools.className = "layer-object-tools"; tools.className = "layer-object-tools";
const lineColor = normalizedColor(properties._lmeColor || record.layer?.options?.color, "#f97316");
const fillColor = normalizedColor(properties._lmeFillColor || record.layer?.options?.fillColor, lineColor);
tools.innerHTML = `<label class="layer-manager-suboption"><input type="checkbox" data-field="selected" ${selected ? "checked" : ""}><span>Seleziona per azioni multiple</span></label> tools.innerHTML = `<label class="layer-manager-suboption"><input type="checkbox" data-field="selected" ${selected ? "checked" : ""}><span>Seleziona per azioni multiple</span></label>
<label class="layer-manager-suboption"><input type="checkbox" data-field="locked" ${locked ? "checked" : ""}><span>Blocca modifiche e rimozione</span></label> <label class="layer-manager-suboption"><input type="checkbox" data-field="locked" ${locked ? "checked" : ""}><span>Blocca modifiche e rimozione</span></label>
<label class="layer-manager-suboption"><input type="checkbox" data-field="label" ${properties._lmeLabelVisible ? "checked" : ""}><span>Etichetta permanente sulla mappa</span></label> <label class="layer-manager-suboption"><input type="checkbox" data-field="label" ${properties._lmeLabelVisible ? "checked" : ""}><span>Etichetta permanente sulla mappa</span></label>
<div class="layer-style-controls"><label>Linea<input type="color" data-field="color" value="${normalizedColor(properties._lmeColor, "#f97316")}"></label> <div class="layer-style-controls">${managedColorEditorMarkup("color", "Colore linea", lineColor)}
<label>Riempimento<input type="color" data-field="fillColor" value="${normalizedColor(properties._lmeFillColor, "#fb923c")}"></label> ${managedColorEditorMarkup("fillColor", "Colore riempimento", fillColor)}
<label>Spessore<input type="range" data-field="weight" min="1" max="10" step="1" value="${Number(properties._lmeWeight) || 3}"></label> <label>Spessore<input type="range" data-field="weight" min="1" max="10" step="1" value="${Number(properties._lmeWeight) || 3}"></label>
<label>Opacita<input type="range" data-field="opacity" min="0.1" max="1" step="0.1" value="${Number(properties._lmeOpacity) || 1}"></label> <label>Opacita<input type="range" data-field="opacity" min="0.1" max="1" step="0.1" value="${Number(properties._lmeOpacity) || 1}"></label>
<label>Riempimento %<input type="range" data-field="fillOpacity" min="0" max="0.8" step="0.05" value="${Number.isFinite(Number(properties._lmeFillOpacity)) ? Number(properties._lmeFillOpacity) : 0.2}"></label> <label>Riempimento %<input type="range" data-field="fillOpacity" min="0" max="0.8" step="0.05" value="${Number.isFinite(Number(properties._lmeFillOpacity)) ? Number(properties._lmeFillOpacity) : 0.2}"></label>
@@ -2099,14 +2168,16 @@ function renderManagedObjectTools(record) {
}); });
tools.querySelector("[data-field='locked']").addEventListener("change", event => updateManagedProperties([record], value => { value._lmeLocked = event.target.checked; })); tools.querySelector("[data-field='locked']").addEventListener("change", event => updateManagedProperties([record], value => { value._lmeLocked = event.target.checked; }));
tools.querySelector("[data-field='label']").addEventListener("change", event => updateManagedProperties([record], value => { value._lmeLabelVisible = event.target.checked; })); tools.querySelector("[data-field='label']").addEventListener("change", event => updateManagedProperties([record], value => { value._lmeLabelVisible = event.target.checked; }));
tools.querySelectorAll(".layer-style-controls input,.layer-style-controls select").forEach(input => input.addEventListener("change", () => applyManagedStyle([record], { const applyCurrentStyle = () => applyManagedStyle([record], {
color: tools.querySelector("[data-field='color']").value, color: tools.querySelector("[data-color-picker='color']").value,
fillColor: tools.querySelector("[data-field='fillColor']").value, fillColor: tools.querySelector("[data-color-picker='fillColor']").value,
weight: Number(tools.querySelector("[data-field='weight']").value), weight: Number(tools.querySelector("[data-field='weight']").value),
opacity: Number(tools.querySelector("[data-field='opacity']").value), opacity: Number(tools.querySelector("[data-field='opacity']").value),
fillOpacity: Number(tools.querySelector("[data-field='fillOpacity']").value), fillOpacity: Number(tools.querySelector("[data-field='fillOpacity']").value),
dash: tools.querySelector("[data-field='dash']").value dash: tools.querySelector("[data-field='dash']").value
}))); });
bindManagedColorEditors(tools, applyCurrentStyle);
tools.querySelectorAll(".layer-style-controls input[type='range'],.layer-style-controls select").forEach(input => input.addEventListener("change", applyCurrentStyle));
tools.querySelector("[data-field='notes']").addEventListener("change", event => updateManagedProperties([record], value => { value._lmeNotes = event.target.value.trim(); })); tools.querySelector("[data-field='notes']").addEventListener("change", event => updateManagedProperties([record], value => { value._lmeNotes = event.target.value.trim(); }));
tools.querySelector("[data-field='photo']").addEventListener("change", async event => { tools.querySelector("[data-field='photo']").addEventListener("change", async event => {
const file = event.target.files?.[0]; if (!file) return; const file = event.target.files?.[0]; if (!file) return;
@@ -2128,13 +2199,150 @@ function normalizedColor(value, fallback) {
return /^#[0-9a-f]{6}$/i.test(String(value || "")) ? value : fallback; return /^#[0-9a-f]{6}$/i.test(String(value || "")) ? value : fallback;
} }
function managedColorEditorMarkup(field, label, color) {
const formats = managedColorFormats(color);
return `<section class="layer-color-editor" data-color-editor="${field}">
<header><strong>${escapeHtml(label)}</strong><input type="color" data-color-picker="${field}" value="${formats.hex}" aria-label="Seleziona ${escapeHtml(label.toLocaleLowerCase("it"))}"><button type="button" data-color-eyedropper title="Preleva un colore dallo schermo">Preleva</button></header>
<div class="layer-color-formats">
<label>HEX<input type="text" data-color-format="hex" value="${formats.hex}" maxlength="7" spellcheck="false"></label>
<label>RGB<input type="text" data-color-format="rgb" value="${formats.rgb}" spellcheck="false"></label>
<label>HSL<input type="text" data-color-format="hsl" value="${formats.hsl}" spellcheck="false"></label>
</div>
<button type="button" class="layer-color-copy" data-color-copy>Copia HEX</button>
</section>`;
}
function bindManagedColorEditors(container, onChanged) {
container.querySelectorAll("[data-color-editor]").forEach(editor => {
const picker = editor.querySelector("[data-color-picker]");
const formatInputs = [...editor.querySelectorAll("[data-color-format]")];
const sync = (color, notify) => {
const formats = managedColorFormats(color);
picker.value = formats.hex;
formatInputs.forEach(input => { input.value = formats[input.dataset.colorFormat]; });
if (notify) onChanged();
};
picker.addEventListener("change", () => sync(picker.value, true));
formatInputs.forEach(input => input.addEventListener("change", () => {
const parsed = parseManagedColor(input.value);
if (!parsed) {
sync(picker.value, false);
setInfo("Colore non valido. Usa HEX, rgb(r, g, b) oppure hsl(h, s%, l%).");
return;
}
sync(parsed, true);
}));
const eyedropper = editor.querySelector("[data-color-eyedropper]");
if (typeof window.EyeDropper !== "function") {
eyedropper.hidden = true;
} else {
eyedropper.addEventListener("click", async () => {
try {
const result = await new window.EyeDropper().open();
if (result?.sRGBHex) sync(result.sRGBHex, true);
} catch (error) {
if (error?.name !== "AbortError") setInfo("Contagocce non disponibile su questo dispositivo.");
}
});
}
editor.querySelector("[data-color-copy]").addEventListener("click", async () => {
const value = picker.value.toUpperCase();
try {
await navigator.clipboard.writeText(value);
setInfo(`Colore ${value} copiato. Puoi incollarlo nel campo HEX di un altro oggetto.`);
} catch {
const hexInput = editor.querySelector("[data-color-format='hex']");
hexInput.focus();
hexInput.select();
setInfo(`Selezionato ${value}: usa il comando Copia del dispositivo.`);
}
});
});
}
function parseManagedColor(value) {
const text = String(value || "").trim();
const shortHex = text.match(/^#([0-9a-f]{3})$/i);
if (shortHex) return `#${[...shortHex[1]].map(part => part + part).join("")}`.toUpperCase();
if (/^#[0-9a-f]{6}$/i.test(text)) return text.toUpperCase();
const rgb = text.match(/^rgba?\(\s*(\d{1,3})\s*[, ]\s*(\d{1,3})\s*[, ]\s*(\d{1,3})(?:\s*[,/]\s*[\d.]+)?\s*\)$/i);
if (rgb) {
const values = rgb.slice(1, 4).map(Number);
if (values.every(channel => channel >= 0 && channel <= 255)) return managedRgbToHex(...values);
}
const hsl = text.match(/^hsla?\(\s*(-?[\d.]+)(?:deg)?\s*[, ]\s*([\d.]+)%\s*[, ]\s*([\d.]+)%(?:\s*[,/]\s*[\d.]+)?\s*\)$/i);
if (hsl) {
const saturation = Number(hsl[2]); const lightness = Number(hsl[3]);
if (saturation >= 0 && saturation <= 100 && lightness >= 0 && lightness <= 100) {
return managedRgbToHex(...managedHslToRgb(Number(hsl[1]), saturation, lightness));
}
}
return null;
}
function managedColorFormats(color) {
const hex = normalizedColor(color, "#000000").toUpperCase();
const [red, green, blue] = [1, 3, 5].map(index => parseInt(hex.slice(index, index + 2), 16));
const redUnit = red / 255; const greenUnit = green / 255; const blueUnit = blue / 255;
const max = Math.max(redUnit, greenUnit, blueUnit); const min = Math.min(redUnit, greenUnit, blueUnit);
const lightness = (max + min) / 2; const delta = max - min;
let hue = 0; let saturation = 0;
if (delta) {
saturation = delta / (1 - Math.abs(2 * lightness - 1));
if (max === redUnit) hue = 60 * (((greenUnit - blueUnit) / delta) % 6);
else if (max === greenUnit) hue = 60 * ((blueUnit - redUnit) / delta + 2);
else hue = 60 * ((redUnit - greenUnit) / delta + 4);
}
if (hue < 0) hue += 360;
return {
hex,
rgb: `rgb(${red}, ${green}, ${blue})`,
hsl: `hsl(${managedColorDecimal(hue)}, ${managedColorDecimal(saturation * 100)}%, ${managedColorDecimal(lightness * 100)}%)`
};
}
function managedColorDecimal(value) {
return String(Number(value.toFixed(2)));
}
function managedRgbToHex(red, green, blue) {
return `#${[red, green, blue].map(channel => Math.round(channel).toString(16).padStart(2, "0")).join("")}`.toUpperCase();
}
function managedHslToRgb(hue, saturation, lightness) {
const normalizedHue = ((hue % 360) + 360) % 360;
const saturationUnit = saturation / 100; const lightnessUnit = lightness / 100;
const chroma = (1 - Math.abs(2 * lightnessUnit - 1)) * saturationUnit;
const section = normalizedHue / 60; const intermediate = chroma * (1 - Math.abs(section % 2 - 1));
const values = section < 1 ? [chroma, intermediate, 0]
: section < 2 ? [intermediate, chroma, 0]
: section < 3 ? [0, chroma, intermediate]
: section < 4 ? [0, intermediate, chroma]
: section < 5 ? [intermediate, 0, chroma]
: [chroma, 0, intermediate];
const offset = lightnessUnit - chroma / 2;
return values.map(channel => Math.round((channel + offset) * 255));
}
function editableManagedMetadataEntries(record) {
const properties = record?.layer?.feature?.properties || {};
const reserved = new Set(["name", "Name", "label", "LABEL"]);
return Object.entries(properties)
.filter(([key, value]) => !key.startsWith("_lme") && !reserved.has(key) && ["string", "number", "boolean"].includes(typeof value));
}
function editManagedAttributes(record) { function editManagedAttributes(record) {
if (lmeState.readOnly) { setInfo("Il progetto e' in sola lettura."); return; } if (lmeState.readOnly) { setInfo("Il progetto e' in sola lettura."); return; }
const properties = record.layer?.feature?.properties || {};
const reserved = new Set(["name", "Name", "label", "LABEL"]); const reserved = new Set(["name", "Name", "label", "LABEL"]);
const entries = Object.entries(properties) const entries = editableManagedMetadataEntries(record);
.filter(([key, value]) => !key.startsWith("_lme") && !reserved.has(key) && ["string", "number", "boolean"].includes(typeof value)); const sourceRecords = layerManagerCategories()
const dialog = showAppDialog("Attributi oggetto", `<div class="attribute-editor"><p>Ogni attributo viene salvato nel progetto e negli export GeoJSON, KML e KMZ.</p><div class="attribute-editor-rows"></div><button type="button" data-add-attribute>+ Aggiungi attributo</button><div class="dialog-command-row"><button type="button" data-cancel>Annulla</button><button type="button" class="primary-command" data-save-attributes>Salva attributi</button></div></div>`); .flatMap(category => managedRecordsForCategory(category))
.filter(item => item.id !== record.id);
const sourceOptions = sourceRecords.map((item, index) =>
`<option value="${escapeHtml(item.id)}">${escapeHtml(managedObjectLabel(item, index))} - ${escapeHtml(item.source)}</option>`).join("");
const dialog = showAppDialog("Metadati oggetto", `<div class="attribute-editor"><p>Ogni metadato viene salvato nel progetto e negli export GeoJSON, KML e KMZ.</p>
<section class="attribute-copy-panel"><strong>Copia da un altro oggetto</strong><label>Oggetto sorgente<select data-copy-source ${sourceRecords.length ? "" : "disabled"}><option value="">Seleziona un oggetto</option>${sourceOptions}</select></label><label class="toggle-line"><input type="checkbox" data-copy-values checked><span>Importa anche i valori</span></label><small>Disattiva il flag per importare soltanto i nomi dei metadati con valore vuoto.</small><button type="button" data-copy-attributes ${sourceRecords.length ? "" : "disabled"}>Copia da</button></section>
<div class="attribute-editor-rows"></div><button type="button" data-add-attribute>+ Aggiungi metadato</button><div class="dialog-command-row"><button type="button" data-cancel>Annulla</button><button type="button" class="primary-command" data-save-attributes>Salva metadati</button></div></div>`);
const rows = dialog.querySelector(".attribute-editor-rows"); const rows = dialog.querySelector(".attribute-editor-rows");
const addRow = (key = "", value = "") => { const addRow = (key = "", value = "") => {
const row = document.createElement("div"); const row = document.createElement("div");
@@ -2145,6 +2353,25 @@ function editManagedAttributes(record) {
}; };
entries.forEach(([key, value]) => addRow(key, value)); entries.forEach(([key, value]) => addRow(key, value));
if (!entries.length) addRow(); if (!entries.length) addRow();
const sourceById = new Map(sourceRecords.map(item => [item.id, item]));
dialog.querySelector("[data-copy-attributes]")?.addEventListener("click", () => {
const source = sourceById.get(dialog.querySelector("[data-copy-source]").value);
if (!source) { setInfo("Seleziona l'oggetto da cui copiare i metadati."); return; }
const includeValues = dialog.querySelector("[data-copy-values]").checked;
const existingRows = new Map([...rows.querySelectorAll(".attribute-editor-row")]
.map(row => [row.querySelector("input").value.trim().toLocaleLowerCase("it"), row])
.filter(([key]) => key));
const sourceEntries = editableManagedMetadataEntries(source);
sourceEntries.forEach(([key, value]) => {
const existing = existingRows.get(key.toLocaleLowerCase("it"));
if (existing) {
if (includeValues) existing.querySelector("textarea").value = String(value);
} else {
addRow(key, includeValues ? value : "");
}
});
setInfo(`${sourceEntries.length} metadati copiati${includeValues ? " con i valori" : " senza valori"}.`);
});
dialog.querySelector("[data-add-attribute]").addEventListener("click", () => addRow()); dialog.querySelector("[data-add-attribute]").addEventListener("click", () => addRow());
dialog.querySelector("[data-cancel]").addEventListener("click", () => dialog.remove()); dialog.querySelector("[data-cancel]").addEventListener("click", () => dialog.remove());
dialog.querySelector("[data-save-attributes]").addEventListener("click", () => { dialog.querySelector("[data-save-attributes]").addEventListener("click", () => {
@@ -2250,6 +2477,16 @@ function showFormDialog(title, fields, submitLabel = "Salva") {
}); });
} }
async function promptProjectName(currentName) {
const result = await showFormDialog("Rinomina progetto", [{
name: "name",
label: "Nuovo nome",
value: currentName || "",
maxLength: 80
}], "Rinomina");
return result?.name?.trim() || null;
}
function showObjectTable() { function showObjectTable() {
const records = layerManagerCategories().flatMap(category => managedRecordsForCategory(category)); const records = layerManagerCategories().flatMap(category => managedRecordsForCategory(category));
lmeState.managerRecords = new Map(records.map(record => [record.id, record])); lmeState.managerRecords = new Map(records.map(record => [record.id, record]));
@@ -2258,9 +2495,9 @@ function showObjectTable() {
const details = managedObjectDetails(record.layer); const details = managedObjectDetails(record.layer);
const selected = lmeState.managerSelectedObjectIds.has(record.id); const selected = lmeState.managerSelectedObjectIds.has(record.id);
const locked = Boolean(properties._lmeLocked); const locked = Boolean(properties._lmeLocked);
return `<tr data-object-id="${escapeHtml(record.id)}"><td><input type="checkbox" data-select="${escapeHtml(record.id)}" ${selected ? "checked" : ""} aria-label="Seleziona ${escapeHtml(managedObjectLabel(record, index))}"></td><td><input type="checkbox" data-lock="${escapeHtml(record.id)}" ${locked ? "checked" : ""} ${lmeState.readOnly ? "disabled" : ""} aria-label="Blocca ${escapeHtml(managedObjectLabel(record, index))}"></td><td><button type="button" data-locate="${escapeHtml(record.id)}" title="Mostra sulla mappa" aria-label="Mostra sulla mappa">⌖</button></td><td>${escapeHtml(managedObjectLabel(record, index))}</td><td>${escapeHtml(managedCategoryName(layerManagerCategories().find(item => item.key === record.categoryKey) || { key: record.categoryKey, label: record.categoryKey }, [record]))}</td><td>${escapeHtml(properties.foglio || properties.FOGLIO || "")}</td><td>${escapeHtml(properties.particella || properties.PARTICELLA || properties.LABEL || "")}</td><td>${escapeHtml(details.slice(0, 2).join(" | "))}</td></tr>`; return `<tr data-object-id="${escapeHtml(record.id)}"><td><input type="checkbox" data-select="${escapeHtml(record.id)}" ${selected ? "checked" : ""} aria-label="Seleziona ${escapeHtml(managedObjectLabel(record, index))}"></td><td><input type="checkbox" data-lock="${escapeHtml(record.id)}" ${locked ? "checked" : ""} ${lmeState.readOnly ? "disabled" : ""} aria-label="Blocca ${escapeHtml(managedObjectLabel(record, index))}"></td><td><button type="button" data-locate="${escapeHtml(record.id)}" title="Mostra sulla mappa" aria-label="Mostra sulla mappa">⌖</button></td><td><button type="button" data-attributes="${escapeHtml(record.id)}" title="Modifica metadati" aria-label="Modifica metadati di ${escapeHtml(managedObjectLabel(record, index))}" ${lmeState.readOnly ? "disabled" : ""}>✎</button></td><td>${escapeHtml(managedObjectLabel(record, index))}</td><td>${escapeHtml(managedCategoryName(layerManagerCategories().find(item => item.key === record.categoryKey) || { key: record.categoryKey, label: record.categoryKey }, [record]))}</td><td>${escapeHtml(properties.foglio || properties.FOGLIO || "")}</td><td>${escapeHtml(properties.particella || properties.PARTICELLA || properties.LABEL || "")}</td><td>${escapeHtml(details.slice(0, 2).join(" | "))}</td></tr>`;
}).join(""); }).join("");
const dialog = showAppDialog("Elenco oggetti e particelle", `<label class="object-table-search">Filtra<input type="search" placeholder="Nome, foglio, particella o gruppo"></label><div class="object-table-legend"><span>Seleziona più oggetti con i flag nella colonna Selez.</span><span>Il lucchetto impedisce modifiche e rimozioni.</span></div><div class="object-table-wrap"><table><thead><tr><th>Selez.</th><th>Blocca</th><th>Mappa</th><th>Nome</th><th>Gruppo</th><th>Foglio</th><th>Particella</th><th>Misure</th></tr></thead><tbody>${body || "<tr><td colspan='8'>Nessun oggetto</td></tr>"}</tbody></table></div>`); const dialog = showAppDialog("Elenco oggetti e particelle", `<label class="object-table-search">Filtra<input type="search" placeholder="Nome, foglio, particella o gruppo"></label><div class="object-table-legend"><span>Seleziona più oggetti con i flag nella colonna Selez.</span><span>Il lucchetto impedisce modifiche e rimozioni; la matita modifica i metadati.</span></div><div class="object-table-wrap"><table><thead><tr><th>Selez.</th><th>Blocca</th><th>Mappa</th><th>Metadati</th><th>Nome</th><th>Gruppo</th><th>Foglio</th><th>Particella</th><th>Misure</th></tr></thead><tbody>${body || "<tr><td colspan='9'>Nessun oggetto</td></tr>"}</tbody></table></div>`);
const byId = new Map(records.map(record => [record.id, record])); const byId = new Map(records.map(record => [record.id, record]));
dialog.querySelector("input[type='search']").addEventListener("input", event => { dialog.querySelector("input[type='search']").addEventListener("input", event => {
const query = event.target.value.toLocaleLowerCase("it"); const query = event.target.value.toLocaleLowerCase("it");
@@ -2288,6 +2525,10 @@ function showObjectTable() {
const record = byId.get(button.dataset.locate); if (!record) return; const record = byId.get(button.dataset.locate); if (!record) return;
dialog.remove(); highlightManagedObject(record); dialog.remove(); highlightManagedObject(record);
})); }));
dialog.querySelectorAll("[data-attributes]").forEach(button => button.addEventListener("click", () => {
const record = byId.get(button.dataset.attributes); if (!record) return;
dialog.remove(); editManagedAttributes(record);
}));
return records.length; return records.length;
} }
@@ -2580,6 +2821,27 @@ function showGeometryResult(title, message, tone = "success") {
showAppDialog(title, `<div class="geometry-result geometry-result-${tone}"><span aria-hidden="true">${icons[tone] || "i"}</span><p>${escapeHtml(message)}</p></div>`); showAppDialog(title, `<div class="geometry-result geometry-result-${tone}"><span aria-hidden="true">${icons[tone] || "i"}</span><p>${escapeHtml(message)}</p></div>`);
} }
function showLeafletToolbarHelp() {
showAppDialog("Guida strumenti mappa", `<div class="leaflet-help">
<p>Gli strumenti operano direttamente sulla mappa. Per le azioni su oggetti esistenti, seleziona prima le righe nel pannello Layer, nella tabella oggetti oppure tocca un oggetto sulla mappa.</p>
<dl class="leaflet-help-list">
<div><dt>+</dt><dd><strong>Ingrandisci</strong>Aumenta lo zoom mantenendo il centro attuale. Esempio: avvicinati a un vertice per posizionarlo con maggiore precisione.</dd></div>
<div><dt>−</dt><dd><strong>Riduci</strong>Allarga l'area visibile. Esempio: usalo per controllare insieme particelle appartenenti a fogli vicini.</dd></div>
<div><dt>●</dt><dd><strong>Punto di interesse</strong>Tocca la posizione da memorizzare. Esempio: segna un cancello, un cippo o il punto di accesso al fondo.</dd></div>
<div><dt>/</dt><dd><strong>Linea</strong>Tocca i vertici del percorso e termina con doppio tocco o sul primo comando della barra. Durante il disegno viene mostrata la distanza; utile per un fronte strada o una recinzione.</dd></div>
<div><dt>⬠</dt><dd><strong>Poligono</strong>Tocca almeno tre vertici e chiudi la figura. Esempio: delimita un'area di intervento; l'app calcola area e perimetro.</dd></div>
<div><dt>□</dt><dd><strong>Rettangolo</strong>Trascina tra due angoli opposti. Esempio: crea rapidamente l'ingombro rettangolare di un fabbricato.</dd></div>
<div><dt>○</dt><dd><strong>Cerchio</strong>Tocca il centro e trascina fino al raggio desiderato. Esempio: rappresenta una fascia di rispetto attorno a un pozzo.</dd></div>
<div><dt>✎</dt><dd><strong>Modifica disegni</strong>Premi la matita e scegli Solo selezionato oppure Tutti. Sposta i vertici e conferma con Salva; gli oggetti bloccati devono prima essere sbloccati.</dd></div>
<div><dt>▱</dt><dd><strong>Elimina disegni</strong>Premi il cestino e scegli Solo selezionato oppure Tutti. L'oggetto rimosso può essere recuperato con Annulla o dal cestino negli strumenti avanzati.</dd></div>
<div><dt>✓</dt><dd><strong>Controlla e ripara</strong>Verifica gli oggetti selezionati e prova a correggere coordinate duplicate o poligoni non validi. Esempio: usalo quando un contorno importato non si esporta o si riempie male; al termine compare un riepilogo.</dd></div>
<div><dt>◉</dt><dd><strong>Crea foro</strong>Seleziona esattamente due poligoni: prima l'area esterna, poi quella interna. Esempio: sottrai il cortile dal perimetro di un fabbricato o un'isola esclusa da un'area di lavoro.</dd></div>
<div><dt>⇄</dt><dd><strong>Confronta due confini</strong>Seleziona esattamente due poligoni. L'app crea il solo primo in rosso, il solo secondo in blu e la sovrapposizione in verde, mostrando le rispettive aree.</dd></div>
<div><dt>?</dt><dd><strong>Guida</strong>Riapre questa descrizione. I risultati di riparazione e confronto vengono mostrati anche in una finestra, così l'operazione non resta senza riscontro.</dd></div>
</dl>
</div>`);
}
function addGeometryToolsControl() { function addGeometryToolsControl() {
if (lmeState.geometryToolsControl || !lmeState.map) return; if (lmeState.geometryToolsControl || !lmeState.map) return;
const GeometryTools = L.Control.extend({ const GeometryTools = L.Control.extend({
@@ -2589,7 +2851,8 @@ function addGeometryToolsControl() {
const actions = [ const actions = [
{ icon: "✓", title: "Controlla e ripara geometrie", run: validateAndRepairSelected }, { icon: "✓", title: "Controlla e ripara geometrie", run: validateAndRepairSelected },
{ icon: "◉", title: "Crea foro da due poligoni", run: createHoleFromSelected }, { icon: "◉", title: "Crea foro da due poligoni", run: createHoleFromSelected },
{ icon: "⇄", title: "Confronta due confini", run: compareSelectedGeometries } { icon: "⇄", title: "Confronta due confini", run: compareSelectedGeometries },
{ icon: "?", title: "Guida strumenti mappa", run: showLeafletToolbarHelp }
]; ];
actions.forEach(action => { actions.forEach(action => {
const button = L.DomUtil.create("a", "", container); const button = L.DomUtil.create("a", "", container);
@@ -3244,77 +3507,155 @@ function applyManagedVisualOrder(container) {
}); });
} }
function setImportedSheetLayerVisible(enabled) { async function setImportedSheetLayerVisible(enabled) {
migrateMisclassifiedImportedSheets(); migrateMisclassifiedImportedSheets();
lmeState.importedSheetsVisible = Boolean(enabled); lmeState.importedSheetsVisible = Boolean(enabled);
const generated = lmeState.importedSheetsVisible && ensureImportedSheetOutline(); let sheetResult = null;
if (lmeState.importedSheetsVisible) {
setInfo("Carico i fogli catastali delle particelle...");
sheetResult = await ensureImportedSheetOutlines();
}
applyImportedSheetVisibility(); applyImportedSheetVisibility();
const count = lmeState.importedSheets?.toGeoJSON()?.features?.length || 0; const count = lmeState.importedSheets?.toGeoJSON()?.features?.length || 0;
setInfo(lmeState.importedSheetsVisible setInfo(lmeState.importedSheetsVisible
? (count ? (count
? `${generated ? "Cornice generata dai dati importati" : "Layer del foglio importato visibile"} (${count} elementi).` ? `${sheetResult?.added ? "Fogli catastali ufficiali caricati" : "Layer dei fogli catastali visibile"} (${count} cornici).`
: "Nessun dato importato da cui ricavare la cornice del foglio.") : (sheetResult?.failed
? "Il servizio ufficiale dei fogli catastali non e' al momento disponibile. Riprova mostrando nuovamente il layer."
: "Nessuna particella con cui individuare il foglio catastale."))
: "Layer del foglio importato nascosto; le particelle restano visibili."); : "Layer del foglio importato nascosto; le particelle restano visibili.");
} }
function ensureImportedSheetOutline() { function removeLegacyGeneratedSheetOutlines() {
if (!lmeState.imported || !lmeState.importedSheets) { const category = layerManagerCategories().find(item => item.key === "importedSheets");
return false; if (!category) return 0;
} const generated = managedRecordsForCategory(category).filter(record =>
Boolean(record.layer?.feature?.properties?._lmeGeneratedSheetOutline));
const currentSheets = lmeState.importedSheets.toGeoJSON(); generated.forEach(record => {
const hasAreaOutline = (currentSheets.features || []).some(feature => record.parent?.removeLayer?.(record.layer);
["Polygon", "MultiPolygon"].includes(feature?.geometry?.type)); clearManagedObjectState(record.id);
if (hasAreaOutline) {
return false;
}
const imported = lmeState.imported.toGeoJSON();
const points = collectGeoJsonCoordinates(imported);
if (!points.length) {
return false;
}
const bounds = points.reduce((result, point) => ({
west: Math.min(result.west, point[0]),
south: Math.min(result.south, point[1]),
east: Math.max(result.east, point[0]),
north: Math.max(result.north, point[1])
}), { west: Infinity, south: Infinity, east: -Infinity, north: -Infinity });
if (!Number.isFinite(bounds.west)
|| !Number.isFinite(bounds.south)
|| bounds.east <= bounds.west
|| bounds.north <= bounds.south) {
return false;
}
const longitudePadding = Math.max((bounds.east - bounds.west) * 0.01, 0.000001);
const latitudePadding = Math.max((bounds.north - bounds.south) * 0.01, 0.000001);
const west = bounds.west - longitudePadding;
const south = bounds.south - latitudePadding;
const east = bounds.east + longitudePadding;
const north = bounds.north + latitudePadding;
addImportedSheetFeatures({
type: "FeatureCollection",
features: [{
type: "Feature",
properties: {
name: "Cornice del foglio importato",
_lmeGeneratedSheetOutline: true
},
geometry: {
type: "Polygon",
coordinates: [[
[west, south],
[east, south],
[east, north],
[west, north],
[west, south]
]]
}
}]
}); });
return true; return generated.length;
}
function cadastralSheetIdentity(feature, index) {
const properties = feature?.properties || {};
const explicit = properties.foglio ?? properties.FOGLIO ?? properties.sheet ?? properties.SHEET;
const administrativeUnit = String(properties.ADMINISTRATIVEUNIT || "").trim().toUpperCase();
if (String(explicit ?? "").trim()) {
return `${administrativeUnit}|${String(explicit).trim().replace(/^0+/, "") || "0"}`;
}
const context = [
properties.NATIONALCADASTRALREFERENCE,
properties.INSPIREID_LOCALID,
properties._lmeParcelReference,
properties._lmeSource,
properties._lmeFolder,
properties.name,
properties.Name
].filter(Boolean).join(" ").toUpperCase();
const namedSheet = context.match(/\bFOGLIO\s*[_ .-]*0*(\d+[A-Z]?)\b/i);
const codedSheet = context.match(/\b([A-Z]\d{3})[._-]([0-9]{4}[A-Z0-9]{2})(?=[._/-]|\b)/i);
if (namedSheet) return `${administrativeUnit}|${namedSheet[1]}`;
if (codedSheet) return `${codedSheet[1]}|${codedSheet[2]}`;
return `geometria-${index}`;
}
function sheetRepresentativePoint(feature) {
try {
return turf.pointOnFeature(feature).geometry.coordinates;
} catch {
const bounds = geoJsonBounds(feature?.geometry);
return bounds ? boundsCenter(bounds) : null;
}
}
function cadastralSheetFeatureKey(feature) {
const properties = feature?.properties || {};
return String(properties.NATIONALCADASTRALZONINGREFERENCE
|| properties.INSPIREID_LOCALID
|| properties.LABEL
|| JSON.stringify(feature?.geometry || {})).trim().toUpperCase();
}
async function ensureImportedSheetOutlines() {
if (!lmeState.imported || !lmeState.importedSheets) {
return { added: 0, failed: false };
}
removeLegacyGeneratedSheetOutlines();
const existingAreaSheets = layerManagerCategories()
.flatMap(category => managedRecordsForCategory(category))
.map(record => ({ categoryKey: record.categoryKey, feature: record.layer?.toGeoJSON?.() }))
.filter(item => ["Polygon", "MultiPolygon"].includes(item.feature?.geometry?.type)
&& !item.feature?.properties?._lmeGeneratedSheetOutline
&& (item.categoryKey === "importedSheets"
|| item.feature?.properties?._lmeOfficialSheet
|| item.feature?.properties?.NATIONALCADASTRALZONINGREFERENCE
|| isSheetOrOverlayFeature(item.feature)))
.map(item => item.feature);
const parcelFeatures = [
...(lmeState.imported.toGeoJSON()?.features || []),
...(lmeState.selectedParcelsLayer?.toGeoJSON?.()?.features || [])
].filter(feature => ["Polygon", "MultiPolygon"].includes(feature?.geometry?.type));
const representatives = new Map();
parcelFeatures.forEach((feature, index) => {
const identity = cadastralSheetIdentity(feature, index);
if (!representatives.has(identity)) representatives.set(identity, feature);
});
if (!representatives.size || !lmeState.dotNetReference) {
return { added: 0, failed: false };
}
const existingKeys = new Set(existingAreaSheets.map(cadastralSheetFeatureKey));
const officialSheets = new Map();
let failures = 0;
for (const [identity, parcelFeature] of representatives) {
const point = sheetRepresentativePoint(parcelFeature);
if (!point) continue;
const existingSheet = findContainingPolygon(point, {
type: "FeatureCollection",
features: [...existingAreaSheets, ...officialSheets.values()]
});
if (existingSheet) continue;
try {
const xml = await lmeState.dotNetReference.invokeMethodAsync(
"GetOfficialCadastralSheetsNear",
point[1],
point[0]);
const candidates = gmlParcelsToGeoJson(xml).features || [];
const containing = findContainingPolygon(point, { type: "FeatureCollection", features: candidates });
const sheet = containing || candidates[0];
if (!sheet) continue;
const key = cadastralSheetFeatureKey(sheet);
if (existingKeys.has(key) || officialSheets.has(key)) continue;
const reference = String(sheet.properties?.NATIONALCADASTRALZONINGREFERENCE
|| sheet.properties?.LABEL
|| identity.split("|").pop()
|| "").trim();
sheet.properties = {
...(sheet.properties || {}),
name: reference ? `Foglio catastale ${reference}` : "Foglio catastale",
foglio: reference,
_lmeSheetIdentity: identity,
_lmeOfficialSheet: true,
_lmeSource: reference ? `Foglio catastale ${reference}` : "Fogli catastali AdE",
_lmeGroupName: reference ? `Foglio ${reference}` : "Fogli catastali AdE"
};
officialSheets.set(key, sheet);
} catch {
failures++;
}
}
if (officialSheets.size) {
addImportedSheetFeatures({ type: "FeatureCollection", features: [...officialSheets.values()] });
applyImportedSheetVisibility();
refreshLayerManager();
finishMapChange(`${officialSheets.size} fogli catastali ufficiali caricati.`);
}
return { added: officialSheets.size, failed: failures > 0 && !officialSheets.size };
} }
function migrateMisclassifiedImportedSheets() { function migrateMisclassifiedImportedSheets() {
@@ -4334,13 +4675,17 @@ function loadProjectSnapshot(raw, projectName) {
lmeState.importedSheetsVisible = projectDisplayOptions lmeState.importedSheetsVisible = projectDisplayOptions
? Boolean(projectDisplayOptions.importedSheetsVisible) ? Boolean(projectDisplayOptions.importedSheetsVisible)
: data.schemaVersion >= 2 && Boolean(data.importedSheetsVisible); : data.schemaVersion >= 2 && Boolean(data.importedSheetsVisible);
if (lmeState.importedSheetsVisible) {
ensureImportedSheetOutline();
}
applyImportedSheetVisibility(); applyImportedSheetVisibility();
L.geoJSON(data.selectedParcels || emptyFeatureCollection(), { L.geoJSON(data.selectedParcels || emptyFeatureCollection(), {
pane: "selectedParcelsPane", pane: "selectedParcelsPane",
style: { color: "#ef4444", weight: 4, opacity: 1, fillColor: "#fbbf24", fillOpacity: 0.26 }, style: feature => ({
color: feature?.properties?._lmeColor || "#ef4444",
weight: Number(feature?.properties?._lmeWeight) || 4,
opacity: Number.isFinite(Number(feature?.properties?._lmeOpacity)) ? Number(feature.properties._lmeOpacity) : 1,
fillColor: feature?.properties?._lmeFillColor || "#fbbf24",
fillOpacity: Number.isFinite(Number(feature?.properties?._lmeFillOpacity)) ? Number(feature.properties._lmeFillOpacity) : 0.26,
dashArray: feature?.properties?._lmeDash || null
}),
onEachFeature: (feature, layer) => { onEachFeature: (feature, layer) => {
const properties = feature?.properties || {}; const properties = feature?.properties || {};
const reference = properties.NATIONALCADASTRALREFERENCE const reference = properties.NATIONALCADASTRALREFERENCE
@@ -4349,8 +4694,15 @@ function loadProjectSnapshot(raw, projectName) {
|| "Particella catastale"; || "Particella catastale";
layer.lmeParcelReference = reference; layer.lmeParcelReference = reference;
layer.bindPopup(`<strong>${escapeHtml(reference)}</strong>`); layer.bindPopup(`<strong>${escapeHtml(reference)}</strong>`);
applyStyleFromProperties(layer);
} }
}).addTo(lmeState.selectedParcelsLayer); }).addTo(lmeState.selectedParcelsLayer);
if (lmeState.importedSheetsVisible) {
void ensureImportedSheetOutlines().then(() => {
applyImportedSheetVisibility();
refreshLayerManager();
});
}
lmeState.gpsTrailPoints = Array.isArray(data.trail) ? data.trail : []; lmeState.gpsTrailPoints = Array.isArray(data.trail) ? data.trail : [];
lmeState.gpsTrailStartedAt = data.trailStartedAt || null; lmeState.gpsTrailStartedAt = data.trailStartedAt || null;
@@ -5334,7 +5686,16 @@ function parcelMemberToFeature(member) {
} }
const properties = {}; const properties = {};
["INSPIREID_LOCALID", "INSPIREID_NAMESPACE", "LABEL", "NATIONALCADASTRALREFERENCE", "ADMINISTRATIVEUNIT"].forEach(name => { [
"INSPIREID_LOCALID",
"INSPIREID_NAMESPACE",
"LABEL",
"NATIONALCADASTRALREFERENCE",
"NATIONALCADASTRALZONINGREFERENCE",
"LEVEL",
"LEVELNAME",
"ADMINISTRATIVEUNIT"
].forEach(name => {
const value = member.getElementsByTagNameNS("*", name)[0]?.textContent; const value = member.getElementsByTagNameNS("*", name)[0]?.textContent;
if (value) { if (value) {
properties[name] = value; properties[name] = value;