Пример #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;
            }

            // Validate parameters:

            bool PromptOverwriteExistingOutputFile(string path)
            {
                var promptResult = MessageBox.Show(this,
                                                   $"The file '{path}' already exists. Do you want to overwrite it?",
                                                   "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                return(promptResult == DialogResult.Yes);
            }

            CompleteBarCodeGenerationParameters parameters;

            try
            {
                parameters = _barCodeParametersValidator.GetValidatedParameters(
                    rawInputPath: inputPathTextBox.Text,
                    rawOutputPath: outputPathTextBox.Text,
                    rawBarWidth: barWidthTextBox.Text,
                    rawImageWidth: imageWidthTextBox.Text,
                    rawImageHeight: imageHeightTextBox.Text,
                    useInputHeightForOutput: useInputHeightForOutputCheckBox.Checked,
                    generateSmoothVersion: smoothCheckBox.Checked,
                    shouldOverwriteOutput: PromptOverwriteExistingOutputFile);
            }
            catch (OperationCanceledException)
            {
                return;
            }
            catch (Exception ex)
            {
                AppendLog("Error validating input parameters. " + ex.ToString());
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            AppendLog($@"Barcode generation starting...
Input: {parameters.InputPath}
Output: {parameters.OutputPath}
Output width: {parameters.BarCode.Width}
Output height: {parameters.BarCode.Height}
Bar width: {parameters.BarCode.BarWidth}");

            // 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(
                        parameters.InputPath,
                        parameters.BarCode,
                        _ffmpegWrapper,
                        _cancellationTokenSource.Token,
                        progress,
                        AppendLog);
                }, _cancellationTokenSource.Token);
            }
            catch (OperationCanceledException)
            {
                AppendLog("Operation cancelled.");
                return;
            }
            catch (Exception ex)
            {
                AppendLog("Error: " + ex.ToString());
                MessageBox.Show(this, "Sorry, something went wrong. See the log for more info.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            finally
            {
                generateButton.Text = GenerateButtonText;
                _cancellationTokenSource?.Dispose();
                _cancellationTokenSource = null;
            }

            if (cancellationLocalRef.IsCancellationRequested)
            {
                AppendLog("Operation cancelled.");
                return;
            }

            // Save the barcode:

            AppendLog("Saving the image...");

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

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

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

            AppendLog("Barcode generated successfully!");
        }
        private void DealWithOneInputFile(RawArguments arguments)
        {
            Console.WriteLine($"Processing file '{arguments.RawInput}':");

            CompleteBarCodeGenerationParameters parameters;

            try
            {
                parameters = _barCodeParametersValidator.GetValidatedParameters(
                    rawInputPath: arguments.RawInput,
                    rawOutputPath: arguments.RawOutput,
                    rawBarWidth: arguments.RawBarWidth,
                    rawImageWidth: arguments.RawWidth,
                    rawImageHeight: arguments.RawHeight,
                    useInputHeightForOutput: arguments.UseInputHeight,
                    generateSmoothVersion: arguments.Smooth,
                    // Choosing whether to overwrite or not is done after validating parameters, not here
                    shouldOverwriteOutput: x => true);
            }
            catch (ParameterValidationException ex)
            {
                Console.Error.WriteLine($"Invalid parameters: {ex.Message}");
                return;
            }

            if (File.Exists(parameters.OutputPath) && arguments.Overwrite == false)
            {
                // Check once before generating the image, and once just before saving.
                Console.WriteLine($"WARNING: skipped file {parameters.OutputPath} because it already exists.");
                return;
            }

            var result = _imageProcessor.CreateBarCode(
                parameters.InputPath,
                parameters.BarCode,
                _ffmpegWrapper,
                CancellationToken.None,
                null,
                x => Console.WriteLine(x));

            try
            {
                if (File.Exists(parameters.OutputPath) && arguments.Overwrite == false)
                {
                    // Check once before generating the image, and once just before saving.
                    Console.WriteLine($"WARNING: skipped file {parameters.OutputPath} because it already exists.");
                }
                else
                {
                    result.Save(parameters.OutputPath);
                    Console.WriteLine($"File {parameters.OutputPath} saved successfully!");
                }
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine($"Unable to save the image: {ex}");
            }

            if (parameters.GenerateSmoothedOutput)
            {
                Bitmap smoothed;
                try
                {
                    smoothed = _imageProcessor.GetSmoothedCopy(result);

                    try
                    {
                        if (File.Exists(parameters.OutputPath) && arguments.Overwrite == false)
                        {
                            Console.WriteLine($"WARNING: skipped file {parameters.OutputPath} because it already exists.");
                        }
                        else
                        {
                            smoothed.Save(parameters.SmoothedOutputPath);
                            Console.WriteLine($"File {parameters.SmoothedOutputPath} saved successfully!");
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.Error.WriteLine($"Unable to save the smoothed image: {ex}");
                    }
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine($"An error occured while creating the smoothed version of the barcode. Error: {ex}");
                }
            }
        }
Пример #3
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;
            TaskbarProgress.SetState(Handle, TaskbarProgress.TaskbarStates.NoProgress);
            return;
        }

        // Validate parameters:

        bool PromptOverwriteExistingOutputFile(IReadOnlyCollection <string> paths)
        {
            var promptResult = MessageBox.Show(this,
                                               $"The following files already exist: '{string.Join(", ", paths.Select(x => $"'{x}'"))}'. Do you want to overwrite them?",
                                               "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            return(promptResult == DialogResult.Yes);
        }

        var generators =
            _barGenerators
            .Where(x => x.Checked)
            .Select(x => x.Generator)
            .ToArray();

        if (generators.Any() == false)
        {
            TaskbarProgress.SetState(Handle, TaskbarProgress.TaskbarStates.Error);
            MessageBox.Show(this, "At least one barcode version must be selected.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return;
        }

        BarCodeParameters parameters;

        try
        {
            parameters = _barCodeParametersValidator.GetValidatedParameters(
                rawInputPath: inputPathTextBox.Text,
                rawBaseOutputPath: outputPathTextBox.Text,
                rawBarWidth: barWidthTextBox.Text,
                rawImageWidth: imageWidthTextBox.Text,
                rawImageHeight: imageHeightTextBox.Text,
                useInputHeightForOutput: useInputHeightForOutputCheckBox.Checked,
                shouldOverwriteOutputPaths: PromptOverwriteExistingOutputFile,
                barGenerators: generators);
        }
        catch (OperationCanceledException)
        {
            TaskbarProgress.SetState(Handle, TaskbarProgress.TaskbarStates.NoProgress);
            return;
        }
        catch (Exception ex)
        {
            AppendLog("Error validating input parameters. " + ex.ToString());
            TaskbarProgress.SetState(Handle, TaskbarProgress.TaskbarStates.Error);
            MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            return;
        }

        AppendLog($@"Barcode generation starting...
Input: '{parameters.InputPath}'
Output: {string.Join(", ", parameters.GeneratorOutputPaths.Select(x => $"'{x.Value}'"))}
Output width: {parameters.Width}
Output height: {parameters.Height}
Bar width: {parameters.BarWidth}");

        // 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;
                    TaskbarProgress.SetValue(Handle, progressBarValue, 100);
                }
            }));
        });

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

        // Actually create the barcode:

        IReadOnlyDictionary <IBarGenerator, 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.CreateBarCodes(
                    parameters,
                    _ffmpegWrapper,
                    _cancellationTokenSource.Token,
                    progress,
                    AppendLog);
            }, _cancellationTokenSource.Token);
        }
        catch (OperationCanceledException)
        {
            AppendLog("Operation cancelled.");
            TaskbarProgress.SetState(Handle, TaskbarProgress.TaskbarStates.NoProgress);
            return;
        }
        catch (Exception ex)
        {
            AppendLog("Error: " + ex.ToString());
            TaskbarProgress.SetState(Handle, TaskbarProgress.TaskbarStates.Error);
            MessageBox.Show(this, "Sorry, something went wrong. See the log for more information.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return;
        }
        finally
        {
            generateButton.Text = GenerateButtonText;
            _cancellationTokenSource?.Dispose();
            _cancellationTokenSource = null;
        }

        if (cancellationLocalRef.IsCancellationRequested)
        {
            AppendLog("Operation cancelled.");
            TaskbarProgress.SetState(Handle, TaskbarProgress.TaskbarStates.NoProgress);
            return;
        }

        // Save the barcode:

        AppendLog("Saving the images...");

        try
        {
            foreach (var barcode in result)
            {
                var outputPath = parameters.GeneratorOutputPaths[barcode.Key];
                barcode.Value.Save(outputPath);
            }
        }
        catch (Exception ex)
        {
            var message = $"Unable to save the images: {ex}";
            AppendLog(message);
            TaskbarProgress.SetState(Handle, TaskbarProgress.TaskbarStates.Error);
            MessageBox.Show(this, message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        AppendLog("Barcode generated successfully!");
        TaskbarProgress.SetState(Handle, TaskbarProgress.TaskbarStates.NoProgress);
    }