Example #1
0
        private async void generateButton_Click(object sender, EventArgs e)
        {
            if (_cancellationTokenSource != null)
            {
                _cancellationTokenSource.Cancel();
                _cancellationTokenSource.Dispose();
                _cancellationTokenSource = null;
                generateButton.Text      = GenerateButtonText;
                progressBar1.Value       = progressBar1.Minimum;
                return;
            }

            #region Validate Params
            try
            {
                ValidateParams();
            }
            catch (OperationCanceledException)
            {
                return;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            #endregion

            #region Loop through files, Send to ffmpeg
            var files = Directory.GetFiles(SettingsHandler.SourceDir)
                        .Where(f => validMovieExtensions
                               .Any(ext => f.EndsWith(ext)))
                        //.Select(f => Path.GetFileName(f))
                        .ToArray();
            //MessageBox.Show(this, $" Will operate on: {files.Length} files", "Debug", MessageBoxButtons.OK, MessageBoxIcon.Information);


            // Actually create the barcode:

            fileCountProgress.Visible = true;
            for (int i = 0; i < files.Length; i++)
            {
                // Register progression callback and ready cancellation source:
                fileCountProgress.Text = $"processing {i} of {files.Length} images";
                var progress = new PercentageProgressHandler(percentage =>
                {
                    var progressBarValue = Math.Min(100, (int)Math.Round(percentage * 100, MidpointRounding.AwayFromZero));
                    Invoke(new Action(() =>
                    {
                        if (_cancellationTokenSource != null)
                        {
                            progressBar1.Value = progressBarValue;
                        }
                    }));
                });

                _cancellationTokenSource = new CancellationTokenSource();
                var cancellationLocalRef = _cancellationTokenSource;

                string outputFile = Path.Combine(SettingsHandler.OutputDir, Path.GetFileName(files[i]));
                if (!Directory.Exists(Path.GetDirectoryName(outputFile)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(outputFile));
                }
                outputFile = Path.ChangeExtension(outputFile, "png");

                //MessageBox.Show(this,
                //    $" Source Fie: {files[i]}, " +
                //    $"Target File: {outputFile} ",
                //    "Debug", MessageBoxButtons.OK, MessageBoxIcon.Information);



                Bitmap result    = null;
                string audioFile = string.Empty;
                try
                {
                    generateButton.Text    = CancelButtonText;
                    generateButton.Enabled = false;
                    // Prevent the user from cancelling for 1sec (it might not be obvious the generation has started)
                    var dontCare = Task.Delay(1000).ContinueWith(t =>
                    {
                        try
                        {
                            Invoke(new Action(() => generateButton.Enabled = true));
                        }
                        catch { }
                    });

                    await Task.Run(() =>
                    {
                        (result, audioFile) = _imageProcessor.CreateBarCode(files[i], _ffmpegWrapper, _cancellationTokenSource.Token, progress);

                        var args = $"-file \"{audioFile}\" -chunk {SettingsHandler.ChunkSize}";
                        AudioProcessor.ProcessAudio(args, _cancellationTokenSource.Token);
                    }, _cancellationTokenSource.Token);

                    //await Task.Run(() =>
                    //{
                    //    var args = $"-file {audioFile} -chunk {SettingsHandler.ChunkSize}";
                    //    AudioProcessor.ProcessAudio(args, _cancellationTokenSource.Token);
                    //}, _cancellationTokenSource.Token);
                }
                catch (OperationCanceledException)
                {
                    return;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this,
                                    $@"Sorry, something went wrong. Here is all the info available at the time of the error (press Ctrl+C to copy it).
                            Input: {files[i]}
                            Output width: {SettingsHandler.ImageWidth}
                            Output height: {SettingsHandler.ImageHeight}
                            Bar width: {SettingsHandler.BarWidth}
                            Error: {ex}",
                                    "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                finally
                {
                    generateButton.Text = GenerateButtonText;
                    _cancellationTokenSource?.Dispose();
                    _cancellationTokenSource = null;
                }

                if (cancellationLocalRef.IsCancellationRequested)
                {
                    return;
                }

                // Save the barcode:

                try
                {
                    // for some reason this app is now hanging if files already exist
                    if (File.Exists(outputFile))
                    {
                        File.Delete(outputFile);
                    }
                    result.Save(outputFile, System.Drawing.Imaging.ImageFormat.Png);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, $" Unable to save the image: {ex}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                if (SettingsHandler.ShouldCreateSmoothDuplicate)
                {
                    Bitmap smoothed;
                    try
                    {
                        smoothed = _imageProcessor.GetSmoothedCopy(result);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, $"An error occured while creating the smoothed version of the barcode. Error: {ex}",
                                        "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    try
                    {
                        var outFile = outputFile.Replace(".png", "_smoothed.png");
                        if (File.Exists(outFile))
                        {
                            File.Delete(outFile);
                        }
                        smoothed.Save(outputFile.Replace(".png", "_smoothed.png"), System.Drawing.Imaging.ImageFormat.Png);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, $" Unable to save the smoothed image: {ex}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            fileCountProgress.Text = $"finished processing {files.Length} images";
            #endregion
        }
        private async void generateButton_Click(object sender, EventArgs e)
        {
            if (_cancellationTokenSource != null)
            {
                _cancellationTokenSource.Cancel();
                _cancellationTokenSource.Dispose();
                _cancellationTokenSource = null;
                generateButton.Text      = GenerateButtonText;
                progressBar1.Value       = progressBar1.Minimum;
                return;
            }

            // Validate parameters:

            string            inputPath;
            string            outputPath;
            string            smoothedOutputPath;
            BarCodeParameters parameters;

            try
            {
                (inputPath, outputPath, smoothedOutputPath, parameters) = GetValidatedParameters();
            }
            catch (OperationCanceledException)
            {
                return;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            // Register progression callback and ready cancellation source:

            var progress = new PercentageProgressHandler(percentage =>
            {
                var progressBarValue = Math.Min(100, (int)Math.Round(percentage * 100, MidpointRounding.AwayFromZero));
                Invoke(new Action(() =>
                {
                    if (_cancellationTokenSource != null)
                    {
                        progressBar1.Value = progressBarValue;
                    }
                }));
            });

            _cancellationTokenSource = new CancellationTokenSource();
            var cancellationLocalRef = _cancellationTokenSource;

            // Actually create the barcode:

            Bitmap result = null;

            try
            {
                generateButton.Text    = CancelButtonText;
                generateButton.Enabled = false;
                // Prevent the user from cancelling for 1sec (it might not be obvious the generation has started)
                var dontCare = Task.Delay(1000).ContinueWith(t =>
                {
                    try
                    {
                        Invoke(new Action(() => generateButton.Enabled = true));
                    }
                    catch { }
                });

                await Task.Run(() =>
                {
                    result = _imageProcessor.CreateBarCode(inputPath, parameters, _ffmpegWrapper, _cancellationTokenSource.Token, progress);
                }, _cancellationTokenSource.Token);
            }
            catch (OperationCanceledException)
            {
                return;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this,
                                $@"Sorry, something went wrong.
Here is all the info available at the time of the error (press Ctrl+C to copy it).

Input: {inputPath}
Output width: {parameters.Width}
Output height: {parameters.Height}
Bar width: {parameters.BarWidth}
Error: {ex}",
                                "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            finally
            {
                generateButton.Text = GenerateButtonText;
                _cancellationTokenSource?.Dispose();
                _cancellationTokenSource = null;
            }

            if (cancellationLocalRef.IsCancellationRequested)
            {
                return;
            }

            // Save the barcode:

            try
            {
                result.Save(outputPath);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, $" Unable to save the image: {ex}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            if (smoothedOutputPath != null)
            {
                Bitmap smoothed;
                try
                {
                    smoothed = _imageProcessor.GetSmoothedCopy(result);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, $"An error occured while creating the smoothed version of the barcode. Error: {ex}",
                                    "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                try
                {
                    smoothed.Save(smoothedOutputPath);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, $" Unable to save the smoothed image: {ex}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }