diff --git a/MaddoShared/ImageCreatorSharp.cs b/MaddoShared/ImageCreatorSharp.cs index 84a4c21..849d8c6 100644 --- a/MaddoShared/ImageCreatorSharp.cs +++ b/MaddoShared/ImageCreatorSharp.cs @@ -148,39 +148,36 @@ public class ImageCreatorSharp private void ExtractExif() { - using (var img = SixLabors.ImageSharp.Image.Load(_workFile.FullName)) + using var img = SixLabors.ImageSharp.Image.Load(_workFile.FullName); + _orientation = ExifReader.Orientations.TopLeft; + + IExifValue rotation = null; + + var found = img.Metadata?.ExifProfile?.TryGetValue(ExifTag.Orientation, out rotation) ?? false; + + if (found ) { - _orientation = ExifReader.Orientations.TopLeft; + var intOrientation = rotation.Value.ToInt32(); + _orientation = (ExifReader.Orientations)intOrientation; + } - IExifValue rotation = null; - - var found = img.Metadata?.ExifProfile?.TryGetValue(ExifTag.Orientation, out rotation) ?? false; - - if (found) + IExifValue date = null; + var creationFound = img.Metadata?.ExifProfile?.TryGetValue(ExifTag.DateTime, out date) ?? false; + if (creationFound) + { + var succ = DateTime.TryParse(date.ToString(), out var crDate); + if (succ) { - _orientation = (ExifReader.Orientations)rotation.ToInt32(); - } - - IExifValue date = null; - var creationFound = img.Metadata?.ExifProfile?.TryGetValue(ExifTag.DateTime, out date) ?? false; - if (creationFound) - { - var succ = DateTime.TryParse(date.ToString(), out var crDate); - if (succ) - { - _creationDate = crDate; - } - else - { - _creationDate = null; - } + _creationDate = crDate; } else { _creationDate = null; } - - + } + else + { + _creationDate = null; } } diff --git a/imagecatalog/Icon.png b/imagecatalog/Icon.png new file mode 100644 index 0000000..849b093 Binary files /dev/null and b/imagecatalog/Icon.png differ diff --git a/imagecatalog/ImageCatalog 2.csproj b/imagecatalog/ImageCatalog 2.csproj index 2e9cd55..572f666 100644 --- a/imagecatalog/ImageCatalog 2.csproj +++ b/imagecatalog/ImageCatalog 2.csproj @@ -10,6 +10,9 @@ 3.0.0.0 3.0.0-alpha.63+Branch.develop.Sha.39a9baf5c618d8d79c75b89e2d5c4020939697f2 3.0.0-alpha0063 + ImageCatalog2025 + default + Logo.ico true @@ -34,10 +37,10 @@ - + + + - - all diff --git a/imagecatalog/Logo.ico b/imagecatalog/Logo.ico new file mode 100644 index 0000000..e614e06 Binary files /dev/null and b/imagecatalog/Logo.ico differ diff --git a/imagecatalog/MainForm.cs b/imagecatalog/MainForm.cs index 371c014..f856f2a 100644 --- a/imagecatalog/MainForm.cs +++ b/imagecatalog/MainForm.cs @@ -8,6 +8,7 @@ using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; +using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; @@ -15,9 +16,9 @@ using CatalogVbLib; using ImageCatalog_2; using ImageCatalog_2.Services; using MaddoShared; +using Microsoft.Extensions.Logging; using Microsoft.VisualBasic; using Microsoft.VisualBasic.CompilerServices; -using Microsoft.WindowsAPICodePack.Dialogs; namespace ImageCatalog { @@ -25,22 +26,23 @@ namespace ImageCatalog public partial class MainForm { - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public DataModel Model { get; set; } private readonly ITestService _service; + private readonly ILogger _logger; - public MainForm(ITestService testService) + public MainForm(ITestService testService, ILogger logger) { _service = testService; - + _logger = logger; + + _logger.LogDebug("Start"); + InitializeComponent(); - - BindControls(); - + _Button3.Name = "Button3"; _Button2.Name = "Button2"; _Button8.Name = "Button8"; @@ -57,11 +59,10 @@ namespace ImageCatalog _btnCreaCatalogoAsync.Name = "btnCreaCatalogoAsync"; var version = Assembly.GetExecutingAssembly().GetName().Version; - _Label27.Text = $"Version: {version.Major}.{version.Minor}.{version.Build}.{version.Revision}"; + _Label27.Text = $"Version: {version.Major}.{version.Minor}.{version.Build}.{version.Revision}"; _results = new ConcurrentBag(); UiUpdateEvent += OnUiUpdateEvent; - } protected void BindControls() @@ -75,7 +76,6 @@ namespace ImageCatalog private void SetText(Label target, string text) { - if (InvokeRequired) { SetTextCallback d = new SetTextCallback(SetText); @@ -86,7 +86,9 @@ namespace ImageCatalog target.Text = text; } } + delegate void SetProgressCallback(ProgressBar target, int amount, int maximum); + private void SetProgress(ProgressBar target, int amount, int maximum) { if (InvokeRequired) @@ -100,6 +102,7 @@ namespace ImageCatalog target.Value = amount; } } + private void OnUiUpdateEvent(object sender, Tuple args) { SetProgress(ProgressBar1, _results.Count, args.Item2); @@ -194,31 +197,43 @@ namespace ImageCatalog ComboBox5.SelectedIndex = 2; } - [DllImport("kernel32.dll", SetLastError = true)] - private static extern bool AllocConsole(); private void Form1_Load(object sender, EventArgs e) { bindingSource1.DataSource = Model; Application.EnableVisualStyles(); setDefaults(); - /* TODO ERROR: Skipped IfDirectiveTrivia */ - AllocConsole(); - /* TODO ERROR: Skipped EndIfDirectiveTrivia */ - Console.WriteLine("Programma avviato"); + // /* TODO ERROR: Skipped IfDirectiveTrivia */ + // AllocConsole(); + // /* TODO ERROR: Skipped EndIfDirectiveTrivia */ + _logger.LogInformation("Programma Avviato"); + //Console.WriteLine("Programma avviato"); } private void FixPaths() { - if (Model.SourcePath.EndsWith(@"\") == false) + Model.SourcePath = FixPath(Model.SourcePath); + Model.DestinationPath = FixPath(Model.DestinationPath); + } + + private string FixPath(string path) + { + if (string.IsNullOrWhiteSpace(path)) { - Model.SourcePath += @"\"; + return string.Empty; } - if (Model.DestinationPath.EndsWith(@"\") == false) - { - Model.DestinationPath += @"\"; - } + // Trim leading/trailing quotes + path = path.Trim().Trim('"'); + + // Normalize directory separators + path = path.Replace('/', Path.DirectorySeparatorChar) + .Replace('\\', Path.DirectorySeparatorChar); + + // Remove trailing separators then add one back + path = path.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar; + + return path; } private void lockUI() @@ -241,6 +256,7 @@ namespace ImageCatalog private void btnCreaCatalogo_Click(object sender, EventArgs e) { + _logger.LogInformation("Avvio elaborazione..."); lockUI(); DateTime timeStart; var timeStop = default(DateTime); @@ -277,7 +293,7 @@ namespace ImageCatalog ContaImmaginiThread = 0; // creaImmaginiWithThreadMod(txtSorgente.Text, txtDestinazione.Text) - creaimmaginiWithThreadDict(Model.SourcePath, Model.DestinationPath); + CreaimmaginiWithThreadDict(Model.SourcePath, Model.DestinationPath); ThreadPoolWorkItem ThAttivo = null; int i = 0; /* TODO ERROR: Skipped DefineDirectiveTrivia */ @@ -354,26 +370,32 @@ namespace ImageCatalog double fotoSec = numFoto / (double)timediffS; double fotoMin = numFoto / (double)timediffM; double fotoOra = numFoto / (double)timediffH; - string s = "S: " + timediffS.ToString() + "; F/s: " + fotoSec.ToString("0.000"); // + " F/m: " + fotoMin.ToString("0.00") + " F/h: " + fotoOra.ToString("0.00") + string s = "S: " + timediffS.ToString() + "; F/s: " + + fotoSec.ToString( + "0.000"); // + " F/m: " + fotoMin.ToString("0.00") + " F/h: " + fotoOra.ToString("0.00") return s; } private string SelectFolder(string startingFolder) { - CommonOpenFileDialog dialog = new CommonOpenFileDialog - { - InitialDirectory = startingFolder, - IsFolderPicker = true - }; - if (dialog.ShowDialog() != CommonFileDialogResult.Ok) return null; - var directoryScelta = dialog.FileName; - if (directoryScelta.EndsWith(@"\") == false) - { - directoryScelta += @"\"; - } + var dialog = new FolderBrowserDialog(); + dialog.InitialDirectory = startingFolder; + if (dialog.ShowDialog() != DialogResult.OK) return string.Empty; + + // CommonOpenFileDialog dialog = new CommonOpenFileDialog + // { + // InitialDirectory = startingFolder, + // IsFolderPicker = true + // }; + // if (dialog.ShowDialog() != CommonFileDialogResult.Ok) return null; + var directoryScelta = FixPath(dialog.SelectedPath); // dialog.FileName; + + // if (directoryScelta.EndsWith(@"\") == false) + // { + // directoryScelta += @"\"; + // } return directoryScelta; - } private void Button2_Click(object sender, EventArgs e) @@ -624,12 +646,14 @@ namespace ImageCatalog if (PictureBox1.Image.Height >= PictureBox1.Image.Width) { PictureBox1.Height = 160; - PictureBox1.Width = Conversions.ToInteger(160 * PictureBox1.Image.Width / (double)PictureBox1.Image.Height); + PictureBox1.Width = + Conversions.ToInteger(160 * PictureBox1.Image.Width / (double)PictureBox1.Image.Height); } else { PictureBox1.Width = 224; - PictureBox1.Height = Conversions.ToInteger(224 * PictureBox1.Image.Height / (double)PictureBox1.Image.Width); + PictureBox1.Height = + Conversions.ToInteger(224 * PictureBox1.Image.Height / (double)PictureBox1.Image.Width); } } @@ -638,7 +662,6 @@ namespace ImageCatalog // 2021 TextBox8.Text = Module1.SetupIni.LeggiParametroString("ChunkSize"); TextBox7.Text = Module1.SetupIni.LeggiParametroString("ThreadsCount"); - } } @@ -860,7 +883,9 @@ namespace ImageCatalog TestoTemp = (ContaDirXDir * NumFileXDir).ToString(); } - for (int ContaTemp = 1, loopTo = NumCifreDir - TestoTemp.Length; ContaTemp <= loopTo; ContaTemp++) + for (int ContaTemp = 1, loopTo = NumCifreDir - TestoTemp.Length; + ContaTemp <= loopTo; + ContaTemp++) TestoTemp = "0" + TestoTemp; DestDir = new DirectoryInfo(Path.Combine(DestDirStart.FullName, SuffixDir, TestoTemp)); // DestDir = New DirectoryInfo(DestDirStart.FullName & IIf(Not DestDirStart.FullName.EndsWith("\"), "\", String.Empty).ToString & SuffixDir & TestoTemp) @@ -1065,7 +1090,6 @@ namespace ImageCatalog // Application.DoEvents() - var ClsCreaImmagine = new ImageCreatorSharp(childFile.Name, SourceDir, DestDir, DestDirStart); // ClsCreaImmagine.NomeFileChild = childFile.Name // ClsCreaImmagine.DestDir = DestDir @@ -1075,6 +1099,7 @@ namespace ImageCatalog ContaImmaginiThread += 1; //MyPool.InsertWorkItem(childFile.Name, new XyThreadAdd((_) => ClsCreaImmagine.CreaImmagineThread()), new object[1] { childFile.Name }, true); } + // copy all the sub-directories by recursively calling this same routine if (chkAggiornaSottodirectory.Checked == true) { @@ -1114,20 +1139,20 @@ namespace ImageCatalog return numerazioneType; } - private void creaimmaginiWithThreadDict(string SourcePath, string DestPath) + private void CreaimmaginiWithThreadDict(string SourcePath, string DestPath) { var dirSourceDest = new Dictionary(); if (chkAggiornaSottodirectory.Checked & chkCreaSottocartelle.Checked) { - var helper = new FileHelper(Conversions.ToInteger(txtFilePerCartella.Text), txtSuffissoCartelle.Text, Conversions.ToInteger(txtCifreContatore.Text), getNumerazione()); + var helper = new FileHelper(Conversions.ToInteger(txtFilePerCartella.Text), txtSuffissoCartelle.Text, + Conversions.ToInteger(txtCifreContatore.Text), getNumerazione()); // getfilesrecursive - dirSourceDest = helper.GetFilesRecursive(new DirectoryInfo(SourcePath), new DirectoryInfo(DestPath), "*.jpg"); + dirSourceDest = + helper.GetFilesRecursive(new DirectoryInfo(SourcePath), new DirectoryInfo(DestPath), "*.jpg"); } else if (chkAggiornaSottodirectory.Checked & !chkCreaSottocartelle.Checked) { - // = getDirsDict(SourcePath, DestPath) - } foreach (var pair in dirSourceDest) @@ -1307,8 +1332,10 @@ namespace ImageCatalog ClsCreaImmagine.jpegQuality = Conversions.ToLong(TextBox32.Text); ClsCreaImmagine.jpegQualityMin = Conversions.ToLong(TextBox33.Text); ContaImmaginiThread += 1; - MyPool.InsertWorkItem(childFile.Name, new XyThreadAdd(ClsCreaImmagine.CreaImmagineThread), new object[1] { childFile.Name }, true); + MyPool.InsertWorkItem(childFile.Name, new XyThreadAdd(ClsCreaImmagine.CreaImmagineThread), + new object[1] { childFile.Name }, true); } + // copy all the sub-directories by recursively calling this same routine if (chkAggiornaSottodirectory.Checked == true) { @@ -1374,7 +1401,8 @@ namespace ImageCatalog tempMultiplier = MaxPixel / (double)currentwidth; } - var NewSize = new Size((int)Math.Round(currentwidth * tempMultiplier), (int)Math.Round(currentheight * tempMultiplier)); + var NewSize = new Size((int)Math.Round(currentwidth * tempMultiplier), + (int)Math.Round(currentheight * tempMultiplier)); return NewSize; } @@ -1382,10 +1410,16 @@ namespace ImageCatalog { StopAttivo = true; //MyPool.StopThreadPool(); - - if (_mainToken != null) + try { - _mainToken.Cancel(); + _mainToken?.Cancel(); + } + catch (Exception exception) + { + _logger.LogError(exception.Message); + _logger.LogInformation("Ignora questo errore"); + // Console.WriteLine(exception); + // Console.WriteLine("Ignora questo errore"); } unlockUI(); @@ -1411,12 +1445,14 @@ namespace ImageCatalog if (PictureBox1.Image.Height >= PictureBox1.Image.Width) { PictureBox1.Height = 160; - PictureBox1.Width = Conversions.ToInteger(160 * PictureBox1.Image.Width / (double)PictureBox1.Image.Height); + PictureBox1.Width = + Conversions.ToInteger(160 * PictureBox1.Image.Width / (double)PictureBox1.Image.Height); } else { PictureBox1.Width = 224; - PictureBox1.Height = Conversions.ToInteger(224 * PictureBox1.Image.Height / (double)PictureBox1.Image.Width); + PictureBox1.Height = + Conversions.ToInteger(224 * PictureBox1.Image.Height / (double)PictureBox1.Image.Width); } } } @@ -1438,7 +1474,6 @@ namespace ImageCatalog { // GetColor() // GetPixelColor(PictureBox1.PointToScreen(e.Location)).ToArgb.ToString("X8") - } private void PictureBox1_MouseUp(object sender, MouseEventArgs e) @@ -1534,14 +1569,14 @@ namespace ImageCatalog { } - private CancellationTokenSource _mainToken; + private CancellationTokenSource? _mainToken; private async void Button1_Click(object sender, EventArgs e) { lockUI(); // Dim timeStart As Date // Dim timeStop As Date - + _mainToken?.Dispose(); _mainToken = new CancellationTokenSource(); var token = _mainToken.Token; @@ -1572,7 +1607,6 @@ namespace ImageCatalog imageCreationOptions.ChunksSize = Conversions.ToInteger(TextBox8.Text); imageCreationOptions.LinearExecution = rdbVecchioMetodo.Checked; - try { @@ -1590,20 +1624,24 @@ namespace ImageCatalog } catch (OperationCanceledException operationCanceledException) { - Console.WriteLine("Operazione cancellata"); + _logger.LogInformation("Operazione Cancellata"); + //Console.WriteLine("Operazione cancellata"); } finally { - _mainToken.Dispose(); - + _mainToken?.Dispose(); + _mainToken = null; + timer1.Tick -= Timer1OnTick; } + Label10.Text = "Finito"; unlockUI(); } private int _currentAmount = 0; private int _previousAmount = 0; + private void Timer1OnTick(object sender, EventArgs e) { _previousAmount = _currentAmount; @@ -1618,7 +1656,6 @@ namespace ImageCatalog } - private async Task CreaCatalogoParallel() { var timeStart = DateAndTime.TimeOfDay; @@ -1723,7 +1760,8 @@ namespace ImageCatalog public DirectoryInfo DirSource, DirDest, DirDestStart; public string NomeImmagine; - public PicInfo(DirectoryInfo Dir_Source, DirectoryInfo Dir_Dest, DirectoryInfo Dir_DestStart, string Nome_Immagine) + public PicInfo(DirectoryInfo Dir_Source, DirectoryInfo Dir_Dest, DirectoryInfo Dir_DestStart, + string Nome_Immagine) { DirSource = Dir_Source; DirDest = Dir_Dest; diff --git a/imagecatalog/Program.cs b/imagecatalog/Program.cs index 7cd5ffb..08949f6 100644 --- a/imagecatalog/Program.cs +++ b/imagecatalog/Program.cs @@ -1,11 +1,54 @@ -using ImageCatalog; +using System.Runtime.InteropServices; +using ImageCatalog; using ImageCatalog_2.Services; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; namespace ImageCatalog_2 { static class Program { + [DllImport("kernel32.dll", SetLastError = true)] + private static extern bool AllocConsole(); + + [DllImport("kernel32.dll", SetLastError = true)] + static extern IntPtr GetStdHandle(int nStdHandle); + + private const int STD_OUTPUT_HANDLE = -11; + private const int STD_ERROR_HANDLE = -12; + + [DllImport("kernel32.dll", SetLastError = true)] + static extern bool SetStdHandle(int nStdHandle, IntPtr handle); + + [DllImport("kernel32.dll", SetLastError = true)] + static extern IntPtr GetConsoleWindow(); + + [DllImport("kernel32.dll", SetLastError = true)] + static extern bool AttachConsole(int dwProcessId); + + [DllImport("kernel32.dll", SetLastError = true)] + static extern IntPtr CreateFile( + string lpFileName, + uint dwDesiredAccess, + uint dwShareMode, + IntPtr lpSecurityAttributes, + uint dwCreationDisposition, + uint dwFlagsAndAttributes, + IntPtr hTemplateFile); + + private const uint GENERIC_WRITE = 0x40000000; + private const uint OPEN_EXISTING = 3; + + private static void RedirectConsoleOutput() + { + var stdOutHandle = CreateFile("CONOUT$", GENERIC_WRITE, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero); + var safeFileHandle = new Microsoft.Win32.SafeHandles.SafeFileHandle(stdOutHandle, true); + var fileStream = new FileStream(safeFileHandle, FileAccess.Write); + var standardOutput = new StreamWriter(fileStream) { AutoFlush = true }; + Console.SetOut(standardOutput); + Console.SetError(standardOutput); + } + public static IServiceProvider ServiceProvider { get; private set; } [STAThread] static void Main() @@ -14,6 +57,9 @@ namespace ImageCatalog_2 Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); + AllocConsole(); + RedirectConsoleOutput(); + var serviceCollection = new ServiceCollection(); ConfigureServices(serviceCollection); @@ -36,6 +82,12 @@ namespace ImageCatalog_2 // Register your forms services.AddTransient(); + + services.AddLogging(configure => + { + configure.AddConsole(); + configure.SetMinimumLevel(LogLevel.Debug); + }); } } }