-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMainWindow.axaml.cs
292 lines (248 loc) · 9.94 KB
/
MainWindow.axaml.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Platform.Storage;
using Avalonia.Threading;
using GUI.Classes;
using Core;
using GUI.Dialogs;
namespace GUI;
public partial class MainWindow : Window, IOptionsConfirmation
{
private List<ImageToConvert> _imagesList = new();
private uint _imageIndex;
private readonly List<CultureInfo> _cultures;
private bool _confirmCopy;
private bool _deleteOriginal;
private bool _dontAsk;
private OverwriteOptionsEnum _overwriteOptions;
private Task<(OverwriteOptionsEnum, bool)?>? _showDialog;
public MainWindow()
{
InitializeComponent();
ParallelProcessesNumericUpDown.Value = ParallelProcessesNumericUpDown.Maximum = Environment.ProcessorCount;
ImagesToConvertDataGrid.ItemsSource = _imagesList;
AddHandler(DragDrop.DropEvent, DropFiles);
// Set language
_cultures = new List<CultureInfo> { CultureInfo.GetCultureInfo("en"), CultureInfo.GetCultureInfo("es") };
List<string> languages = new();
var tempIndex = 0;
for (var i = 0; i < _cultures.Count; i++)
{
var culture = _cultures[i];
languages.Add(culture.DisplayName);
if (culture.TwoLetterISOLanguageName == CultureInfo.CurrentCulture.TwoLetterISOLanguageName)
tempIndex = i;
}
LanguageComboBox.ItemsSource = languages;
LanguageComboBox.SelectedIndex = tempIndex;
LanguageComboBox.SelectionChanged += LanguageComboBox_OnSelectionChanged;
}
private async void AddFilesButton_OnClick(object? sender, RoutedEventArgs e)
{
// Show file picker dialog
FilePickerFileType filter = new("Images")
{
Patterns = new[] { "*.png", "*.jpg", "*.jpeg", "*.gif", "*.bmp", "*.pbm", "*.pgm", "*.ppm", "*tga", "*.tiff", "*.webp" }
};
var files = await StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
{
Title = "Select images to convert to QOI",
AllowMultiple = true,
FileTypeFilter = new[] { filter }
});
if (files.Count < 1) return;
// Check if the user selected GIF images
if (files.Any(file => Path.GetExtension(file.Path.LocalPath).EndsWith("gif")))
{
var confirmDialog = new ConfirmDialog(Assets.Resources.GIF_files_confirmation);
var a = await confirmDialog.ShowDialog<bool?>(this);
switch (a)
{
case true:
files = files.Where(file => !Path.GetExtension(file.Path.AbsolutePath).EndsWith("gif")).ToList();
break;
case null:
return;
}
}
// Add selected files to list
foreach (var file in files)
_imagesList.Add(new ImageToConvert(file.Path.AbsolutePath, _imageIndex++));
ValidateFilesList();
}
private void ValidateFilesList()
{
if (_imagesList.Any())
{
// Show data grid and re-bind items
ImagesToConvertPlaceHolder.IsVisible = false;
ImagesToConvertDataGrid.ItemsSource = null;
ImagesToConvertDataGrid.ItemsSource = _imagesList;
ImagesToConvertDataGrid.IsVisible = StartConversionButton.IsEnabled = true;
if(StartImmediatelyCheckBox.IsChecked ?? false)
ConvertImagesInList();
}
else
{
// Hide data grid
ImagesToConvertPlaceHolder.IsVisible = true;
ImagesToConvertDataGrid.IsVisible = StartConversionButton.IsEnabled = false;
}
}
private void ClearListButton_OnClick(object? sender, RoutedEventArgs e)
{
if ((sender as Button)!.CommandParameter is null) // Clears list
_imagesList.Clear();
else // Removes only correctly converted files
_imagesList = _imagesList.Where(image => image.State != ConversionStateEnum.Correct).ToList();
ValidateFilesList();
}
private async void DropFiles(object? sender, DragEventArgs e)
{
var data = e.Data;
// Checks if the user dropped files correctly
if (!data.Contains(DataFormats.Files)) return;
var files = data.GetFiles();
if (files is null) return;
List<string> paths = files.Select(file => file.Path.LocalPath).ToList();
// Add selected files to list
for (var i = 0; i < paths.Count; i++)
{
var path = paths[i];
if (File.GetAttributes(path).HasFlag(FileAttributes.Directory))
{
var confirmDialog = new ConfirmDialog(Assets.Resources.Directory_confirmation);
var a = await confirmDialog.ShowDialog<bool?>(this);
switch (a)
{
case true:
paths.AddRange(Directory.GetFiles(path));
continue;
case false:
continue;
case null:
return;
}
}
_imagesList.Add(new ImageToConvert(path, _imageIndex++));
}
ValidateFilesList();
}
private void StartConversionButton_OnClick(object? sender, RoutedEventArgs e) => ConvertImagesInList();
private void ConvertImagesInList()
{
var imagesToProcess = _imagesList.Where(img => img.State != ConversionStateEnum.Correct).ToList();
if (!imagesToProcess.Any()) return;
StartConversionButton.Content = "Working,,,";
StartConversionButton.IsEnabled = false;
_confirmCopy = CopyAttributesCheckBox.IsChecked ?? true;
_deleteOriginal = DeleteOriginalCheckBox.IsChecked ?? false;
var processedImages = 0;
// Get the current settings.
ThreadPool.GetMinThreads(out _, out var minIoc);
ThreadPool.SetMaxThreads((int)(ParallelProcessesNumericUpDown.Value ?? 1), minIoc);
foreach (var image in imagesToProcess)
{
image.State = ConversionStateEnum.Waiting;
ThreadPool.QueueUserWorkItem((data) =>
{
Convert(image);
processedImages++;
Dispatcher.UIThread.Post(() =>
{
ImagesToConvertDataGrid.ItemsSource = null;
ImagesToConvertDataGrid.ItemsSource = _imagesList;
if (processedImages < imagesToProcess.Count) return;
StartConversionButton.Content = "Start conversion";
StartConversionButton.IsEnabled = true;
});
});
}
ImagesToConvertDataGrid.ItemsSource = null;
ImagesToConvertDataGrid.ItemsSource = _imagesList;
_dontAsk = false;
}
private void Convert(object? data)
{
if(data is not ImageToConvert image) return;
// TODO: Check if file is an image
image.State = ConversionStateEnum.Working;
if(Converter.ConvertToQoi(this, image.FilePath))
image.State = ConversionStateEnum.Correct;
else
{
image.State = ConversionStateEnum.Error;
image.ToolTipMessage = "There was an error during conversion";
}
}
private void LanguageComboBox_OnSelectionChanged(object? sender, SelectionChangedEventArgs e)
{
Assets.Resources.Culture = _cultures[LanguageComboBox.SelectedIndex];
}
private void RemoveButton_OnClick(object? sender, RoutedEventArgs e)
{
if((sender as Button)!.CommandParameter is not uint id) return;
_imagesList.Remove(_imagesList.First(image => image.Id == id));
ValidateFilesList();
}
public bool ConfirmCopy(string originalFile = "") => _confirmCopy;
public bool ConfirmDeletion(string originalFile = "") => _deleteOriginal;
public bool ConfirmOverwrite(ref string existingFile)
{
// Wait if an ask dialog is being showed
if (_showDialog is not null && !_showDialog.IsCompleted)
_showDialog.Wait();
switch (ExistingFilesComboBox.SelectedIndex)
{
// Ask
case 0:
if (!_dontAsk)
{
// Ask what to do in a new dialog
var fileName = Path.GetFileName(existingFile);
_showDialog = Dispatcher.UIThread.InvokeAsync(async () =>
{
ConfirmOverwrite confirmOverwriteDialog = new(fileName);
return await confirmOverwriteDialog.ShowDialog<(OverwriteOptionsEnum, bool)?>(this);
});
var selectedValueTuple = _showDialog.Result;
if (selectedValueTuple is null) return false;
_dontAsk = selectedValueTuple.Value.Item2;
_overwriteOptions = selectedValueTuple.Value.Item1;
}
switch (_overwriteOptions)
{
case OverwriteOptionsEnum.Skip:
return false;
case OverwriteOptionsEnum.Rename:
existingFile = existingFile.Insert(existingFile.Length - 4, "_copy");
return true;
case OverwriteOptionsEnum.Overwrite:
return true;
default:
throw new ArgumentOutOfRangeException();
}
// Skip
case 1:
return false;
// Rename
case 2:
existingFile = existingFile.Insert(existingFile.Length - 4, "_copy");
return true;
// Overwrite
case 3: return true;
}
return false;
}
public void ManageDirectory(string directoryPath)
{
}
}