team-ljyzipelo

공개
403줄17 KB
1using System.ComponentModel;
2using System.IO;
3using System.Security;
4using System.Windows;
5using System.Windows.Media;
6using Microsoft.Win32;
7using Zipelo.Core;
8using Zipelo.Ui;
9
10namespace Zipelo.Desktop;
11
12public 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 // 실제 해제 저장 계층 검증 전에는 프로그램 호출도 거부함.
113 await SelectAndRun(WorkspaceAction.Extract, () => null);
114 }
115
116 private async Task SelectAndRun(WorkspaceAction action, Func<WorkspaceRequest?> select)
117 {
118 if (phase != ScreenPhase.Idle) { return; }
119 if (!CanExecute(action) || action == WorkspaceAction.Extract)
120 {
121 SetStatus(action == WorkspaceAction.Extract
122 ? "압축 풀기는 안전한 저장 기능의 검증 후 사용할 수 있습니다."
123 : "이 기능의 작업 프로세스가 연결되지 않았거나 지원하지 않습니다.", true);
124 return;
125 }
126
127 // 파일 선택부터 결과 반영까지 같은 게이트를 유지함.
128 phase = ScreenPhase.Selecting;
129 UpdateActions();
130 try
131 {
132 var request = select();
133 if (request is null) { return; }
134 if (request.Action == WorkspaceAction.List)
135 {
136 var target = request.Sources.Count == 1
137 ? ArchiveOpenArguments.ValidatePath(request.Sources[0])
138 : new ArchiveOpenTarget(null, "압축파일은 한 번에 하나만 열 수 있습니다.");
139 if (target.Error is not null) { SetStatus(target.Error, true); return; }
140 }
141 await RunJob(request);
142 }
143 catch (ArchiveException error)
144 {
145 SetStatus(WorkspaceMessages.Error(error.Code), true);
146 Progress.Value = 0;
147 }
148 catch (Exception)
149 {
150 // 파일 선택과 엔진 예외의 원문은 화면과 로그에 노출하지 않음.
151 SetStatus("작업을 시작하지 못했습니다. 파일 상태를 확인하고 다시 선택하세요.", true);
152 Progress.Value = 0;
153 }
154 finally
155 {
156 Progress.IsIndeterminate = false;
157 activeJob = null;
158 activeJobId = null;
159 passwordRequests.Clear();
160 phase = ScreenPhase.Idle;
161 UpdateActions();
162 }
163 }
164
165 private async Task RunJob(WorkspaceRequest request)
166 {
167 using var cancellation = new CancellationTokenSource();
168 activeJob = cancellation;
169 activeJobId = request.JobId;
170 lastSequence = 0;
171 passwordRequests.Clear();
172 phase = ScreenPhase.Running;
173 Progress.Value = 0;
174 Progress.IsIndeterminate = true;
175 ResultSummary.Text = "";
176 UpdateActions();
177 SetStatus(request.Action == WorkspaceAction.List ? "파일 목록을 읽고 있습니다." : "파일을 압축하고 있습니다.");
178
179 var progress = new Progress<WorkspaceProgress>(value => ApplyProgress(request.JobId, value));
180 try
181 {
182 var result = await Task.Run(() => workspace.ExecuteAsync(
183 request, progress, RequestPasswordAsync, cancellation.Token));
184 phase = ScreenPhase.Finishing;
185 UpdateActions();
186 if (result.JobId != request.JobId)
187 {
188 throw new ArchiveException(ArchiveError.EngineFailure);
189 }
190
191 // 늦은 취소 토큰 대신 호스트의 실제 종료 결과를 사용함.
192 PublishResult(request, result);
193 }
194 catch (OperationCanceledException) when (cancellation.IsCancellationRequested)
195 {
196 phase = ScreenPhase.Finishing;
197 Progress.Value = 0;
198 SetStatus("중지 요청 후 작업이 종료되었습니다. 결과 파일 상태를 확인하세요.");
199 }
200 catch (ArchiveException error)
201 {
202 phase = ScreenPhase.Finishing;
203 Progress.Value = 0;
204 SetStatus(WorkspaceMessages.Error(error.Code), true);
205 }
206 catch (Exception)
207 {
208 phase = ScreenPhase.Finishing;
209 Progress.Value = 0;
210 SetStatus("파일을 처리하지 못했습니다. 파일 상태와 저장 위치를 확인하고 다시 시도하세요.", true);
211 }
212 finally
213 {
214 // 수명이 끝난 작업의 이벤트와 암호 요청을 결과 반영 이후 거부함.
215 activeJobId = null;
216 activeJob = null;
217 Progress.IsIndeterminate = false;
218 }
219 }
220
221 private void ApplyProgress(Guid jobId, WorkspaceProgress value)
222 {
223 if (activeJobId != jobId || value.JobId != jobId || value.Sequence <= lastSequence ||
224 phase is ScreenPhase.Idle or ScreenPhase.Selecting or ScreenPhase.Finishing)
225 {
226 return;
227 }
228 lastSequence = value.Sequence;
229 if (value.State is JobState.Completed or JobState.Partial or JobState.Cancelled or JobState.Failed)
230 {
231 phase = ScreenPhase.Finishing;
232 Progress.IsIndeterminate = false;
233 SetStatus("작업 결과와 정리를 확인하고 있습니다.");
234 UpdateActions();
235 return;
236 }
237 if (phase == ScreenPhase.Cancelling || activeJob?.IsCancellationRequested == true || value.State == JobState.Cancelling)
238 {
239 phase = ScreenPhase.Cancelling;
240 SetStatus("중지 요청을 처리하고 있습니다.");
241 Progress.IsIndeterminate = true;
242 }
243 else if (passwordWindow is not null || value.State == JobState.WaitingForPassword)
244 {
245 phase = ScreenPhase.WaitingForPassword;
246 SetStatus("암호 입력을 기다리고 있습니다.");
247 Progress.IsIndeterminate = false;
248 }
249 else
250 {
251 phase = ScreenPhase.Running;
252 Progress.IsIndeterminate = value.TotalBytes is null or <= 0;
253 if (value.TotalBytes > 0)
254 {
255 Progress.Value = Math.Clamp(100.0 * value.ProcessedBytes / value.TotalBytes.Value, 0, 100);
256 }
257 SetStatus($"처리한 크기: {Math.Max(0, value.ProcessedBytes):N0}바이트");
258 }
259 UpdateActions();
260 }
261
262 private void PublishResult(WorkspaceRequest request, WorkspaceResult result)
263 {
264 if (request.Action == WorkspaceAction.Create)
265 {
266 Progress.Value = result.Creation?.Publication?.Published == true ? 100 : 0;
267 ResultSummary.Text = "생성에 사용한 선택은 유지됩니다. 다른 저장 이름은 새로 압축하기에서 선택하세요.";
268 SetStatus(result.Creation is not null ? ZipCreationWorkflow.Describe(result.Creation)
269 : "새 파일의 게시를 확인하지 못했습니다.", result.Creation?.Publication?.Published != true);
270 return;
271 }
272 var succeeded = result.Outcome == WorkspaceOutcome.Completed && result.Error == ArchiveError.None;
273 Progress.Value = succeeded ? 100 : 0;
274 if (request.Action == WorkspaceAction.List && succeeded)
275 {
276 archivePath = request.Sources[0];
277 ArchiveTitle.Text = Path.GetFileName(archivePath);
278 Files.ItemsSource = result.Entries;
279 EmptyState.Text = "이 압축파일에는 표시할 항목이 없습니다.";
280 EmptyState.Visibility = result.Entries.Count == 0 ? Visibility.Visible : Visibility.Collapsed;
281 }
282 var published = result.Entries.Count(entry => entry.Outcome == EntryOutcome.Extracted);
283 var failed = result.Entries.Count(entry => entry.Outcome == EntryOutcome.Failed || entry.Error != ArchiveError.None);
284 ResultSummary.Text = $"결과 항목 {result.Entries.Count:N0}개, 게시 확인 {published:N0}개, 실패 {failed:N0}개";
285 if (succeeded)
286 {
287 SetStatus(request.Action == WorkspaceAction.List ? "파일 목록을 읽었습니다. 내용 검증은 별도입니다." : "ZIP 생성 작업이 완료되었습니다.");
288 }
289 else if (result.Outcome == WorkspaceOutcome.Cancelled && result.Error is ArchiveError.None or ArchiveError.Cancelled)
290 {
291 SetStatus("작업이 중지되었습니다. 결과 파일 상태를 확인하세요.");
292 }
293 else if (result.Outcome == WorkspaceOutcome.Partial)
294 {
295 SetStatus("일부 항목만 처리했습니다. 결과와 검증 상태를 확인하세요.", true);
296 }
297 else
298 {
299 SetStatus(WorkspaceMessages.Error(result.Error), true);
300 }
301 }
302
303 private Task<SecureString?> RequestPasswordAsync(PasswordChallenge challenge, CancellationToken cancellationToken)
304 {
305 return Dispatcher.InvokeAsync<SecureString?>(() =>
306 {
307 cancellationToken.ThrowIfCancellationRequested();
308 if (activeJobId != challenge.JobId || challenge.RequestId == Guid.Empty ||
309 phase is ScreenPhase.Finishing or ScreenPhase.Cancelling || passwordWindow is not null ||
310 !passwordRequests.Add(challenge.RequestId))
311 {
312 throw new ArchiveException(ArchiveError.InvalidPasswordResponse);
313 }
314
315 phase = ScreenPhase.WaitingForPassword;
316 SetStatus(challenge.Attempt > 1 ? "암호를 다시 확인해 입력하세요." : "암호 입력을 기다리고 있습니다.");
317 Progress.IsIndeterminate = false;
318 var dialog = new PasswordWindow { Owner = this };
319 passwordWindow = dialog;
320 UpdateActions();
321 using var registration = cancellationToken.Register(() =>
322 Dispatcher.BeginInvoke(new Action(() =>
323 {
324 if (dialog.IsVisible) { dialog.Close(); }
325 })));
326 try
327 {
328 cancellationToken.ThrowIfCancellationRequested();
329 if (dialog.ShowDialog() == true && !cancellationToken.IsCancellationRequested && activeJobId == challenge.JobId)
330 {
331 return dialog.TakePassword();
332 }
333 RequestStop();
334 return null;
335 }
336 finally
337 {
338 dialog.DiscardPassword();
339 passwordWindow = null;
340 if (phase != ScreenPhase.Finishing)
341 {
342 phase = activeJob?.IsCancellationRequested == true ? ScreenPhase.Cancelling : ScreenPhase.Running;
343 SetStatus(phase == ScreenPhase.Cancelling ? "중지 요청을 처리하고 있습니다." : "작업을 계속하고 있습니다.");
344 Progress.IsIndeterminate = true;
345 }
346 UpdateActions();
347 }
348 }).Task;
349 }
350
351 private void StopJob(object sender, RoutedEventArgs e) => RequestStop();
352
353 private void RequestStop()
354 {
355 if (activeJob is null || phase == ScreenPhase.Finishing) { return; }
356 phase = ScreenPhase.Cancelling;
357 try { activeJob.Cancel(); }
358 catch (AggregateException)
359 {
360 // 취소 관찰자 실패가 있어도 실제 작업 종료를 기다림.
361 }
362 SetStatus("중지 요청을 처리하고 있습니다.");
363 UpdateActions();
364 }
365
366 private void UpdateActions()
367 {
368 var ready = phase == ScreenPhase.Idle;
369 OpenButton.IsEnabled = ready && CanExecute(WorkspaceAction.List);
370 CreateButton.IsEnabled = ready && CanExecute(WorkspaceAction.Create);
371 CreateButton.Content = ZipCreationWorkflow.ValidationEnabled ? "ZIP 생성 검증" : "새로 압축하기";
372 CreateButton.ToolTip = ZipCreationWorkflow.ScopeMessage;
373 RetryCreateButton.IsEnabled = ready && CanExecute(WorkspaceAction.Create) &&
374 creationSources.Length > 0 && creationDestination is not null;
375 ExtractButton.IsEnabled = false;
376 ExtractButton.ToolTip = "안전한 저장 기능의 Windows 검증 후 사용할 수 있습니다.";
377 StopButton.IsEnabled = activeJob is not null &&
378 phase is ScreenPhase.Running or ScreenPhase.WaitingForPassword;
379 }
380
381 private void SetStatus(string message, bool error = false)
382 {
383 Status.Text = message;
384 Status.Foreground = error ? new SolidColorBrush(Color.FromRgb(164, 38, 44)) : SystemColors.ControlTextBrush;
385 }
386
387 private void ShowInstallation(object sender, RoutedEventArgs e)
388 {
389 MessageBox.Show(this,
390 "설치 파일은 준비 중입니다.\n\n예정 흐름: 설치 파일 더블클릭 → 설치 → 완료\n\n기본 앱은 설치 후 Windows 설정에서 직접 선택합니다. 현재 화면은 설정을 변경하지 않습니다.",
391 "설치와 기본 앱 설정", MessageBoxButton.OK, MessageBoxImage.Information);
392 }
393
394 private void OnClosing(object? sender, CancelEventArgs e)
395 {
396 if (phase != ScreenPhase.Idle)
397 {
398 e.Cancel = true;
399 RequestStop();
400 SetStatus("파일 선택이나 작업 정리가 끝난 뒤 창을 닫아주세요.");
401 }
402 }
403}