| 1 | use crate::{ |
| 2 | core, |
| 3 | runtime::{Action, Completion, DEFAULT_CAPACITY, Outcome, Task}, |
| 4 | }; |
| 5 | |
| 6 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 7 | pub enum CloseState { |
| 8 | Open, |
| 9 | Confirming, |
| 10 | Waiting, |
| 11 | Allowed, |
| 12 | } |
| 13 | |
| 14 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 15 | pub enum Status { |
| 16 | Idle, |
| 17 | Running, |
| 18 | CancelRequested, |
| 19 | Completed, |
| 20 | Cancelled, |
| 21 | NativeFailure, |
| 22 | DeliveryFailure, |
| 23 | Panicked, |
| 24 | } |
| 25 | |
| 26 | pub struct Controller { |
| 27 | pub task: Option<Task>, |
| 28 | receiver: Option<core::Receiver>, |
| 29 | pub terminal: Option<Completion>, |
| 30 | pub close: CloseState, |
| 31 | pub status: Status, |
| 32 | pub generation: u64, |
| 33 | pub progress: Option<core::Progress>, |
| 34 | pub delivery_error: Option<core::DeliveryError>, |
| 35 | pub selected: Option<(core::OperationId, u64, usize)>, |
| 36 | pub spawn_error: Option<crate::runtime::StartFailure>, |
| 37 | pub panic: Option<Box<dyn std::any::Any + Send>>, |
| 38 | } |
| 39 | |
| 40 | impl Default for Controller { |
| 41 | fn default() -> Self { |
| 42 | Self { |
| 43 | task: None, |
| 44 | receiver: None, |
| 45 | terminal: None, |
| 46 | close: CloseState::Open, |
| 47 | status: Status::Idle, |
| 48 | generation: 0, |
| 49 | progress: None, |
| 50 | delivery_error: None, |
| 51 | selected: None, |
| 52 | spawn_error: None, |
| 53 | panic: None, |
| 54 | } |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | impl Controller { |
| 59 | pub fn busy(&self) -> bool { |
| 60 | self.task.as_ref().is_some_and(|task| !task.joined()) |
| 61 | } |
| 62 | pub fn start(&mut self, action: Action) -> bool { |
| 63 | self.start_with(action, DEFAULT_CAPACITY) |
| 64 | } |
| 65 | pub fn start_with(&mut self, action: Action, capacity: usize) -> bool { |
| 66 | if self.busy() || self.close != CloseState::Open { |
| 67 | return false; |
| 68 | } |
| 69 | let Some(generation) = self.generation.checked_add(1) else { |
| 70 | return false; |
| 71 | }; |
| 72 | let task = match Task::spawn(action, capacity) { |
| 73 | Ok(task) => task, |
| 74 | Err(error) => { |
| 75 | self.spawn_error = Some(error); |
| 76 | return false; |
| 77 | } |
| 78 | }; |
| 79 | self.receiver = Some(core::Receiver::new(task.id)); |
| 80 | self.task = Some(task); |
| 81 | self.generation = generation; |
| 82 | self.selected = None; |
| 83 | self.terminal = None; |
| 84 | self.delivery_error = None; |
| 85 | self.panic = None; |
| 86 | self.spawn_error = None; |
| 87 | self.progress = None; |
| 88 | self.status = Status::Running; |
| 89 | true |
| 90 | } |
| 91 | pub fn cancel(&mut self) -> bool { |
| 92 | if !self.busy() { |
| 93 | return false; |
| 94 | } |
| 95 | let first = self.task.as_ref().unwrap().cancellation.request(); |
| 96 | if self.status == Status::Running { |
| 97 | self.status = Status::CancelRequested; |
| 98 | } |
| 99 | first |
| 100 | } |
| 101 | pub fn request_close(&mut self) { |
| 102 | if self.close == CloseState::Open { |
| 103 | self.close = if self.busy() { |
| 104 | CloseState::Confirming |
| 105 | } else { |
| 106 | CloseState::Allowed |
| 107 | }; |
| 108 | } |
| 109 | } |
| 110 | pub fn keep_open(&mut self) { |
| 111 | if self.close != CloseState::Allowed { |
| 112 | self.close = CloseState::Open; |
| 113 | } |
| 114 | } |
| 115 | pub fn confirm_close(&mut self) { |
| 116 | if self.close == CloseState::Confirming { |
| 117 | self.close = if self.busy() { |
| 118 | CloseState::Waiting |
| 119 | } else { |
| 120 | CloseState::Allowed |
| 121 | }; |
| 122 | self.cancel(); |
| 123 | } |
| 124 | } |
| 125 | pub fn poll(&mut self) { |
| 126 | let Some(task) = self.task.as_mut() else { |
| 127 | return; |
| 128 | }; |
| 129 | if let Some(events) = &task.events { |
| 130 | // 기본 큐 한도만큼만 처리하며 frame에서 수신을 기다리지 않음. |
| 131 | for event in events.try_iter().take(DEFAULT_CAPACITY) { |
| 132 | match event.validate(self.receiver.as_mut().unwrap()) { |
| 133 | Ok(core::Delivery::Accepted) => { |
| 134 | self.progress = event.progress().or(self.progress) |
| 135 | } |
| 136 | Ok(core::Delivery::IgnoredStale) => {} |
| 137 | Err(error) => { |
| 138 | self.delivery_error.get_or_insert(error); |
| 139 | task.cancellation.request(); |
| 140 | } |
| 141 | } |
| 142 | } |
| 143 | } |
| 144 | if self.terminal.is_none() { |
| 145 | if let Some(done) = &task.completion { |
| 146 | self.terminal = done.try_recv().ok(); |
| 147 | } |
| 148 | } |
| 149 | if let Some(join) = task.poll_join() { |
| 150 | match join { |
| 151 | Ok(Some(completion)) => self.terminal = Some(completion), |
| 152 | Ok(None) => { |
| 153 | if self.terminal.is_none() { |
| 154 | if let Some(done) = &task.completion { |
| 155 | self.terminal = done.try_recv().ok(); |
| 156 | } |
| 157 | } |
| 158 | } |
| 159 | Err(panic) => { |
| 160 | self.panic = Some(panic); |
| 161 | self.status = Status::Panicked; |
| 162 | } |
| 163 | } |
| 164 | if let Some(events) = &task.events { |
| 165 | for event in events.try_iter() { |
| 166 | match event.validate(self.receiver.as_mut().unwrap()) { |
| 167 | Ok(core::Delivery::Accepted) => { |
| 168 | self.progress = event.progress().or(self.progress) |
| 169 | } |
| 170 | Ok(core::Delivery::IgnoredStale) => {} |
| 171 | Err(error) => { |
| 172 | self.delivery_error.get_or_insert(error); |
| 173 | } |
| 174 | } |
| 175 | } |
| 176 | } |
| 177 | if let Some(completion) = &self.terminal { |
| 178 | if let Err(error) = completion.outcome.validate(self.receiver.as_mut().unwrap()) { |
| 179 | self.delivery_error.get_or_insert(error); |
| 180 | } |
| 181 | self.status = if self.panic.is_some() { |
| 182 | Status::Panicked |
| 183 | } else if completion.delivery.is_some() || self.delivery_error.is_some() { |
| 184 | Status::DeliveryFailure |
| 185 | } else if completion.outcome.is_ok() { |
| 186 | Status::Completed |
| 187 | } else if completion.outcome.cancelled() { |
| 188 | Status::Cancelled |
| 189 | } else { |
| 190 | Status::NativeFailure |
| 191 | }; |
| 192 | } else if self.panic.is_none() { |
| 193 | self.status = Status::DeliveryFailure; |
| 194 | } |
| 195 | if self.close == CloseState::Waiting { |
| 196 | self.close = CloseState::Allowed; |
| 197 | } |
| 198 | } |
| 199 | } |
| 200 | pub fn rows(&self) -> Vec<&str> { |
| 201 | if self.status != Status::Completed { |
| 202 | return Vec::new(); |
| 203 | } |
| 204 | match self.terminal.as_ref().map(|c| &c.outcome) { |
| 205 | Some(Outcome::Ustar(t)) => t |
| 206 | .result() |
| 207 | .map(|c| c.value().entries.iter().map(|e| e.name.as_str()).collect()) |
| 208 | .unwrap_or_default(), |
| 209 | Some(Outcome::Zip(_)) => vec!["생성한 sample.zip"], |
| 210 | Some(Outcome::Gzip(_)) => vec!["검증한 GZip 메모리 내용"], |
| 211 | None => Vec::new(), |
| 212 | } |
| 213 | } |
| 214 | pub fn select(&mut self, operation: core::OperationId, generation: u64, index: usize) -> bool { |
| 215 | if self.task.as_ref().map(|t| t.id) != Some(operation) |
| 216 | || generation != self.generation |
| 217 | || index >= self.rows().len() |
| 218 | { |
| 219 | return false; |
| 220 | } |
| 221 | self.selected = Some((operation, generation, index)); |
| 222 | true |
| 223 | } |
| 224 | pub fn selected_bytes(&self) -> Option<&[u8]> { |
| 225 | if self.status != Status::Completed { |
| 226 | return None; |
| 227 | } |
| 228 | let (operation, generation, index) = self.selected?; |
| 229 | if self.task.as_ref()?.id != operation || generation != self.generation { |
| 230 | return None; |
| 231 | } |
| 232 | match &self.terminal.as_ref()?.outcome { |
| 233 | Outcome::Zip(t) => t.result().ok().map(|v| v.value().as_slice()), |
| 234 | Outcome::Gzip(t) => t.result().ok()?.value().bytes.as_deref(), |
| 235 | Outcome::Ustar(t) => { |
| 236 | let value = t.result().ok()?.value(); |
| 237 | let id = &value.entries.get(index)?.id; |
| 238 | value |
| 239 | .files |
| 240 | .iter() |
| 241 | .find(|f| &f.id == id) |
| 242 | .map(|f| f.bytes.as_slice()) |
| 243 | } |
| 244 | } |
| 245 | } |
| 246 | pub fn preview(&self) -> String { |
| 247 | let Some(bytes) = self.selected_bytes() else { |
| 248 | return "목록에서 결과를 선택하세요".into(); |
| 249 | }; |
| 250 | if let Ok(text) = std::str::from_utf8(bytes) { |
| 251 | text.chars().take(2048).collect() |
| 252 | } else { |
| 253 | format!("바이너리 {} bytes", bytes.len()) |
| 254 | } |
| 255 | } |
| 256 | pub fn status_text(&self) -> &'static str { |
| 257 | match self.status { |
| 258 | Status::Idle => "합성 작업을 선택하세요", |
| 259 | Status::Running => "메모리 처리 중", |
| 260 | Status::CancelRequested => "취소 요청됨 / 반환과 종료 대기", |
| 261 | Status::Completed => "메모리 처리 완료", |
| 262 | Status::Cancelled => "작업이 취소 결과를 반환함", |
| 263 | Status::NativeFailure => "메모리 작업 실패", |
| 264 | Status::DeliveryFailure => "UI 전달 실패 / 입력 파일 손상이나 사용자 취소가 아님", |
| 265 | Status::Panicked => "작업 스레드 panic / 완료 결과 없음", |
| 266 | } |
| 267 | } |
| 268 | } |