1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
use crate::*;
use anyhow::Result;
use serde::Serialize;
use std::{path::Path, pin::pin};
use stream_future::stream;
use trylog::macros::*;
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "t", content = "data")]
pub enum OpenGameStatus {
LoadProfile,
CreateRuntime,
LoadPlugin(String, usize, usize),
GamePlugin,
LoadResource,
LoadParagraph,
LoadSettings,
LoadGlobalRecords,
LoadRecords,
Loaded,
}
impl From<OpenStatus> for OpenGameStatus {
fn from(value: OpenStatus) -> Self {
match value {
OpenStatus::LoadProfile => Self::LoadProfile,
OpenStatus::CreateRuntime => Self::CreateRuntime,
OpenStatus::LoadPlugin(name, i, len) => Self::LoadPlugin(name, i, len),
OpenStatus::GamePlugin => Self::GamePlugin,
OpenStatus::LoadResource => Self::LoadResource,
OpenStatus::LoadParagraph => Self::LoadParagraph,
}
}
}
pub struct GameViewModel<M: SettingsManager> {
context: Option<Context>,
current_record: ActionRecord,
current_raw_context: Option<RawContext>,
settings_manager: M,
settings: Option<Settings>,
records: Vec<ActionRecord>,
global_record: Option<GlobalRecord>,
}
impl<M: SettingsManager> GameViewModel<M> {
pub fn new(settings_manager: M) -> Self {
Self {
settings_manager,
context: None,
current_record: ActionRecord::default(),
current_raw_context: None,
settings: None,
records: vec![],
global_record: None,
}
}
#[stream(OpenGameStatus, lifetime = "'a")]
pub async fn open_game<'a>(
&'a mut self,
paths: &'a [impl AsRef<Path>],
frontend_type: FrontendType,
) -> Result<()> {
let context = Context::open(paths, frontend_type);
let mut context = pin!(context);
while let Some(status) = context.next().await {
yield status.into();
}
let context = context.await?;
yield OpenGameStatus::LoadSettings;
let settings = unwrap_or_default_log!(
self.settings_manager.load_settings(),
"Load settings failed"
);
self.settings = Some(settings);
yield OpenGameStatus::LoadGlobalRecords;
let global_record = unwrap_or_default_log!(
self.settings_manager
.load_global_record(&context.game().config.title),
"Load global records failed"
);
self.global_record = Some(global_record);
yield OpenGameStatus::LoadRecords;
self.records = unwrap_or_default_log!(
self.settings_manager
.load_records(&context.game().config.title),
"Load records failed"
);
self.context = Some(context);
yield OpenGameStatus::Loaded;
Ok(())
}
pub fn context(&self) -> &Context {
self.context
.as_ref()
.expect("should be called after open_game")
}
pub fn context_mut(&mut self) -> &mut Context {
self.context
.as_mut()
.expect("should be called after open_game")
}
pub fn record(&self) -> &ActionRecord {
&self.current_record
}
pub fn settings(&self) -> &Settings {
self.settings
.as_ref()
.expect("should be called after open_game")
}
pub fn set_settings(&mut self, settings: Settings) {
self.settings = Some(settings);
}
pub fn records(&self) -> &[ActionRecord] {
&self.records
}
pub fn global_record(&self) -> &GlobalRecord {
self.global_record
.as_ref()
.expect("should be called after open_game")
}
pub fn global_record_mut(&mut self) -> &mut GlobalRecord {
self.global_record
.as_mut()
.expect("should be called after open_game")
}
pub fn avaliable_locale(&self) -> impl Iterator<Item = &Locale> {
self.context().game().paras.keys()
}
pub fn init_new(&mut self) {
let ctx = self.context().game().start_context();
self.current_record = ActionRecord::default();
self.current_raw_context = None;
self.context_mut().set_context(ctx);
}
pub fn init_context(&mut self, record: ActionRecord) {
let mut ctx = record.last_ctx_with_game(self.context().game());
self.current_record = record;
self.current_raw_context = self.current_record.history.last().cloned();
log::debug!("Context: {:?}", self.current_raw_context);
ctx.cur_act += 1;
self.context_mut().set_context(ctx);
}
pub fn init_context_by_index(&mut self, index: usize) {
self.init_context(self.records()[index].clone())
}
fn push_history(&mut self, ctx: &RawContext) {
let cur_text = self
.context()
.game()
.find_para(
&self.context().game().config.base_lang,
&ctx.cur_base_para,
&ctx.cur_para,
)
.and_then(|p| p.texts.get(ctx.cur_act));
let is_text = cur_text
.map(|line| matches!(line, Line::Text(_)))
.unwrap_or_default();
if is_text {
self.current_record.history.push(ctx.clone());
}
}
pub fn next_run(&mut self) -> bool {
let ctx = self.context_mut().next_run();
if let Some(ctx) = &ctx {
self.push_history(ctx);
self.global_record_mut().update(ctx);
log::debug!("{:?}", ctx);
}
self.current_raw_context = ctx;
self.current_raw_context.is_some()
}
pub fn next_back_run(&mut self) -> bool {
if self.current_record.history.len() <= 1 {
log::debug!("No action in the history.");
false
} else {
self.current_record.history.pop();
self.current_raw_context = self.current_record.history.last().cloned();
debug_assert!(self.current_raw_context.is_some());
let mut ctx = self
.current_raw_context
.clone()
.expect("current raw context cannot be None");
ctx.cur_act += 1;
self.context_mut().set_context(ctx);
true
}
}
pub fn current_run(&self) -> Option<&RawContext> {
self.current_raw_context.as_ref()
}
pub fn current_title(&self) -> Option<&String> {
self.context()
.current_paragraph_title(&self.settings().lang)
}
pub fn current_action(&self) -> Option<Action> {
self.current_run().map(|raw_ctx| {
unwrap_or_default_log!(
self.context().get_action(&self.settings().lang, raw_ctx),
"Cannot get action"
)
})
}
pub fn current_actions(&self) -> Option<(Action, Option<Action>)> {
self.current_run().map(|raw_ctx| self.get_actions(raw_ctx))
}
fn get_actions(&self, raw_ctx: &RawContext) -> (Action, Option<Action>) {
let action = unwrap_or_default_log!(
self.context().get_action(&self.settings().lang, raw_ctx),
"Cannot get action"
);
let base_action = self.settings().sub_lang.as_ref().map(|sub_lang| {
unwrap_or_default_log!(
self.context().get_action(sub_lang, raw_ctx),
"Cannot get sub action"
)
});
(action, base_action)
}
pub fn switch(&mut self, i: usize) {
log::debug!("Switch {}", i);
self.context_mut().switch(i);
}
pub fn save_current_to(&mut self, index: usize) {
let record = self.current_record.clone();
if index >= self.records.len() {
self.records.push(record);
} else {
self.records[index] = record;
}
}
pub fn save_settings(&self) -> Result<()> {
let game = &self.context().game().config.title;
self.settings_manager.save_settings(self.settings())?;
self.settings_manager
.save_global_record(game, self.global_record())?;
self.settings_manager.save_records(game, self.records())?;
Ok(())
}
pub fn current_visited(&self) -> bool {
self.current_run()
.map(|ctx| self.global_record().visited(ctx))
.unwrap_or_default()
}
pub fn records_text(&self) -> impl Iterator<Item = ActionText> + '_ {
self.records().iter().map(|record| {
let raw_ctx = record
.last_ctx()
.expect("there should be at least one RawContext in the ActionRecord");
let action = unwrap_or_default_log!(
self.context().get_action(&self.settings().lang, raw_ctx),
"Cannot get action"
);
if let Action::Text(action) = action {
action
} else {
panic!("action in the record should be text action")
}
})
}
pub fn current_history(
&self,
) -> impl DoubleEndedIterator<Item = (Action, Option<Action>)> + '_ {
self.record()
.history
.iter()
.map(|raw_ctx| self.get_actions(raw_ctx))
}
}