| 1 | using Avalonia.Controls; |
| 2 | using Avalonia.Interactivity; |
| 3 | using Avalonia.Markup.Xaml; |
| 4 | using Avalonia.Platform.Storage; |
| 5 | using Zipelo.Core; |
| 6 | using Zipelo.Ui; |
| 7 | |
| 8 | namespace Zipelo.Ubuntu; |
| 9 | |
| 10 | public partial class MainWindow : Window |
| 11 | { |
| 12 | private readonly IUbuntuArchiveWorkspace workspace; |
| 13 | private readonly Button openButton; |
| 14 | private readonly Button stopButton; |
| 15 | private readonly TextBlock archiveTitle; |
| 16 | private readonly TextBlock availability; |
| 17 | private readonly TextBlock status; |
| 18 | private readonly TextBlock emptyState; |
| 19 | private readonly ProgressBar progress; |
| 20 | private readonly ListBox files; |
| 21 | private readonly Button createButton; |
| 22 | private readonly Button retryCreateButton; |
| 23 | private readonly TextBox creationName; |
| 24 | private readonly TextBlock creationSelection; |
| 25 | private IReadOnlyList<IStorageFile> creationFiles = Array.Empty<IStorageFile>(); |
| 26 | private string? creationFolder; |
| 27 | private readonly Button extractButton; |
| 28 | private readonly TextBox extractionName; |
| 29 | private readonly TextBlock extractionSelection; |
| 30 | private SelectedArchive? openedArchive; |
| 31 | private bool startupHandled; |
| 32 | private bool busy; |
| 33 | private bool stopping; |
| 34 | private CancellationTokenSource? activeJob; |
| 35 | private Guid? activeJobId; |
| 36 | |
| 37 | public MainWindow() : this(new UbuntuWorkspace()) { } |
| 38 | |
| 39 | public MainWindow(IUbuntuArchiveWorkspace workspace) |
| 40 | { |
| 41 | this.workspace = workspace; |
| 42 | AvaloniaXamlLoader.Load(this); |
| 43 | openButton = this.FindControl<Button>("OpenButton")!; |
| 44 | stopButton = this.FindControl<Button>("StopButton")!; |
| 45 | archiveTitle = this.FindControl<TextBlock>("ArchiveTitle")!; |
| 46 | availability = this.FindControl<TextBlock>("Availability")!; |
| 47 | status = this.FindControl<TextBlock>("Status")!; |
| 48 | emptyState = this.FindControl<TextBlock>("EmptyState")!; |
| 49 | progress = this.FindControl<ProgressBar>("Progress")!; |
| 50 | files = this.FindControl<ListBox>("Files")!; |
| 51 | createButton = this.FindControl<Button>("CreateButton")!; |
| 52 | retryCreateButton = this.FindControl<Button>("RetryCreateButton")!; |
| 53 | creationName = this.FindControl<TextBox>("CreationName")!; |
| 54 | creationSelection = this.FindControl<TextBlock>("CreationSelection")!; |
| 55 | extractButton = this.FindControl<Button>("ExtractButton")!; |
| 56 | extractionName = this.FindControl<TextBox>("ExtractionName")!; |
| 57 | extractionSelection = this.FindControl<TextBlock>("ExtractionSelection")!; |
| 58 | Closed += (_, _) => |
| 59 | { |
| 60 | foreach (var file in creationFiles) { file.Dispose(); } |
| 61 | openedArchive?.Owner?.Dispose(); |
| 62 | }; |
| 63 | UpdateActions(); |
| 64 | } |
| 65 | |
| 66 | private sealed record SelectedArchive(string Name, Func<Task<Stream>> OpenRead, IDisposable? Owner = null); |
| 67 | |
| 68 | public async Task OpenStartupAsync(IReadOnlyList<string> arguments) |
| 69 | { |
| 70 | if (startupHandled) { return; } |
| 71 | startupHandled = true; |
| 72 | var target = ArchiveOpenArguments.Parse(arguments); |
| 73 | if (target.Error is not null) { status.Text = target.Error; return; } |
| 74 | if (target.Path is null) { return; } |
| 75 | await OpenArchiveCoreAsync(() => Task.FromResult<SelectedArchive?>(new( |
| 76 | Path.GetFileName(target.Path), () => Task.FromResult<Stream>(new FileStream( |
| 77 | target.Path, FileMode.Open, FileAccess.Read, FileShare.Read, 65536, |
| 78 | FileOptions.Asynchronous | FileOptions.SequentialScan))))); |
| 79 | } |
| 80 | |
| 81 | private async void OpenArchive(object? sender, RoutedEventArgs e) |
| 82 | { |
| 83 | await OpenArchiveCoreAsync(async () => |
| 84 | { |
| 85 | if (!StorageProvider.CanOpen) |
| 86 | { |
| 87 | status.Text = "파일 선택을 사용할 수 없습니다."; |
| 88 | return null; |
| 89 | } |
| 90 | var selection = await StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions |
| 91 | { |
| 92 | Title = "ZIP 압축파일 열기", |
| 93 | AllowMultiple = false, |
| 94 | FileTypeFilter = [new FilePickerFileType("ZIP 압축파일") { Patterns = ["*.zip"] }] |
| 95 | }); |
| 96 | if (selection.Count == 0) { return null; } |
| 97 | if (selection.Count != 1) |
| 98 | { |
| 99 | foreach (var file in selection) { file.Dispose(); } |
| 100 | status.Text = "압축파일은 한 번에 하나만 열 수 있습니다."; |
| 101 | return null; |
| 102 | } |
| 103 | var selected = selection[0]; |
| 104 | return new SelectedArchive(selected.Name, selected.OpenReadAsync, selected); |
| 105 | }); |
| 106 | } |
| 107 | |
| 108 | private async Task OpenArchiveCoreAsync(Func<Task<SelectedArchive?>> select) |
| 109 | { |
| 110 | if (busy) |
| 111 | { |
| 112 | status.Text = "다른 작업이 진행 중입니다. 작업 후 파일 열기를 다시 요청하세요."; |
| 113 | return; |
| 114 | } |
| 115 | if (!workspace.CanListZip) |
| 116 | { |
| 117 | status.Text = "작업 프로세스를 사용할 수 없습니다. 프로그램 폴더를 확인하세요."; |
| 118 | UpdateActions(); |
| 119 | return; |
| 120 | } |
| 121 | busy = true; |
| 122 | UpdateActions(); |
| 123 | SelectedArchive? selected = null; |
| 124 | try |
| 125 | { |
| 126 | selected = await select(); |
| 127 | if (selected is null) { return; } |
| 128 | var error = ArchiveOpenArguments.ValidateName(selected.Name); |
| 129 | if (error is not null) { status.Text = error; return; } |
| 130 | |
| 131 | using var cancellation = new CancellationTokenSource(); |
| 132 | activeJob = cancellation; |
| 133 | activeJobId = Guid.NewGuid(); |
| 134 | stopping = false; |
| 135 | progress.IsVisible = true; |
| 136 | status.Text = "파일 목록을 읽고 있습니다."; |
| 137 | UpdateActions(); |
| 138 | |
| 139 | // 파일 선택 제공자의 스트림을 사용하므로 포털 URI를 로컬 경로로 추측하지 않음. |
| 140 | await using var input = await selected.OpenRead(); |
| 141 | var jobId = activeJobId.Value; |
| 142 | var result = await workspace.ListAsync(jobId, input, cancellation.Token); |
| 143 | if (activeJobId != result.JobId) |
| 144 | { |
| 145 | throw new ArchiveException(ArchiveError.EngineFailure); |
| 146 | } |
| 147 | if (result.State == JobState.Completed && result.Error == ArchiveError.None) |
| 148 | { |
| 149 | // 이전 목록은 성공적으로 읽은 결과가 있을 때만 교체함. |
| 150 | files.ItemsSource = result.Entries.Select(entry => new ArchiveRow( |
| 151 | entry.Entry.Name, |
| 152 | entry.Entry.DeclaredSize is long size ? $"{size:N0}바이트" : "알 수 없음", |
| 153 | entry.Verification switch |
| 154 | { |
| 155 | VerificationState.Passed => "검증 통과", |
| 156 | VerificationState.Failed => "검증 실패", |
| 157 | VerificationState.Unavailable => "검증 불가", |
| 158 | _ => "검증 전" |
| 159 | })).ToArray(); |
| 160 | var previousArchive = openedArchive; |
| 161 | openedArchive = selected; |
| 162 | previousArchive?.Owner?.Dispose(); |
| 163 | archiveTitle.Text = selected.Name; |
| 164 | emptyState.Text = "이 압축파일에는 표시할 항목이 없습니다."; |
| 165 | emptyState.IsVisible = result.Entries.Count == 0; |
| 166 | status.Text = $"항목 {result.Entries.Count:N0}개를 읽었습니다. 내용 검증은 별도입니다."; |
| 167 | } |
| 168 | else if (result.State == JobState.Cancelled) |
| 169 | { |
| 170 | status.Text = "목록 읽기가 중지되었습니다."; |
| 171 | } |
| 172 | else |
| 173 | { |
| 174 | status.Text = ErrorMessage(result.Error); |
| 175 | } |
| 176 | } |
| 177 | catch (OperationCanceledException) |
| 178 | { |
| 179 | status.Text = "목록 읽기 요청이 취소되었습니다."; |
| 180 | } |
| 181 | catch (ArchiveException error) |
| 182 | { |
| 183 | status.Text = ErrorMessage(error.Code); |
| 184 | } |
| 185 | catch (Exception) |
| 186 | { |
| 187 | // 포털과 작업자 예외 원문에 포함될 수 있는 파일 경로를 노출하지 않음. |
| 188 | status.Text = "파일을 읽지 못했습니다. 파일과 프로그램 폴더를 확인하고 다시 시도하세요."; |
| 189 | } |
| 190 | finally |
| 191 | { |
| 192 | try |
| 193 | { |
| 194 | if (!ReferenceEquals(selected, openedArchive)) { selected?.Owner?.Dispose(); } |
| 195 | } |
| 196 | catch (Exception) { status.Text = "파일 핸들 정리를 완료하지 못했습니다. 다시 열기 전에 파일 상태를 확인하세요."; } |
| 197 | activeJob = null; |
| 198 | activeJobId = null; |
| 199 | progress.IsVisible = false; |
| 200 | busy = false; |
| 201 | stopping = false; |
| 202 | UpdateActions(); |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | private async void CreateArchive(object? sender, RoutedEventArgs e) => await RunCreation(true); |
| 207 | |
| 208 | private async void RetryCreation(object? sender, RoutedEventArgs e) => await RunCreation(false); |
| 209 | |
| 210 | private async Task RunCreation(bool choose) |
| 211 | { |
| 212 | if (busy || !workspace.CanCreateZip) { return; } |
| 213 | busy = true; |
| 214 | UpdateActions(); |
| 215 | try |
| 216 | { |
| 217 | if (choose) |
| 218 | { |
| 219 | if (!StorageProvider.CanOpen || !StorageProvider.CanPickFolder) |
| 220 | { |
| 221 | status.Text = "파일과 저장 폴더를 선택할 수 없습니다."; |
| 222 | return; |
| 223 | } |
| 224 | var selection = await StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions |
| 225 | { |
| 226 | Title = "ZIP에 넣을 파일 선택 (폴더 제외)", AllowMultiple = true |
| 227 | }); |
| 228 | if (selection.Count == 0) { return; } |
| 229 | foreach (var file in creationFiles) { file.Dispose(); } |
| 230 | creationFiles = selection; |
| 231 | creationFolder = null; |
| 232 | creationSelection.Text = $"선택한 파일 {selection.Count:N0}개: {string.Join(", ", selection.Select(file => file.Name))}"; |
| 233 | var folders = await StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions |
| 234 | { |
| 235 | Title = "새 ZIP을 저장할 폴더 선택", AllowMultiple = false |
| 236 | }); |
| 237 | if (folders.Count == 0) { return; } |
| 238 | using var folder = folders[0]; |
| 239 | // 네이티브 게시 API에는 명시적으로 선택된 로컬 폴더만 전달함. |
| 240 | if (!folder.Path.IsFile) |
| 241 | { |
| 242 | creationFolder = null; |
| 243 | status.Text = "현재는 로컬 저장 폴더만 지원합니다."; |
| 244 | return; |
| 245 | } |
| 246 | creationFolder = folder.Path.LocalPath; |
| 247 | } |
| 248 | if (creationFiles.Count == 0 || creationFolder is null) { return; } |
| 249 | var name = creationName.Text ?? ""; |
| 250 | if (OutputPathPolicy.Validate(name, OutputPathPolicy.CurrentPolicy).Count != 1 || |
| 251 | !name.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)) |
| 252 | { |
| 253 | status.Text = "경로 없이 .zip으로 끝나는 새 파일 이름을 입력하세요."; |
| 254 | return; |
| 255 | } |
| 256 | var destination = Path.Combine(creationFolder, name); |
| 257 | creationSelection.Text = $"선택한 파일 {creationFiles.Count:N0}개 → {destination}"; |
| 258 | using var cancellation = new CancellationTokenSource(); |
| 259 | activeJob = cancellation; |
| 260 | activeJobId = Guid.NewGuid(); |
| 261 | stopping = false; |
| 262 | progress.IsVisible = true; |
| 263 | status.Text = "선택한 파일을 읽고 새 ZIP을 생성하고 있습니다."; |
| 264 | UpdateActions(); |
| 265 | var sources = creationFiles.Select(file => new CreationSource(file.Name, async token => |
| 266 | { |
| 267 | token.ThrowIfCancellationRequested(); |
| 268 | return await file.OpenReadAsync(); |
| 269 | })).ToArray(); |
| 270 | var result = await workspace.CreateAsync(activeJobId.Value, sources, destination, cancellation.Token); |
| 271 | if (result.Job.JobId != activeJobId) { throw new ArchiveException(ArchiveError.EngineFailure); } |
| 272 | // 게시 후 늦은 취소로 실제 저장 성공을 취소 표시하지 않음. |
| 273 | status.Text = ZipCreationWorkflow.Describe(result); |
| 274 | } |
| 275 | catch (OperationCanceledException) |
| 276 | { |
| 277 | status.Text = "생성 요청이 취소되었습니다. 선택한 파일과 저장 위치는 유지됩니다."; |
| 278 | } |
| 279 | catch (ArchiveException error) { status.Text = ErrorMessage(error.Code); } |
| 280 | catch (Exception) |
| 281 | { |
| 282 | status.Text = "생성하지 못했습니다. 파일과 저장 위치를 확인하세요. 기존 목록과 선택은 유지됩니다."; |
| 283 | } |
| 284 | finally |
| 285 | { |
| 286 | activeJob = null; |
| 287 | activeJobId = null; |
| 288 | progress.IsVisible = false; |
| 289 | busy = false; |
| 290 | stopping = false; |
| 291 | UpdateActions(); |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | private async void ExtractArchive(object? sender, RoutedEventArgs e) |
| 296 | { |
| 297 | var source = openedArchive; |
| 298 | if (busy || source is null || !workspace.CanExtractZip) { return; } |
| 299 | busy = true; |
| 300 | UpdateActions(); |
| 301 | try |
| 302 | { |
| 303 | var name = extractionName.Text ?? ""; |
| 304 | ZipExtractionWorkflow.ValidateFolderName(name); |
| 305 | if (!StorageProvider.CanPickFolder) |
| 306 | { |
| 307 | status.Text = "저장 위치 선택을 사용할 수 없습니다."; |
| 308 | return; |
| 309 | } |
| 310 | var folders = await StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions |
| 311 | { |
| 312 | Title = "새 결과 폴더를 만들 부모 위치 선택", AllowMultiple = false |
| 313 | }); |
| 314 | if (folders.Count == 0) { return; } |
| 315 | using var parent = folders[0]; |
| 316 | if (!parent.Path.IsFile) |
| 317 | { |
| 318 | status.Text = "안전한 네이티브 게시에는 사용자가 고른 로컬 부모 폴더가 필요합니다."; |
| 319 | return; |
| 320 | } |
| 321 | var destination = Path.Combine(parent.Path.LocalPath, name); |
| 322 | extractionSelection.Text = $"새 결과 폴더: {destination}"; |
| 323 | using var cancellation = new CancellationTokenSource(); |
| 324 | var jobId = Guid.NewGuid(); |
| 325 | activeJobId = jobId; |
| 326 | activeJob = cancellation; |
| 327 | stopping = false; |
| 328 | progress.IsVisible = true; |
| 329 | status.Text = "ZIP 무결성과 새 결과 폴더 게시를 확인하고 있습니다."; |
| 330 | UpdateActions(); |
| 331 | var result = await Task.Run(() => workspace.ExtractAsync(jobId, async token => |
| 332 | { |
| 333 | token.ThrowIfCancellationRequested(); |
| 334 | return await source.OpenRead(); |
| 335 | }, destination, cancellation.Token)); |
| 336 | if (activeJobId != jobId || result.Job.JobId != jobId) |
| 337 | { |
| 338 | throw new ArchiveException(ArchiveError.EngineFailure); |
| 339 | } |
| 340 | status.Text = ZipExtractionWorkflow.Describe(result); |
| 341 | } |
| 342 | catch (OperationCanceledException) |
| 343 | { |
| 344 | status.Text = "압축 풀기가 취소되었습니다. 기존 목록과 선택은 유지됩니다."; |
| 345 | } |
| 346 | catch (ArchiveException error) { status.Text = ErrorMessage(error.Code); } |
| 347 | catch (Exception) |
| 348 | { |
| 349 | status.Text = "압축 풀기를 완료하지 못했습니다. 파일과 새 저장 위치를 확인하세요. 목록과 선택은 유지됩니다."; |
| 350 | } |
| 351 | finally |
| 352 | { |
| 353 | activeJob = null; |
| 354 | activeJobId = null; |
| 355 | progress.IsVisible = false; |
| 356 | busy = false; |
| 357 | stopping = false; |
| 358 | UpdateActions(); |
| 359 | } |
| 360 | } |
| 361 | |
| 362 | private void StopJob(object? sender, RoutedEventArgs e) => RequestStop(); |
| 363 | |
| 364 | private void RequestStop() |
| 365 | { |
| 366 | if (activeJob is null || stopping) { return; } |
| 367 | stopping = true; |
| 368 | try { activeJob.Cancel(); } |
| 369 | catch (AggregateException) { } |
| 370 | status.Text = "작업 프로세스의 종료를 기다리고 있습니다."; |
| 371 | UpdateActions(); |
| 372 | } |
| 373 | |
| 374 | private void UpdateActions() |
| 375 | { |
| 376 | openButton.IsEnabled = !busy && workspace.CanListZip; |
| 377 | createButton.IsEnabled = !busy && workspace.CanCreateZip; |
| 378 | createButton.Content = ZipCreationWorkflow.ValidationEnabled ? "ZIP 생성 검증" : "새로 압축하기"; |
| 379 | retryCreateButton.IsEnabled = !busy && workspace.CanCreateZip && creationFiles.Count > 0 && creationFolder is not null; |
| 380 | creationName.IsEnabled = !busy && workspace.CanCreateZip; |
| 381 | extractButton.IsEnabled = !busy && openedArchive is not null && workspace.CanExtractZip; |
| 382 | extractButton.Content = ZipExtractionWorkflow.ValidationEnabled ? "압축 풀기 검증" : "압축 풀기"; |
| 383 | extractButton.SetValue(ToolTip.TipProperty, ZipExtractionWorkflow.ScopeMessage); |
| 384 | extractionName.IsEnabled = !busy && workspace.CanExtractZip; |
| 385 | stopButton.IsEnabled = activeJob is not null && !stopping; |
| 386 | availability.Text = workspace.AvailabilityMessage; |
| 387 | } |
| 388 | |
| 389 | private void OnClosing(object? sender, WindowClosingEventArgs e) |
| 390 | { |
| 391 | if (!busy) { return; } |
| 392 | e.Cancel = true; |
| 393 | RequestStop(); |
| 394 | status.Text = "파일 선택이나 작업 정리가 끝난 뒤 창을 닫아주세요."; |
| 395 | } |
| 396 | |
| 397 | private static string ErrorMessage(ArchiveError error) => error switch |
| 398 | { |
| 399 | ArchiveError.OutputConflict => "같은 이름의 파일이 있습니다. 기존 파일은 유지됩니다. 새 이름을 입력하세요.", |
| 400 | ArchiveError.UnsafePath => "파일 이름을 확인하세요. 중복 이름이나 경로가 포함된 이름은 사용할 수 없습니다.", |
| 401 | ArchiveError.EngineUnavailable => "작업 프로세스를 시작할 수 없습니다. 프로그램 폴더를 확인하세요.", |
| 402 | ArchiveError.UnsupportedOperation => "이 ZIP 형식이나 암호 방식은 현재 연결에서 지원하지 않습니다.", |
| 403 | ArchiveError.BudgetExceeded => "처리 크기나 시간 한도를 초과했습니다. 더 작은 파일로 시도하세요.", |
| 404 | ArchiveError.IntegrityFailure => "데이터가 검증을 통과하지 못했습니다. 정상 파일로 간주하지 마세요.", |
| 405 | _ => "작업 프로세스가 정상 결과를 반환하지 못했습니다. 다른 파일을 선택해 다시 시도하세요." |
| 406 | }; |
| 407 | } |
| 408 | |
| 409 | public sealed record ArchiveRow(string Name, string Size, string Verification); |