team-ljyzipelo

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