forked from paulirwin/JavaToCSharp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindowViewModel.cs
More file actions
433 lines (357 loc) · 13.6 KB
/
MainWindowViewModel.cs
File metadata and controls
433 lines (357 loc) · 13.6 KB
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
using System.Diagnostics;
using Avalonia;
using Avalonia.Collections;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Media;
using Avalonia.Platform.Storage;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using JavaToCSharp;
using JavaToCSharpGui.Infrastructure;
using JavaToCSharpGui.Views;
namespace JavaToCSharpGui.ViewModels;
public partial class MainWindowViewModel : ViewModelBase
{
private readonly IHostStorageProvider? _storageProvider;
private readonly IUIDispatcher _dispatcher;
private readonly ITextClipboard? _clipboard;
private bool _usingFolderConvert;
/// <summary>
/// Constructor for the Avalonia Designer view inside the IDE.
/// </summary>
public MainWindowViewModel()
{
_dispatcher = new UIDispatcher(Dispatcher.UIThread);
if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime
{
MainWindow: not null
} desktop)
{
_storageProvider = new HostStorageProvider(desktop.MainWindow.StorageProvider);
_clipboard = new TextClipboard(desktop.MainWindow.Clipboard);
}
}
/// <summary>
/// Real constructor
/// </summary>
/// <param name="storageProvider">The storage provider.</param>
/// <param name="dispatcher">The UI Thread Dispatcher.</param>
/// <param name="clipboard">The clipboard.</param>
public MainWindowViewModel(IHostStorageProvider storageProvider, IUIDispatcher dispatcher, ITextClipboard clipboard)
{
_storageProvider = storageProvider;
_dispatcher = dispatcher;
_clipboard = clipboard;
DisplayName = "Java to C# Converter";
}
[ObservableProperty] private AvaloniaList<FileInfo> _folderInputFiles = [];
[ObservableProperty] private AvaloniaList<string> _folderOutputFiles = [];
private string _currentJavaFile = "";
[ObservableProperty] private TextDocument _javaText = new();
[ObservableProperty] private TextDocument _cSharpText = new();
[ObservableProperty] private string _openPath = "";
[ObservableProperty] private string _openFolderPath = "";
[ObservableProperty] private string _conversionStateLabel = "";
public FontFamily MonospaceFontFamily { get; } =
FontFamily.Parse("Cascadia Code,SF Mono,DejaVu Sans Mono,Menlo,Consolas");
[ObservableProperty] private bool _isConvertEnabled = true;
[ObservableProperty] private string _message = "";
[ObservableProperty] private string _messageTitle = "";
[RelayCommand]
private async Task Convert()
{
CurrentOptions.Options.WarningEncountered += Options_WarningEncountered;
CurrentOptions.Options.StateChanged += Options_StateChanged;
IsConvertEnabled = false;
_usingFolderConvert = false;
var text = JavaText.Text;
await Task.Run(async () =>
{
try
{
string? csharp = JavaToCSharpConverter.ConvertText(text, CurrentOptions.Options);
await DispatcherInvoke(() => CSharpText.Text = csharp ?? "");
}
catch (Exception ex)
{
await DispatcherInvoke(() =>
ShowMessage($"There was an error converting the text to C#: {ex.GetBaseException().Message}",
"Conversion Error"));
ConversionStateLabel = "";
}
finally
{
await DispatcherInvoke(() => IsConvertEnabled = true);
CurrentOptions.Options.WarningEncountered -= Options_WarningEncountered;
CurrentOptions.Options.StateChanged -= Options_StateChanged;
}
});
}
[RelayCommand]
private async Task OpenFolderDialog()
{
if (_storageProvider?.CanPickFolder is true)
{
FolderPickerOpenOptions options = new()
{
Title = "Folder Browser",
AllowMultiple = false,
SuggestedStartLocation = await _storageProvider.TryGetWellKnownFolderAsync(WellKnownFolder.Documents)
};
var result = await _storageProvider.OpenFolderPickerAsync(options);
if (!result.Any())
{
return;
}
string path = result[0].Path.LocalPath;
var dir = new DirectoryInfo(path);
if (!dir.Exists)
{
OpenFolderPath = string.Empty;
FolderInputFiles.Clear();
return;
}
OpenFolderPath = path;
await Task.Run(() =>
{
var files = dir.GetFiles("*.java", SearchOption.AllDirectories);
FolderInputFiles.Clear();
FolderInputFiles.AddRange(files);
return Task.CompletedTask;
});
}
}
[RelayCommand]
private async Task FolderConvert()
{
if (FolderInputFiles.Count == 0)
{
ShowMessage("No Java files found in the specified folder!");
return;
}
CurrentOptions.Options.WarningEncountered += Options_WarningEncountered;
CurrentOptions.Options.StateChanged += Options_StateChanged;
IsConvertEnabled = false;
_usingFolderConvert = true;
FolderOutputFiles.Clear();
await Task.Run(async () =>
{
try
{
var dir = new DirectoryInfo(OpenFolderPath);
string dirName = dir.Name;
string outDirName = $"{dirName}_csharp_output";
var outDir = new DirectoryInfo(Path.Combine(OpenFolderPath, outDirName));
if (!outDir.Exists)
outDir.Create();
string outDirFullName = outDir.FullName;
int subStartIndex = dir.FullName.Length;
foreach (var jFile in FolderInputFiles.Where(static x => x.Directory is not null))
{
string jPath = jFile.Directory!.FullName;
string jOutPath = $"{outDirFullName}{jPath[subStartIndex..]}";
string jOutFileName = Path.GetFileNameWithoutExtension(jFile.Name) + ".cs";
string jOutFileFullName = Path.Combine(jOutPath, jOutFileName);
_currentJavaFile = jFile.FullName;
if (!Directory.Exists(jOutPath))
Directory.CreateDirectory(jOutPath);
string jText = await File.ReadAllTextAsync(_currentJavaFile);
if (string.IsNullOrEmpty(jText))
continue;
try
{
string? csText = JavaToCSharpConverter.ConvertText(jText, CurrentOptions.Options);
await File.WriteAllTextAsync(jOutFileFullName, csText);
await DispatcherInvoke(() =>
{
FolderOutputFiles.Add(jOutFileFullName);
});
}
catch (Exception ex)
{
await DispatcherInvoke(() =>
{
ShowMessage($"There was an error converting {jFile.FullName} to C#: {ex.GetBaseException().Message}",
"Conversion Error");
});
}
}
}
catch (Exception ex)
{
await DispatcherInvoke(() =>
ShowMessage($"There was an error converting the text to C#: {ex.GetBaseException().Message}",
"Conversion Error"));
ConversionStateLabel = "";
}
finally
{
await DispatcherInvoke(() => IsConvertEnabled = true);
CurrentOptions.Options.WarningEncountered -= Options_WarningEncountered;
CurrentOptions.Options.StateChanged -= Options_StateChanged;
}
});
}
[RelayCommand]
private void ClearMessage()
{
MessageTitle = "";
Message = "";
IsMessageShown = false;
}
private void ShowMessage(string message, string title = "")
{
MessageTitle = title;
Message = message;
IsMessageShown = true;
}
[ObservableProperty] private bool _isMessageShown;
private void Options_StateChanged(object? sender, ConversionStateChangedEventArgs e)
{
ConversionStateLabel = e.NewState switch
{
ConversionState.Starting => "Starting...",
ConversionState.ParsingJavaAst => "Parsing Java code...",
ConversionState.BuildingCSharpAst => "Building C# AST...",
ConversionState.Done => "Done!",
_ => ConversionStateLabel
};
}
private async void Options_WarningEncountered(object? sender, ConversionWarningEventArgs e)
{
if (_usingFolderConvert)
{
await DispatcherInvoke(() =>
{
CSharpText.Text = $"{CSharpText.Text}{Environment.NewLine}" +
$"=================={Environment.NewLine}" +
$"[WARN] {_currentJavaFile}{e.JavaLineNumber}{Environment.NewLine}" +
$"\t\tMessage: {e.Message}{Environment.NewLine}";
});
}
else
{
ShowMessage($"Java Line {e.JavaLineNumber}: {e.Message}", "Warning Encountered");
}
}
[RelayCommand]
private async Task OpenFileDialog()
{
if (_storageProvider?.CanOpen is true)
{
var filePickerOpenOptions = new FilePickerOpenOptions
{
FileTypeFilter = new FilePickerFileType[]
{
new("Java files")
{
Patterns = new[] { "*.java" },
}
},
};
var result = await _storageProvider.OpenFilePickerAsync(filePickerOpenOptions);
if (result.Any())
{
OpenPath = result[0].Path.LocalPath;
JavaText.Text = await File.ReadAllTextAsync(result[0].Path.LocalPath);
}
}
}
[RelayCommand]
private async Task PasteInput()
{
if (_clipboard is null)
{
return;
}
var text = await _clipboard.GetTextAsync();
if (!string.IsNullOrEmpty(text))
{
JavaText.Text = text;
ConversionStateLabel = "Pasted Java code from clipboard!";
await Task.Delay(2000);
await _dispatcher.InvokeAsync(() => { ConversionStateLabel = ""; }, DispatcherPriority.Background);
}
}
[RelayCommand]
private async Task CopyOutput()
{
if (_clipboard is null)
{
return;
}
await _clipboard.SetTextAsync(CSharpText.Text);
ConversionStateLabel = "Copied C# code to clipboard!";
await Task.Delay(2000);
await _dispatcher.InvokeAsync(() => { ConversionStateLabel = ""; }, DispatcherPriority.Background);
}
[RelayCommand]
private async Task SaveOutput()
{
if (_storageProvider?.CanSave is true)
{
IStorageFolder? startLocation = null;
if (Path.GetDirectoryName(OpenPath) is string dir)
{
startLocation = await _storageProvider.TryGetFolderFromPathAsync(dir);
}
startLocation ??= await _storageProvider.TryGetWellKnownFolderAsync(WellKnownFolder.Documents);
var filePickerSaveOptions = new FilePickerSaveOptions
{
SuggestedFileName = Path.GetFileNameWithoutExtension(OpenPath) + ".cs",
SuggestedStartLocation = startLocation,
Title = "Save C# File"
};
var result = await _storageProvider.OpenSaveFileDialogAsync(filePickerSaveOptions);
if (result is not null)
{
await File.WriteAllTextAsync(result.Path.LocalPath, CSharpText.Text);
ConversionStateLabel = "Saved C# code to file!";
await Task.Delay(2000);
await _dispatcher.InvokeAsync(() => { ConversionStateLabel = ""; }, DispatcherPriority.Background);
}
}
}
[RelayCommand]
private static void ForkMeOnGitHub() => Process.Start(new ProcessStartInfo
{
FileName = "https://github.com/paulirwin/javatocsharp",
UseShellExecute = true
});
[RelayCommand]
private static void OpenSettings()
{
var parent = Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop
? desktop.MainWindow
: null;
var settings = new SettingsWindow();
if (parent is not null)
{
settings.ShowDialog(parent);
}
else
{
settings.Show();
}
}
[RelayCommand]
private static void OpenAbout()
{
var parent = Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop
? desktop.MainWindow
: null;
var about = new AboutWindow();
if (parent is not null)
{
about.ShowDialog(parent);
}
else
{
about.Show();
}
}
private async Task DispatcherInvoke(Action callback) =>
await _dispatcher.InvokeAsync(callback, DispatcherPriority.Normal);
}