| 1 | using System.ComponentModel; |
| 2 | using System.IO; |
| 3 | using System.Security; |
| 4 | using System.Windows; |
| 5 | using System.Windows.Media; |
| 6 | using Microsoft.Win32; |
| 7 | using Zipelo.Core; |
| 8 | using Zipelo.Ui; |
| 9 | |
| 10 | namespace Zipelo.Desktop; |
| 11 | |
| 12 | public partial class MainWindow : Window |
| 13 | { |
| 14 | private enum ScreenPhase { Idle, Selecting, Running, WaitingForPassword, Cancelling, Finishing } |
| 15 | |
| 16 | private readonly IArchiveWorkspace workspace; |
| 17 | private readonly HashSet<Guid> passwordRequests = []; |
| 18 | private ScreenPhase phase; |
| 19 | private CancellationTokenSource? activeJob; |
| 20 | private Guid? activeJobId; |
| 21 | private long lastSequence; |
| 22 | private string? archivePath; |
| 23 | private PasswordWindow? passwordWindow; |
| 24 | private string[] creationSources = []; |
| 25 | private string? creationDestination; |
| 26 | private bool startupHandled; |
| 27 | |
| 28 | public MainWindow(IArchiveWorkspace workspace) |
| 29 | { |
| 30 | this.workspace = workspace; |
| 31 | InitializeComponent(); |
| 32 | Availability.Text = workspace is IWorkspaceCapabilities features |
| 33 | ? features.AvailabilityMessage |
| 34 | : "작업 프로세스가 아직 연결되지 않았습니다. 파일을 처리할 수 없습니다."; |
| 35 | UpdateActions(); |
| 36 | } |
| 37 | |
| 38 | private bool CanExecute(WorkspaceAction action, string format = "zip") => |
| 39 | workspace.IsAvailable && workspace is IWorkspaceCapabilities features && features.CanExecute(action, format); |
| 40 | |
| 41 | public async Task OpenStartupAsync(IReadOnlyList<string> arguments) |
| 42 | { |
| 43 | if (startupHandled) { return; } |
| 44 | startupHandled = true; |
| 45 | var target = ArchiveOpenArguments.Parse(arguments); |
| 46 | if (target.Error is not null) { SetStatus(target.Error, true); return; } |
| 47 | if (target.Path is null) { return; } |
| 48 | if (phase != ScreenPhase.Idle) |
| 49 | { |
| 50 | SetStatus("다른 작업이 진행 중이라 시작 파일을 열지 못했습니다. 작업 후 파일 열기를 사용하세요.", true); |
| 51 | return; |
| 52 | } |
| 53 | await SelectAndRun(WorkspaceAction.List, () => new WorkspaceRequest( |
| 54 | Guid.NewGuid(), WorkspaceAction.List, [target.Path])); |
| 55 | } |
| 56 | |
| 57 | private async void OpenArchive(object sender, RoutedEventArgs e) |
| 58 | { |
| 59 | await SelectAndRun(WorkspaceAction.List, () => |
| 60 | { |
| 61 | var dialog = new OpenFileDialog |
| 62 | { |
| 63 | Title = "압축파일 열기", |
| 64 | Filter = "ZIP 압축파일|*.zip", |
| 65 | CheckFileExists = true |
| 66 | }; |
| 67 | return dialog.ShowDialog(this) == true |
| 68 | ? new WorkspaceRequest(Guid.NewGuid(), WorkspaceAction.List, [dialog.FileName]) |
| 69 | : null; |
| 70 | }); |
| 71 | } |
| 72 | |
| 73 | private async void CreateArchive(object sender, RoutedEventArgs e) |
| 74 | { |
| 75 | await SelectAndRun(WorkspaceAction.Create, () => |
| 76 | { |
| 77 | var sources = new OpenFileDialog |
| 78 | { |
| 79 | Title = "압축할 파일 선택", |
| 80 | Multiselect = true, |
| 81 | CheckFileExists = true |
| 82 | }; |
| 83 | if (sources.ShowDialog(this) != true) { return null; } |
| 84 | creationSources = sources.FileNames; |
| 85 | creationDestination = null; |
| 86 | CreationSelection.Text = $"선택한 생성 파일 {creationSources.Length:N0}개: {string.Join(", ", creationSources.Select(path => Path.GetFileName(path)))}"; |
| 87 | var destination = new SaveFileDialog |
| 88 | { |
| 89 | Title = "새 ZIP 파일 저장 위치", |
| 90 | Filter = "ZIP 압축파일|*.zip", |
| 91 | DefaultExt = ".zip", |
| 92 | AddExtension = true, |
| 93 | FileName = creationDestination ?? "새 압축파일.zip", |
| 94 | OverwritePrompt = false |
| 95 | }; |
| 96 | if (destination.ShowDialog(this) != true) { return null; } |
| 97 | creationDestination = destination.FileName; |
| 98 | CreationSelection.Text += $" → {Path.GetFileName(creationDestination)}"; |
| 99 | return new WorkspaceRequest(Guid.NewGuid(), WorkspaceAction.Create, creationSources, creationDestination); |
| 100 | }); |
| 101 | } |
| 102 | |
| 103 | private async void RetryCreation(object sender, RoutedEventArgs e) |
| 104 | { |
| 105 | await SelectAndRun(WorkspaceAction.Create, () => creationSources.Length > 0 && creationDestination is not null |
| 106 | ? new WorkspaceRequest(Guid.NewGuid(), WorkspaceAction.Create, creationSources, creationDestination) |
| 107 | : null); |
| 108 | } |
| 109 | |
| 110 | private async void ExtractArchive(object sender, RoutedEventArgs e) |
| 111 | { |
| 112 | await SelectAndRun(WorkspaceAction.Extract, () => |
| 113 | { |
| 114 | if (archivePath is null) { SetStatus("먼저 ZIP 목록을 열어주세요.", true); return null; } |
| 115 | var name = ExtractionName.Text; |
| 116 | ZipExtractionWorkflow.ValidateFolderName(name); |
| 117 | var parent = new OpenFolderDialog |
| 118 | { |
| 119 | Title = "새 결과 폴더를 만들 부모 위치 선택 (기존 폴더에 병합하지 않음)", |
| 120 | Multiselect = false |
| 121 | }; |
| 122 | if (parent.ShowDialog(this) != true) { return null; } |
| 123 | var destination = Path.Combine(parent.FolderName, name); |
| 124 | ExtractionSelection.Text = $"새 결과 폴더: {destination}"; |
| 125 | return new WorkspaceRequest(Guid.NewGuid(), WorkspaceAction.Extract, [archivePath], destination); |
| 126 | }); |
| 127 | } |
| 128 | |
| 129 | private async Task SelectAndRun(WorkspaceAction action, Func<WorkspaceRequest?> select) |
| 130 | { |
| 131 | if (phase != ScreenPhase.Idle) { return; } |
| 132 | if (!CanExecute(action)) |
| 133 | { |
| 134 | SetStatus(action == WorkspaceAction.Extract |
| 135 | ? "일반 압축 풀기는 비활성입니다. 명시적인 개발 검증 빌드와 작업자가 필요합니다." |
| 136 | : "이 기능의 작업 프로세스가 연결되지 않았거나 지원하지 않습니다.", true); |
| 137 | return; |
| 138 | } |
| 139 | |
| 140 | // 파일 선택부터 결과 반영까지 같은 게이트를 유지함. |
| 141 | phase = ScreenPhase.Selecting; |
| 142 | UpdateActions(); |
| 143 | try |
| 144 | { |
| 145 | var request = select(); |
| 146 | if (request is null) { return; } |
| 147 | if (request.Action == WorkspaceAction.List) |
| 148 | { |
| 149 | var target = request.Sources.Count == 1 |
| 150 | ? ArchiveOpenArguments.ValidatePath(request.Sources[0]) |
| 151 | : new ArchiveOpenTarget(null, "압축파일은 한 번에 하나만 열 수 있습니다."); |
| 152 | if (target.Error is not null) { SetStatus(target.Error, true); return; } |
| 153 | } |
| 154 | await RunJob(request); |
| 155 | } |
| 156 | catch (ArchiveException error) |
| 157 | { |
| 158 | SetStatus(WorkspaceMessages.Error(error.Code), true); |
| 159 | Progress.Value = 0; |
| 160 | } |
| 161 | catch (Exception) |
| 162 | { |
| 163 | // 파일 선택과 엔진 예외의 원문은 화면과 로그에 노출하지 않음. |
| 164 | SetStatus("작업을 시작하지 못했습니다. 파일 상태를 확인하고 다시 선택하세요.", true); |
| 165 | Progress.Value = 0; |
| 166 | } |
| 167 | finally |
| 168 | { |
| 169 | Progress.IsIndeterminate = false; |
| 170 | activeJob = null; |
| 171 | activeJobId = null; |
| 172 | passwordRequests.Clear(); |
| 173 | phase = ScreenPhase.Idle; |
| 174 | UpdateActions(); |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | private async Task RunJob(WorkspaceRequest request) |
| 179 | { |
| 180 | using var cancellation = new CancellationTokenSource(); |
| 181 | activeJob = cancellation; |
| 182 | activeJobId = request.JobId; |
| 183 | lastSequence = 0; |
| 184 | passwordRequests.Clear(); |
| 185 | phase = ScreenPhase.Running; |
| 186 | Progress.Value = 0; |
| 187 | Progress.IsIndeterminate = true; |
| 188 | ResultSummary.Text = ""; |
| 189 | UpdateActions(); |
| 190 | SetStatus(request.Action switch |
| 191 | { |
| 192 | WorkspaceAction.List => "파일 목록을 읽고 있습니다.", |
| 193 | WorkspaceAction.Extract => "ZIP 무결성과 새 폴더 게시를 확인하고 있습니다.", |
| 194 | _ => "파일을 압축하고 있습니다." |
| 195 | }); |
| 196 | |
| 197 | var progress = new Progress<WorkspaceProgress>(value => ApplyProgress(request.JobId, value)); |
| 198 | try |
| 199 | { |
| 200 | var result = await Task.Run(() => workspace.ExecuteAsync( |
| 201 | request, progress, RequestPasswordAsync, cancellation.Token)); |
| 202 | phase = ScreenPhase.Finishing; |
| 203 | UpdateActions(); |
| 204 | if (activeJobId != request.JobId || result.JobId != request.JobId) |
| 205 | { |
| 206 | throw new ArchiveException(ArchiveError.EngineFailure); |
| 207 | } |
| 208 | |
| 209 | // 늦은 취소 토큰 대신 호스트의 실제 종료 결과를 사용함. |
| 210 | PublishResult(request, result); |
| 211 | } |
| 212 | catch (OperationCanceledException) when (cancellation.IsCancellationRequested) |
| 213 | { |
| 214 | phase = ScreenPhase.Finishing; |
| 215 | Progress.Value = 0; |
| 216 | SetStatus("중지 요청 후 작업이 종료되었습니다. 결과 파일 상태를 확인하세요."); |
| 217 | } |
| 218 | catch (ArchiveException error) |
| 219 | { |
| 220 | phase = ScreenPhase.Finishing; |
| 221 | Progress.Value = 0; |
| 222 | SetStatus(WorkspaceMessages.Error(error.Code), true); |
| 223 | } |
| 224 | catch (Exception) |
| 225 | { |
| 226 | phase = ScreenPhase.Finishing; |
| 227 | Progress.Value = 0; |
| 228 | SetStatus("파일을 처리하지 못했습니다. 파일 상태와 저장 위치를 확인하고 다시 시도하세요.", true); |
| 229 | } |
| 230 | finally |
| 231 | { |
| 232 | // 수명이 끝난 작업의 이벤트와 암호 요청을 결과 반영 이후 거부함. |
| 233 | activeJobId = null; |
| 234 | activeJob = null; |
| 235 | Progress.IsIndeterminate = false; |
| 236 | } |
| 237 | } |
| 238 | |
| 239 | private void ApplyProgress(Guid jobId, WorkspaceProgress value) |
| 240 | { |
| 241 | if (activeJobId != jobId || value.JobId != jobId || value.Sequence <= lastSequence || |
| 242 | phase is ScreenPhase.Idle or ScreenPhase.Selecting or ScreenPhase.Finishing) |
| 243 | { |
| 244 | return; |
| 245 | } |
| 246 | lastSequence = value.Sequence; |
| 247 | if (value.State is JobState.Completed or JobState.Partial or JobState.Cancelled or JobState.Failed) |
| 248 | { |
| 249 | phase = ScreenPhase.Finishing; |
| 250 | Progress.IsIndeterminate = false; |
| 251 | SetStatus("작업 결과와 정리를 확인하고 있습니다."); |
| 252 | UpdateActions(); |
| 253 | return; |
| 254 | } |
| 255 | if (phase == ScreenPhase.Cancelling || activeJob?.IsCancellationRequested == true || value.State == JobState.Cancelling) |
| 256 | { |
| 257 | phase = ScreenPhase.Cancelling; |
| 258 | SetStatus("중지 요청을 처리하고 있습니다."); |
| 259 | Progress.IsIndeterminate = true; |
| 260 | } |
| 261 | else if (passwordWindow is not null || value.State == JobState.WaitingForPassword) |
| 262 | { |
| 263 | phase = ScreenPhase.WaitingForPassword; |
| 264 | SetStatus("암호 입력을 기다리고 있습니다."); |
| 265 | Progress.IsIndeterminate = false; |
| 266 | } |
| 267 | else |
| 268 | { |
| 269 | phase = ScreenPhase.Running; |
| 270 | Progress.IsIndeterminate = value.TotalBytes is null or <= 0; |
| 271 | if (value.TotalBytes > 0) |
| 272 | { |
| 273 | Progress.Value = Math.Clamp(100.0 * value.ProcessedBytes / value.TotalBytes.Value, 0, 100); |
| 274 | } |
| 275 | SetStatus($"처리한 크기: {Math.Max(0, value.ProcessedBytes):N0}바이트"); |
| 276 | } |
| 277 | UpdateActions(); |
| 278 | } |
| 279 | |
| 280 | private void PublishResult(WorkspaceRequest request, WorkspaceResult result) |
| 281 | { |
| 282 | if (request.Action == WorkspaceAction.Extract) |
| 283 | { |
| 284 | var extractionPublished = result.Extraction is not null && ZipExtractionWorkflow.Published(result.Extraction); |
| 285 | Progress.Value = extractionPublished ? 100 : 0; |
| 286 | ResultSummary.Text = "열린 ZIP 목록과 이름/위치는 유지됩니다. 다른 새 위치는 압축 풀기 검증에서 선택하세요."; |
| 287 | SetStatus(result.Extraction is not null ? ZipExtractionWorkflow.Describe(result.Extraction) |
| 288 | : "새 결과 폴더의 게시를 확인하지 못했습니다.", !extractionPublished); |
| 289 | return; |
| 290 | } |
| 291 | if (request.Action == WorkspaceAction.Create) |
| 292 | { |
| 293 | Progress.Value = result.Creation?.Publication?.Published == true ? 100 : 0; |
| 294 | ResultSummary.Text = "생성에 사용한 선택은 유지됩니다. 다른 저장 이름은 새로 압축하기에서 선택하세요."; |
| 295 | SetStatus(result.Creation is not null ? ZipCreationWorkflow.Describe(result.Creation) |
| 296 | : "새 파일의 게시를 확인하지 못했습니다.", result.Creation?.Publication?.Published != true); |
| 297 | return; |
| 298 | } |
| 299 | var succeeded = result.Outcome == WorkspaceOutcome.Completed && result.Error == ArchiveError.None; |
| 300 | Progress.Value = succeeded ? 100 : 0; |
| 301 | if (request.Action == WorkspaceAction.List && succeeded) |
| 302 | { |
| 303 | archivePath = request.Sources[0]; |
| 304 | ArchiveTitle.Text = Path.GetFileName(archivePath); |
| 305 | Files.ItemsSource = result.Entries; |
| 306 | EmptyState.Text = "이 압축파일에는 표시할 항목이 없습니다."; |
| 307 | EmptyState.Visibility = result.Entries.Count == 0 ? Visibility.Visible : Visibility.Collapsed; |
| 308 | } |
| 309 | var published = result.Entries.Count(entry => entry.Outcome == EntryOutcome.Extracted); |
| 310 | var failed = result.Entries.Count(entry => entry.Outcome == EntryOutcome.Failed || entry.Error != ArchiveError.None); |
| 311 | ResultSummary.Text = $"결과 항목 {result.Entries.Count:N0}개, 게시 확인 {published:N0}개, 실패 {failed:N0}개"; |
| 312 | if (succeeded) |
| 313 | { |
| 314 | SetStatus(request.Action == WorkspaceAction.List ? "파일 목록을 읽었습니다. 내용 검증은 별도입니다." : "ZIP 생성 작업이 완료되었습니다."); |
| 315 | } |
| 316 | else if (result.Outcome == WorkspaceOutcome.Cancelled && result.Error is ArchiveError.None or ArchiveError.Cancelled) |
| 317 | { |
| 318 | SetStatus("작업이 중지되었습니다. 결과 파일 상태를 확인하세요."); |
| 319 | } |
| 320 | else if (result.Outcome == WorkspaceOutcome.Partial) |
| 321 | { |
| 322 | SetStatus("일부 항목만 처리했습니다. 결과와 검증 상태를 확인하세요.", true); |
| 323 | } |
| 324 | else |
| 325 | { |
| 326 | SetStatus(WorkspaceMessages.Error(result.Error), true); |
| 327 | } |
| 328 | } |
| 329 | |
| 330 | private Task<SecureString?> RequestPasswordAsync(PasswordChallenge challenge, CancellationToken cancellationToken) |
| 331 | { |
| 332 | return Dispatcher.InvokeAsync<SecureString?>(() => |
| 333 | { |
| 334 | cancellationToken.ThrowIfCancellationRequested(); |
| 335 | if (activeJobId != challenge.JobId || challenge.RequestId == Guid.Empty || |
| 336 | phase is ScreenPhase.Finishing or ScreenPhase.Cancelling || passwordWindow is not null || |
| 337 | !passwordRequests.Add(challenge.RequestId)) |
| 338 | { |
| 339 | throw new ArchiveException(ArchiveError.InvalidPasswordResponse); |
| 340 | } |
| 341 | |
| 342 | phase = ScreenPhase.WaitingForPassword; |
| 343 | SetStatus(challenge.Attempt > 1 ? "암호를 다시 확인해 입력하세요." : "암호 입력을 기다리고 있습니다."); |
| 344 | Progress.IsIndeterminate = false; |
| 345 | var dialog = new PasswordWindow { Owner = this }; |
| 346 | passwordWindow = dialog; |
| 347 | UpdateActions(); |
| 348 | using var registration = cancellationToken.Register(() => |
| 349 | Dispatcher.BeginInvoke(new Action(() => |
| 350 | { |
| 351 | if (dialog.IsVisible) { dialog.Close(); } |
| 352 | }))); |
| 353 | try |
| 354 | { |
| 355 | cancellationToken.ThrowIfCancellationRequested(); |
| 356 | if (dialog.ShowDialog() == true && !cancellationToken.IsCancellationRequested && activeJobId == challenge.JobId) |
| 357 | { |
| 358 | return dialog.TakePassword(); |
| 359 | } |
| 360 | RequestStop(); |
| 361 | return null; |
| 362 | } |
| 363 | finally |
| 364 | { |
| 365 | dialog.DiscardPassword(); |
| 366 | passwordWindow = null; |
| 367 | if (phase != ScreenPhase.Finishing) |
| 368 | { |
| 369 | phase = activeJob?.IsCancellationRequested == true ? ScreenPhase.Cancelling : ScreenPhase.Running; |
| 370 | SetStatus(phase == ScreenPhase.Cancelling ? "중지 요청을 처리하고 있습니다." : "작업을 계속하고 있습니다."); |
| 371 | Progress.IsIndeterminate = true; |
| 372 | } |
| 373 | UpdateActions(); |
| 374 | } |
| 375 | }).Task; |
| 376 | } |
| 377 | |
| 378 | private void StopJob(object sender, RoutedEventArgs e) => RequestStop(); |
| 379 | |
| 380 | private void RequestStop() |
| 381 | { |
| 382 | if (activeJob is null || phase == ScreenPhase.Finishing) { return; } |
| 383 | phase = ScreenPhase.Cancelling; |
| 384 | try { activeJob.Cancel(); } |
| 385 | catch (AggregateException) |
| 386 | { |
| 387 | // 취소 관찰자 실패가 있어도 실제 작업 종료를 기다림. |
| 388 | } |
| 389 | SetStatus("중지 요청을 처리하고 있습니다."); |
| 390 | UpdateActions(); |
| 391 | } |
| 392 | |
| 393 | private void UpdateActions() |
| 394 | { |
| 395 | var ready = phase == ScreenPhase.Idle; |
| 396 | OpenButton.IsEnabled = ready && CanExecute(WorkspaceAction.List); |
| 397 | CreateButton.IsEnabled = ready && CanExecute(WorkspaceAction.Create); |
| 398 | CreateButton.Content = ZipCreationWorkflow.ValidationEnabled ? "ZIP 생성 검증" : "새로 압축하기"; |
| 399 | CreateButton.ToolTip = ZipCreationWorkflow.ScopeMessage; |
| 400 | RetryCreateButton.IsEnabled = ready && CanExecute(WorkspaceAction.Create) && |
| 401 | creationSources.Length > 0 && creationDestination is not null; |
| 402 | ExtractButton.IsEnabled = ready && archivePath is not null && CanExecute(WorkspaceAction.Extract); |
| 403 | ExtractButton.Content = ZipExtractionWorkflow.ValidationEnabled ? "압축 풀기 검증" : "압축 풀기"; |
| 404 | ExtractButton.ToolTip = ZipExtractionWorkflow.ScopeMessage; |
| 405 | ExtractionName.IsEnabled = ready && CanExecute(WorkspaceAction.Extract); |
| 406 | StopButton.IsEnabled = activeJob is not null && |
| 407 | phase is ScreenPhase.Running or ScreenPhase.WaitingForPassword; |
| 408 | } |
| 409 | |
| 410 | private void SetStatus(string message, bool error = false) |
| 411 | { |
| 412 | Status.Text = message; |
| 413 | Status.Foreground = error ? new SolidColorBrush(Color.FromRgb(164, 38, 44)) : SystemColors.ControlTextBrush; |
| 414 | } |
| 415 | |
| 416 | private void ShowInstallation(object sender, RoutedEventArgs e) |
| 417 | { |
| 418 | MessageBox.Show(this, |
| 419 | "설치 파일은 준비 중입니다.\n\n예정 흐름: 설치 파일 더블클릭 → 설치 → 완료\n\n기본 앱은 설치 후 Windows 설정에서 직접 선택합니다. 현재 화면은 설정을 변경하지 않습니다.", |
| 420 | "설치와 기본 앱 설정", MessageBoxButton.OK, MessageBoxImage.Information); |
| 421 | } |
| 422 | |
| 423 | private void OnClosing(object? sender, CancelEventArgs e) |
| 424 | { |
| 425 | if (phase != ScreenPhase.Idle) |
| 426 | { |
| 427 | e.Cancel = true; |
| 428 | RequestStop(); |
| 429 | SetStatus("파일 선택이나 작업 정리가 끝난 뒤 창을 닫아주세요."); |
| 430 | } |
| 431 | } |
| 432 | } |