dialogi 0.4.0

A dialog parser
Documentation
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
#![deny(missing_docs)]

//! A crate to parse dialog lines from a simple markdown inspired format.

use header_parsing::parse_header;
use thiserror::Error;

use std::{
    collections::{HashMap, HashSet},
    fs::{File, read_dir},
    hash::Hash,
    io::{BufRead, BufReader, Error as IoError},
    mem,
    path::{Path, PathBuf},
};

/// A single dialog line consisting of actions to be advanced when the line is displayed, and the text itself.
#[derive(Clone, Debug)]
pub struct DialogLine<P> {
    /// The text of the dialog line.
    pub text: Box<str>,
    /// The actions advanced by the dialog line, identified by parameters of type `P`.
    pub actions: HashSet<P>,
}

/// A full dialog block consisting of the name of the talker, the lines of the dialog, and some final actions to be advanced when the whole text box is fully displayed.
#[derive(Clone, Debug)]
pub struct DialogBlock<P> {
    /// The speaker name of the dialog block.
    pub name: Box<str>,
    /// The text lines of the dialog block.
    pub lines: Vec<DialogLine<P>>,
    /// The actions advanced by the dialog block, identified by parameters of type `P`.
    pub final_actions: HashSet<P>,
}

impl<P> DialogBlock<P> {
    fn new() -> Self {
        Self {
            name: "".into(),
            lines: Vec::new(),
            final_actions: HashSet::new(),
        }
    }

    fn is_empty(&self) -> bool {
        self.name.is_empty() && self.lines.is_empty() && self.final_actions.is_empty()
    }

    /// The text lines of a dialog block as string references.
    pub fn lines(&self) -> impl Iterator<Item = &str> {
        self.lines.iter().map(|line| line.text.as_ref())
    }
}

/// A parameter to define an action of the dialog.
pub trait DialogParameter: Sized {
    /// The parameter context, which might be important for creation by name.
    type Context;
    /// The method to create a parameter. It might access some context and returns some new dialog parameter or none.
    fn create(name: &str, context: &mut Self::Context) -> Option<Self>;
}

/// A change to define an how actions are applied.
pub trait DialogChange: Sized {
    /// The parameter to apply this change.
    type Parameter: DialogParameter + Clone + Eq + Hash;

    /// Creates the change of the parameter back to the default value.
    fn default_change(parameter: Self::Parameter) -> Self;

    /// Creates a change of the parameter to the specified value.
    fn value_change(
        parameter: Self::Parameter,
        value: &str,
        context: &mut <<Self as DialogChange>::Parameter as DialogParameter>::Context,
    ) -> Self;
}

/// Defines a full sequential dialog as a sequence of dialog blocks.
pub struct DialogSequence<C, P> {
    /// The sequence of dialog blocks.
    pub blocks: Vec<DialogBlock<P>>,
    /// The changes to be applied by the dialog parameters.
    pub changes: HashMap<P, Vec<C>>,
}

/// A trait to parse dialog sequences into, identified by a name.
pub trait DialogMap<C: DialogChange>: Default {
    /// Adds a single sequential dialog into the dialog map.
    fn add(&mut self, key: Vec<Box<str>>, value: DialogSequence<C, C::Parameter>);
}

impl<C: DialogChange> DialogMap<C> for HashMap<Vec<Box<str>>, DialogSequence<C, C::Parameter>> {
    fn add(&mut self, key: Vec<Box<str>>, value: DialogSequence<C, C::Parameter>) {
        self.insert(key, value);
    }
}

impl<C: DialogChange> DialogMap<C> for Vec<DialogSequence<C, C::Parameter>> {
    fn add(&mut self, _key: Vec<Box<str>>, value: DialogSequence<C, C::Parameter>) {
        self.push(value);
    }
}

/// An error type returned when parsing a the dialog structure fails.
#[derive(Debug, Error)]
pub enum ParsingError {
    /// Colon parameters are not allowed to have a value supplied.
    #[error("Colon parameters are not allowed to have a value supplied")]
    ColonParameterWithValues,
    /// Error while opening story file.
    #[error("Error while opening story file {path}: {source}")]
    OpeningError {
        /// The path to the story file.
        path: PathBuf,
        /// The underlying IO error.
        source: IoError,
    },
    /// Error while reading story file.
    #[error("Error while reading story file {path}: {source}")]
    ReadingError {
        /// The path to the story file.
        path: PathBuf,
        /// The underlying IO error.
        source: IoError,
    },
    /// Subheader found without a matching header.
    #[error("Subheader found without a matching header")]
    SubheaderWithoutHeader,
    /// Invalid dialog format.
    #[error("Invalid dialog format")]
    InvalidIndentation,
    /// Invalid indentation level.
    #[error("Invalid indentation level")]
    IndentationTooHigh,
    /// Default parameters cannot have a value supplied.
    #[error("Default parameters cannot have a value supplied")]
    DefaultParameterWithValue,
    /// Duplicate definition of change.
    #[error("Duplicate definition of change: {0}")]
    DuplicateDefinitionOfChange(Box<str>),
}

impl<C: DialogChange> DialogSequence<C, C::Parameter> {
    fn new() -> Self {
        Self {
            blocks: Vec::new(),
            changes: HashMap::new(),
        }
    }

    /// Loads a new dialog file from a specified path and returns a new text map.
    ///
    /// If the path is a folder, it will be scanned for `.pk` files and sub folders.
    /// If the path is a file, it will be parsed as directly using the `.pk` parsing format.
    pub fn map_from_path<M: DialogMap<C>>(
        path: &Path,
        context: &mut <C::Parameter as DialogParameter>::Context,
    ) -> Result<M, ParsingError> {
        let mut text_map = M::default();
        Self::fill_map_from_path(path, &mut text_map, context)?;
        Ok(text_map)
    }

    /// Loads a new dialog file from a specified path into the supplied text map.
    ///
    /// If the path is a folder, it will be scanned for `.pk` files and sub folders.
    /// If the path is a file, it will be parsed as directly using the `.pk` parsing format.
    pub fn fill_map_from_path<M: DialogMap<C>>(
        path: &Path,
        text_map: &mut M,
        context: &mut <C::Parameter as DialogParameter>::Context,
    ) -> Result<(), ParsingError> {
        Self::named_fill_map_from_path(path, text_map, Vec::new(), context)
    }

    fn named_fill_map_from_path<M: DialogMap<C>>(
        path: &Path,
        text_map: &mut M,
        default_name: Vec<Box<str>>,
        context: &mut <C::Parameter as DialogParameter>::Context,
    ) -> Result<(), ParsingError> {
        let Ok(dirs) = read_dir(path) else {
            return Self::fill_map_from_file(path, default_name, text_map, context);
        };

        for entry in dirs {
            let Ok(dir) = entry else {
                eprintln!("Warning: failed to read entry in {}", path.display());
                continue;
            };
            Self::try_fill_submap_from_path(&dir.path(), default_name.clone(), text_map, context)?;
        }

        Ok(())
    }

    fn try_fill_submap_from_path<M: DialogMap<C>>(
        path: &Path,
        mut relative_name: Vec<Box<str>>,
        text_map: &mut M,
        context: &mut <C::Parameter as DialogParameter>::Context,
    ) -> Result<(), ParsingError> {
        let Some(name) = path.file_stem() else {
            return Ok(());
        };

        let Some(name) = name.to_str() else {
            return Ok(());
        };

        relative_name.push(name.into());
        Self::named_fill_map_from_path(path, text_map, relative_name, context)
    }

    fn handle_content_line(
        &mut self,
        line: &str,
        current_block: &mut DialogBlock<C::Parameter>,
        path: &mut Vec<Box<str>>,
        context: &mut <C::Parameter as DialogParameter>::Context,
    ) -> Result<(), ParsingError> {
        if line.trim().is_empty() {
            if !current_block.is_empty() {
                self.blocks
                    .push(mem::replace(current_block, DialogBlock::new()));
            }

            return Ok(());
        }

        let mut spaces = 0;
        let mut chars = line.chars();
        let mut c = chars.next().unwrap();
        while c == ' ' {
            spaces += 1;
            c = chars.next().unwrap();
        }
        let first = c;

        if first == '-' {
            if spaces % 2 != 0 {
                return Err(ParsingError::InvalidIndentation);
            }
            let level = spaces / 2;
            if level > path.len() {
                return Err(ParsingError::IndentationTooHigh);
            }
            while path.len() > level {
                path.pop();
            }
            let line = line[(spaces + 1)..].trim();
            let (name_end, value) = line
                .split_once(' ')
                .map_or((line, ""), |(name, value)| (name.trim(), value.trim()));
            let default = name_end.ends_with('!');

            if default && !value.is_empty() {
                return Err(ParsingError::DefaultParameterWithValue);
            }

            let colon_end = name_end.ends_with(':');

            let name_end: Box<str> = if default || colon_end {
                &name_end[0..(name_end.len() - 1)]
            } else {
                name_end
            }
            .into();

            if colon_end {
                if !value.is_empty() {
                    return Err(ParsingError::ColonParameterWithValues);
                }

                path.push(name_end);
                return Ok(());
            }

            let parameter_name = path.iter().rev().fold(name_end.clone(), |name, element| {
                format!("{element}:{name}").into()
            });

            path.push(name_end);

            let Some(parameter) = DialogParameter::create(&parameter_name, context) else {
                return Ok(());
            };

            if current_block.final_actions.contains(&parameter) {
                return Err(ParsingError::DuplicateDefinitionOfChange(parameter_name));
            }

            let change = if default {
                DialogChange::default_change(parameter.clone())
            } else {
                DialogChange::value_change(parameter.clone(), value, context)
            };

            if let Some(map) = self.changes.get_mut(&parameter) {
                map.push(change);
            } else {
                self.changes.insert(parameter.clone(), vec![change]);
            }

            current_block.final_actions.insert(parameter);

            return Ok(());
        }

        path.clear();

        let (Some((name, text)), 0) = (line.split_once(':'), spaces) else {
            current_block.lines.push(DialogLine {
                text: line.trim().into(),
                actions: mem::take(&mut current_block.final_actions),
            });

            return Ok(());
        };

        let text = text.trim();

        let parameters = if current_block.is_empty() {
            mem::take(&mut current_block.final_actions)
        } else {
            let old = mem::replace(current_block, DialogBlock::new());
            self.blocks.push(old);
            HashSet::new()
        };

        current_block.name = name.trim().into();
        if text.is_empty() {
            current_block.final_actions = parameters;
        } else {
            current_block.lines = vec![DialogLine {
                text: text.into(),
                actions: parameters,
            }];
        }

        Ok(())
    }

    fn fill_map_from_file<M: DialogMap<C>>(
        path: &Path,
        default_name: Vec<Box<str>>,
        text_map: &mut M,
        context: &mut <C::Parameter as DialogParameter>::Context,
    ) -> Result<(), ParsingError> {
        let valid_path = path.extension().is_some_and(|e| e == "pk");

        if !valid_path {
            return Ok(());
        }

        let story_file = File::open(path).map_err(|source| ParsingError::OpeningError {
            path: path.to_path_buf(),
            source,
        })?;
        let mut current_block = DialogBlock::new();
        let mut current_sequence = Self::new();
        let mut name = Vec::new();
        let mut parameter_path = Vec::new();

        for line in BufReader::new(story_file).lines() {
            let line = line.map_err(|source| ParsingError::ReadingError {
                path: path.to_path_buf(),
                source,
            })?;

            if let Some(success) = parse_header(&mut name, &line) {
                let Ok(changes) = success else {
                    return Err(ParsingError::SubheaderWithoutHeader);
                };

                if !current_block.is_empty() {
                    current_sequence.blocks.push(current_block);
                    current_block = DialogBlock::new();
                }

                if !current_sequence.blocks.is_empty() {
                    let mut new_name = default_name.clone();
                    new_name.extend(changes.path.clone());
                    text_map.add(new_name, current_sequence);
                }
                current_sequence = Self::new();

                changes.apply();

                continue;
            }

            current_sequence.handle_content_line(
                &line,
                &mut current_block,
                &mut parameter_path,
                context,
            )?;
        }

        if !current_block.is_empty() {
            current_sequence.blocks.push(current_block);
        }

        if !current_sequence.blocks.is_empty() {
            let mut new_name = default_name;
            new_name.extend(name);
            text_map.add(new_name, current_sequence);
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write as _;

    #[derive(Clone, Debug, PartialEq, Eq, Hash)]
    struct TestParameter(Box<str>);

    impl DialogParameter for TestParameter {
        type Context = ();
        fn create(name: &str, _context: &mut ()) -> Option<Self> {
            Some(TestParameter(name.into()))
        }
    }

    #[derive(Debug)]
    #[allow(dead_code)]
    enum TestChange {
        Default(TestParameter),
        Value(TestParameter, Box<str>),
    }

    impl DialogChange for TestChange {
        type Parameter = TestParameter;

        fn default_change(parameter: TestParameter) -> Self {
            TestChange::Default(parameter)
        }

        fn value_change(parameter: TestParameter, value: &str, _context: &mut ()) -> Self {
            TestChange::Value(parameter, value.into())
        }
    }

    type TestSequence = DialogSequence<TestChange, TestParameter>;
    type TestMap = Vec<TestSequence>;

    use std::sync::atomic::{AtomicU32, Ordering};

    static TEST_COUNTER: AtomicU32 = AtomicU32::new(0);

    fn parse_file(content: &str) -> Result<TestMap, ParsingError> {
        let id = TEST_COUNTER.fetch_add(1, Ordering::Relaxed);
        let dir = std::env::temp_dir().join(format!("dialogi_test_{id}"));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("test.pk");
        let mut file = File::create(&path).unwrap();
        file.write_all(content.as_bytes()).unwrap();
        let result = TestSequence::map_from_path::<TestMap>(&path, &mut ());
        std::fs::remove_file(&path).unwrap();
        let _ = std::fs::remove_dir(&dir);
        result
    }

    #[test]
    fn simple_text_blocks() {
        let sequences = parse_file("# Scene\n\nHello world\n\nSecond block").unwrap();
        assert_eq!(sequences.len(), 1);
        assert_eq!(sequences[0].blocks.len(), 2);
        assert_eq!(sequences[0].blocks[0].name.as_ref(), "");
        assert_eq!(sequences[0].blocks[0].lines[0].text.as_ref(), "Hello world");
        assert_eq!(
            sequences[0].blocks[1].lines[0].text.as_ref(),
            "Second block"
        );
    }

    #[test]
    fn talker_with_text() {
        let sequences = parse_file("# Scene\n\nAlice: Hi!\n\nBob: Hello").unwrap();
        assert_eq!(sequences[0].blocks.len(), 2);
        assert_eq!(sequences[0].blocks[0].name.as_ref(), "Alice");
        assert_eq!(sequences[0].blocks[0].lines[0].text.as_ref(), "Hi!");
        assert_eq!(sequences[0].blocks[1].name.as_ref(), "Bob");
    }

    #[test]
    fn talker_multiline() {
        let sequences = parse_file("# Scene\n\nAlice:\nLine 1\nLine 2").unwrap();
        assert_eq!(sequences[0].blocks[0].name.as_ref(), "Alice");
        assert_eq!(sequences[0].blocks[0].lines.len(), 2);
        assert_eq!(sequences[0].blocks[0].lines[0].text.as_ref(), "Line 1");
        assert_eq!(sequences[0].blocks[0].lines[1].text.as_ref(), "Line 2");
    }

    #[test]
    fn events_with_values() {
        let sequences = parse_file("# Scene\n\n- Mood happy\nAlice: Hi!").unwrap();
        assert!(
            sequences[0]
                .changes
                .contains_key(&TestParameter("Mood".into()))
        );
        assert!(
            sequences[0].blocks[0]
                .final_actions
                .contains(&TestParameter("Mood".into()))
        );
        assert_eq!(sequences[0].blocks[1].name.as_ref(), "Alice");
    }

    #[test]
    fn default_event() {
        let sequences = parse_file("# Scene\n\n- Mood!\nSome text").unwrap();
        assert!(
            sequences[0]
                .changes
                .contains_key(&TestParameter("Mood".into()))
        );
    }

    #[test]
    fn hierarchical_event_path() {
        let sequences =
            parse_file("# Scene\n\n- Path:\n  - To:\n    - Param Value\nSome text").unwrap();
        assert!(
            sequences[0]
                .changes
                .contains_key(&TestParameter("Path:To:Param".into()))
        );
    }

    #[test]
    fn multiple_headers() {
        let sequences = parse_file("# Scene 1\n\nText 1\n\n# Scene 2\n\nText 2").unwrap();
        assert_eq!(sequences.len(), 2);
    }

    #[test]
    fn invalid_indentation() {
        let result = parse_file("# Scene\n\n - Param Value");
        assert!(matches!(result, Err(ParsingError::InvalidIndentation)));
    }

    #[test]
    fn indentation_too_high() {
        let result = parse_file("# Scene\n\n    - Param Value");
        assert!(matches!(result, Err(ParsingError::IndentationTooHigh)));
    }

    #[test]
    fn default_parameter_with_value() {
        let result = parse_file("# Scene\n\n- Param! Value");
        assert!(matches!(
            result,
            Err(ParsingError::DefaultParameterWithValue)
        ));
    }

    #[test]
    fn empty_lines_separate_blocks() {
        let sequences = parse_file("# Scene\n\nLine 1\n\nLine 2\n\nLine 3").unwrap();
        assert_eq!(sequences[0].blocks.len(), 3);
    }

    #[test]
    fn narrator_text_has_empty_name() {
        let sequences = parse_file("# Scene\n\nNarrator text here").unwrap();
        assert_eq!(sequences[0].blocks[0].name.as_ref(), "");
    }

    #[test]
    fn colon_parameter_with_value_rejected() {
        let result = parse_file("# Scene\n\n- Path: Value");
        assert!(matches!(
            result,
            Err(ParsingError::ColonParameterWithValues)
        ));
    }

    #[test]
    fn nonexistent_file() {
        let result =
            TestSequence::map_from_path::<TestMap>(Path::new("/nonexistent/test.pk"), &mut ());
        assert!(matches!(result, Err(ParsingError::OpeningError { .. })));
    }

    #[test]
    fn non_pk_file_ignored() {
        let id = TEST_COUNTER.fetch_add(1, Ordering::Relaxed);
        let dir = std::env::temp_dir().join(format!("dialogi_test_ext_{id}"));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("test.txt");
        std::fs::write(&path, "# Scene\n\nHello").unwrap();
        let result = TestSequence::map_from_path::<TestMap>(&path, &mut ()).unwrap();
        assert!(result.is_empty());
        std::fs::remove_file(&path).unwrap();
        let _ = std::fs::remove_dir(&dir);
    }
}