printobserver-core 0.16.0

Supervision logic for printobserver.
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
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
//! The G-code index reads a slicer's plan out of a file streamed into it.
//!
//! Each file here is `PrusaSlicer`'s syntax, written out in the test so that
//! what it plans is plain beside what is asserted, and each is streamed into
//! the real builder through [`GcodeSink`] — the interface the printer port's
//! whole-file read feeds — in pieces that cut lines part-way, as a download
//! arrives. The server's journeys run the same builder over a real slice.

use core::fmt::Write as _;
use core::future::Future as _;
use core::ops::ControlFlow;
use core::pin::pin;
use core::task::{Context, Poll, Waker};

use printobserver_core::gcode_index::{Claimed, GcodeIndexes};

use printobserver_core::gcode_index::{
    PLANNED_CHANGE_REACH_BYTES, PlannedChange, PlannedChangeKind, PlannedSegment,
};
use printobserver_core::{GcodeIndex, IndexBuilder, PlanFact, PlanMismatch, SetValue};
use printobserver_printer_api::GcodeSink as _;
use printobserver_types::PrintId;

/// Stream a file into the builder in pieces of `piece` bytes.
fn indexed_in(text: &str, piece: usize) -> GcodeIndex {
    let mut builder = IndexBuilder::new();
    for chunk in text.as_bytes().chunks(piece) {
        assert_eq!(builder.take(chunk), ControlFlow::Continue(()));
    }
    builder.finish()
}

/// Stream a file into the builder in pieces that cut its lines.
fn indexed(text: &str) -> GcodeIndex {
    indexed_in(text, 7)
}

/// The offset just past the first line carrying `needle`, which is where a
/// position has read that line.
fn past(text: &str, needle: &str) -> i64 {
    let at = text.find(needle).expect("the file carries the line");
    let end = text[at..]
        .find('\n')
        .map_or(text.len(), |newline| at + newline + 1);
    i64::try_from(end).expect("a small offset")
}

/// Two layers of a part with a support layer under an overhang, its time
/// estimates in both modes, its fan and flow, and two labelled objects.
const PLATE: &str = "\
; generated by PrusaSlicer 2.9.6
M486 S0
M486 Abox.stl
M486 S-1
M486 S1
M486 A\"tower.stl\"
M486 S-1
M83
G90
M73 P0 R10
M73 Q0 S11
M221 S100 ; set flow to 100%
;TYPE:Custom
G1 X0 Y0 E5 ; the purge line
;LAYER_CHANGE
;Z:0.2
;HEIGHT:0.2
M107
M486 S0
;TYPE:External perimeter
G1 X10 Y10 F600
G1 X20 Y10 E1.5
G1 X20 Y20 E1.5
M486 S-1
M486 S1
G1 X50 Y50
G1 X60 Y50 E1.5
;TYPE:Support material
G1 X60 Y55 E0.4
M486 S-1
M73 P50 R5
M73 Q50 S6
;LAYER_CHANGE
;Z:0.4
;HEIGHT:0.2
M106 S255
M486 S0
G1 X10 Y10
G1 E0.8 ; an unretraction lays no path
G1 X12 Y10 E0.2 ; still support material, carried across the change
;TYPE:Overhang perimeter
G2 X22 Y10 I5 J0 E1.2
G1 X30 Y10 E-0.8 ; a wipe retracts
M486 S-1
M221 S95
;TYPE:Custom
G1 X0 Y200 E1 ; the end G-code
M73 P100 R0
";

/// At each layer the plan names the layer, its height, every type it laid
/// material under — support and overhang among them — the final height, and
/// the slicer's time left in the normal mode.
#[test]
fn each_layer_names_its_height_its_types_and_the_time_left() {
    let index = indexed(PLATE);

    let first = index.plan_at(past(PLATE, "G1 X20 Y20 E1.5"));
    assert_eq!((first.layer, first.z_mm), (Some(1), Some(0.2)));
    assert_eq!(
        first.types,
        vec![
            "External perimeter".to_owned(),
            "Support material".to_owned()
        ],
        "a layer's types are every type it lays, ahead of the position too"
    );
    assert_eq!(first.final_z_mm, Some(0.4));
    assert_eq!(first.minutes_left, Some(10));

    let second = index.plan_at(past(PLATE, "M73 P100 R0"));
    assert_eq!(second.layer, Some(2));
    assert_eq!(second.z_mm, Some(0.4));
    assert_eq!(
        second.types,
        vec![
            "Support material".to_owned(),
            "Overhang perimeter".to_owned()
        ],
        "the type in force across a layer change counts, and Custom never does"
    );
    assert_eq!(second.minutes_left, Some(0));
    assert_eq!(index.layer_count(), 2);
    assert_eq!(index.busiest_layer().map(|(types, _)| types), Some(2));
    assert_eq!(index.bytes(), u64::try_from(PLATE.len()).expect("small"));
}

/// A marker the printer is part-way through is not yet in force: the position
/// must lie past the whole of its line.
#[test]
fn a_marker_counts_once_its_whole_line_is_read() {
    let index = indexed(PLATE);
    let change = past(PLATE, "M73 P50 R5");

    assert_eq!(index.plan_at(change - 1).minutes_left, Some(10));
    assert_eq!(index.plan_at(change).minutes_left, Some(5));
    let before = index.plan_at(past(PLATE, "G1 X0 Y0 E5"));
    assert_eq!(before.layer, None, "the start G-code is in no layer");
    assert!(before.types.is_empty());
    assert_eq!(index.plan_at(-1).minutes_left, None);
}

/// The flow and fan are what the file last set by the position, and a change
/// made since is beside it; a fan with another number is not the part fan.
#[test]
fn the_flow_and_the_fan_are_what_the_file_set_by_the_position() {
    let index = indexed(PLATE);
    let first = past(PLATE, "G1 X20 Y20 E1.5");
    let last = past(PLATE, "M73 P100 R0");

    let plan = index.plan_with(first, Some(1.05), None);
    assert_eq!(
        plan.flow_factor,
        Some(SetValue {
            file: Some(1.0),
            changed: Some(1.05)
        })
    );
    assert_eq!(
        plan.fan_percent,
        Some(SetValue {
            file: Some(0.0),
            changed: None
        })
    );
    let plan = index.plan_at(last);
    assert_eq!(plan.flow_factor.and_then(|set| set.file), Some(0.95));
    assert_eq!(plan.fan_percent.and_then(|set| set.file), Some(100.0));
    assert_eq!(
        index.flow_at(last).map(|set| set.at),
        u64::try_from(past(PLATE, "M221 S95")).ok()
    );

    let other_fan = indexed("M106 P1 S255\nM106 S127.5\n");
    assert_eq!(other_fan.fan_at(100).map(|set| set.value), Some(50.0));
}

/// Each labelled object is counted once, unnamed, and covers the rectangle its
/// material reached, the top of a clockwise half circle included; moves
/// outside any object, and moves that lay nothing, reach none.
#[test]
fn each_object_covers_the_bed_area_its_material_reached() {
    let index = indexed(PLATE);
    let plan = index.plan_at(past(PLATE, "M73 P100 R0"));

    assert_eq!(plan.objects, vec![[10, 10, 22, 20], [50, 50, 60, 55]]);
    assert_eq!(plan.object_count, Some(2));
    assert!(plan.unknown.is_empty(), "{:?}", plan.unknown);
}

/// A file carrying no markers at all builds an index all the same, and every
/// fact the file does not state is named as unknown rather than left out.
#[test]
fn a_file_without_markers_says_which_facts_are_unknown() {
    let bare = "G28\nG1 X10 Y10 E1\nG1 X20 Y10 E1\n";
    let index = indexed(bare);
    let plan = index.plan_at(i64::try_from(bare.len()).expect("small"));

    assert_eq!(plan.layer, None);
    assert!(plan.types.is_empty());
    assert!(plan.objects.is_empty());
    assert_eq!(
        plan.object_count, None,
        "no object labelled, yet a count was given"
    );
    assert_eq!(
        plan.unknown,
        vec![
            PlanFact::Layer,
            PlanFact::FinalZ,
            PlanFact::Types,
            PlanFact::MinutesLeft,
            PlanFact::FlowFactor,
            PlanFact::FanPercent,
            PlanFact::Objects,
        ]
    );
    assert_eq!(index.lines(), 3);
    assert_eq!(index.entries(), 0);
    assert!(index.resident_bytes() > 0);
}

/// Only the silent mode's estimates, a flow nobody set and no labels: the time
/// left, the flow and the types are unknown, the layers are not.
#[test]
fn silent_mode_estimates_alone_leave_the_time_left_unknown() {
    let silent = ";LAYER_CHANGE\n;Z:0.3\nM73 Q10 S50\nM73 R5\nG1 X1 Y1 E1\n";
    let plan = indexed(silent).plan_at(i64::try_from(silent.len()).expect("small"));

    assert_eq!(plan.minutes_left, None);
    assert!(plan.unknown.contains(&PlanFact::MinutesLeft));
    assert!(plan.unknown.contains(&PlanFact::Types));
    assert!(plan.unknown.contains(&PlanFact::FlowFactor));
    assert!(!plan.unknown.contains(&PlanFact::Layer));
    assert_eq!(plan.final_z_mm, Some(0.3));
}

/// Absolute extrusion and absolute or relative axes are followed, `G92` and
/// `G28` move the reckoning without laying anything, and a radius arc reaches
/// the side of its chord its direction sweeps.
#[test]
fn the_reckoning_follows_every_mode_a_slicer_writes() {
    let text = "\
M486 S3
M486 Apart
M82
G90
G92 E0
G1 X10 Y10 E1
G1 X20 Y10 E2
G1 X30 Y10 E1.5 ; less than before: a retraction
G91
G1 X5 Y0 E0.5
G90
G92 X0 Y0
G1 X1 Y0 E3
G28 X
G28
G3 X2 Y0 R1 E4
G92
M486 S-1
M486 S7
G1 X1000000 Y1 E1 ; beyond any machine's travel
M486 S-1
M486 S8
G1 X5 Y5 ; a travel lays nothing
M486 S-1
";
    let plan = indexed_in(text, 3).plan_at(i64::try_from(text.len()).expect("small"));
    assert_eq!(
        plan.objects[0],
        [0, -1, 35, 10],
        "the half circle below its chord was not reached, or more than it"
    );
    assert_eq!(
        plan.objects[1],
        [0, 0, 0, 1],
        "an X beyond any machine's travel was read as a place"
    );
    assert_eq!(
        plan.objects.len(),
        2,
        "an object that laid nothing is no object"
    );
}

/// A line longer than any G-code line is read as nothing, a carriage return
/// and a checksum end a command, and the last line counts without a newline.
#[test]
fn an_overlong_line_is_nothing_and_the_last_line_needs_no_newline() {
    let text = format!(
        ";LAYER_CHANGE\r\n;Z:0.2\r\nN12 M73 P1 R9*55\r\n;TYPE:{}\n;TYPE:Perimeter\nG1 X1 Y1 E1\n;LAYER_CHANGE",
        "x".repeat(5000)
    );
    let index = indexed_in(&text, 1024);
    let plan = index.plan_at(i64::try_from(text.len()).expect("small"));

    assert_eq!(index.layer_count(), 2);
    assert_eq!((plan.layer, plan.z_mm), (Some(2), None));
    assert_eq!(plan.final_z_mm, None);
    assert!(plan.unknown.contains(&PlanFact::FinalZ));
    let first = index.plan_at(past(&text, "G1 X1 Y1 E1"));
    assert_eq!(first.types, vec!["Perimeter".to_owned()]);
    assert_eq!(first.minutes_left, Some(9), "a numbered line was not read");
}

/// More types than any slicer names, and more objects, are held to a bound.
#[test]
fn types_and_objects_are_held_to_a_bound() {
    let mut text = String::from("M83\n;LAYER_CHANGE\n;Z:0.2\n");
    for number in 0..70 {
        writeln!(text, ";TYPE:kind {number}\nG1 X{number} Y1 E1").expect("a String takes it");
    }
    for number in 0..1100 {
        writeln!(text, "M486 S{number}\nG1 X{number} Y2 E1\nM486 S-1").expect("a String takes it");
    }
    let index = indexed_in(&text, 4096);
    let plan = index.plan_at(i64::try_from(text.len()).expect("small"));

    assert_eq!(plan.types.len(), 64);
    assert_eq!(plan.objects.len(), 1024);
}

/// A waker that does nothing, for polling by hand.
fn idle() -> Context<'static> {
    Context::from_waker(Waker::noop())
}

/// One print's index is built by one caller: a second asking while it builds
/// waits, and is handed that build's index once it is finished — and a build
/// dropped unfinished hands the claim to whoever asks next.
#[test]
fn one_caller_builds_a_prints_index_and_the_others_wait_for_it() {
    let indexes = GcodeIndexes::default();
    let print_id = PrintId::new();

    let mut first = pin!(indexes.claim(print_id));
    let Poll::Ready(Claimed::Build(claim)) = first.as_mut().poll(&mut idle()) else {
        panic!("the first caller was not handed the build");
    };
    let mut second = pin!(indexes.claim(print_id));
    assert!(
        second.as_mut().poll(&mut idle()).is_pending(),
        "a second caller did not wait for the build under way"
    );
    drop(claim);
    let Poll::Ready(Claimed::Build(claim)) = second.as_mut().poll(&mut idle()) else {
        panic!("a dropped build did not hand the claim on");
    };
    let built = claim.finish(indexed(PLATE));

    let mut third = pin!(indexes.claim(print_id));
    let Poll::Ready(Claimed::Ready(index)) = third.as_mut().poll(&mut idle()) else {
        panic!("a finished build was not handed to the next caller");
    };
    assert_eq!(index, built);
    assert_eq!(indexes.built(print_id), Some(built));
    assert_eq!(indexes.built(PrintId::new()), None);
}

/// A nearly straight arc about a far centre covers about what its line does,
/// rather than the whole of its circle, and a negative radius goes the long
/// way round.
#[test]
fn an_arc_covers_the_part_of_its_circle_it_sweeps() {
    let text = "\
M83
M486 S0
G1 X0 Y0
G2 X10 Y0 I5 J-1000 E1
M486 S-1
M486 S1
G1 X0 Y0
G2 X1 Y1 R-1 E1 ; three quarters of the circle about (0, 1)
M486 S-1
M486 S2
G1 X0 Y0
G3 X0 Y0 I1 J0 E1 ; ending where it began, the whole circle
M486 S-1
";
    let plan = indexed(text).plan_at(i64::try_from(text.len()).expect("small"));
    let covered = plan.objects;

    assert_eq!(covered, vec![[0, 0, 10, 0], [-1, 0, 1, 2], [0, -1, 2, 1]]);
}

/// An object is named by a whole number, and `-1` alone stops one: a fraction
/// or another negative number names no object and leaves the one being laid
/// down as it was.
#[test]
fn only_a_whole_object_number_or_minus_one_moves_between_objects() {
    let text = "\
M83
M486 S2
G1 X0 Y0
G1 X10 Y0 E1
M486 S2.5
M486 S-3
G1 X10 Y10 E1
M486 S-1
G1 X50 Y50 E1
";
    let plan = indexed(text).plan_at(i64::try_from(text.len()).expect("small"));

    assert_eq!(plan.objects.len(), 1, "{:?}", plan.objects);
    assert_eq!(
        plan.objects[0],
        [0, 0, 10, 10],
        "a malformed number moved the reader off object 2, or past its stop"
    );
}

/// `M106` with no speed is full speed, and a speed past full is read as full.
#[test]
fn a_fan_with_no_speed_or_past_full_is_read_as_full() {
    let text = "M106\nG4\nM106 S900\n";
    let index = indexed(text);
    assert_eq!(
        index.fan_at(past_in(text, "G4")).map(|set| set.value),
        Some(100.0)
    );
    assert_eq!(
        index
            .fan_at(i64::try_from(text.len()).expect("small"))
            .map(|set| set.value),
        Some(100.0)
    );
}

/// A bed area is widened to whole millimetres — its least edges down, its
/// most edges up — so it still holds every move that laid the object, and a
/// name labels the file's objects without being kept.
#[test]
fn a_bed_area_widens_to_whole_millimetres_and_keeps_no_name() {
    let text = "M83\nM486 S0\nM486 Abracket.stl\nG1 X10.26 Y4.5\nG1 X21.31 Y7.24 E1\nM486 S-1\n";
    let plan = indexed(text).plan_at(i64::try_from(text.len()).expect("small"));

    assert_eq!(plan.objects, vec![[10, 4, 22, 8]]);
    assert_eq!(plan.object_count, Some(1));
    let named = indexed("M486 Abracket.stl\n").plan_at(100);
    assert_eq!(
        named.object_count,
        Some(0),
        "a name alone labels no object to count"
    );
    assert!(
        !named.unknown.contains(&PlanFact::Objects),
        "a file labelling its objects by name was read as labelling none"
    );
}

/// An arc whose radius cannot reach its end, and one ending where it began,
/// reach no further than their ends.
#[test]
fn a_radius_arc_with_no_circle_reaches_its_ends_alone() {
    let text = "\
M83
M486 S0
G1 X0 Y0
G2 X10 Y0 R1 E1 ; the radius cannot span the chord
M486 S-1
M486 S1
G1 X5 Y5
G2 X5 Y5 R2 E1 ; ending where it began
M486 S-1
";
    let plan = indexed(text).plan_at(i64::try_from(text.len()).expect("small"));
    let covered = plan.objects;

    assert_eq!(covered, vec![[0, 0, 10, 0], [5, 5, 5, 5]]);
}

/// A number written with more digits than are summed exactly is read by a
/// full parse, and a word that is no number is no coordinate.
#[test]
fn a_long_or_unusual_number_is_read_by_a_full_parse() {
    let text = "\
M83
M486 S0
G1 X0.0000000000000001 Y0
G1 X5.000000000000000001 Y1 E1
G1 X--5 Y0 E1
G1 X10.00000000000000000001 Y2 E1
M486 S-1
";
    let plan = indexed(text).plan_at(i64::try_from(text.len()).expect("small"));

    assert_eq!(
        plan.objects[0],
        [0, 0, 10, 2],
        "an unusual number was misread, or a word that is no number moved the head"
    );
}

/// The offset just past the first line carrying `needle` in `text`.
fn past_in(text: &str, needle: &str) -> i64 {
    let at = text.find(needle).expect("the file carries the line");
    let end = text[at..]
        .find('\n')
        .map_or(text.len(), |newline| at + newline + 1);
    i64::try_from(end).expect("a small offset")
}

/// A file of `layers` layers of walls, the one at `bridged` (counting from 1)
/// bridging, the fan set off before the first and the flow at `flow`.
fn bridging(layers: usize, bridged: usize, flow: u32) -> String {
    let mut text = format!("M83\nM221 S{flow}\nM107\n");
    for layer in 1..=layers {
        let _ = write!(text, ";LAYER_CHANGE\n;Z:{}\n", layer * 2);
        text.push_str(";TYPE:Perimeter\nG1 X0 Y0\nG1 X10 Y0 E1\n");
        if layer == bridged {
            text.push_str(";TYPE:Bridge infill\nG1 X10 Y10 E1\n");
        }
    }
    text
}

/// The fan off is wrong for the plan while the current layer or any of the
/// five below it — what a frame shows — bridges, and not once the bridge is
/// further down or the fan is on again; flow well under one is wrong while
/// the current layer lays walls, and a change put back to normal clears both.
#[test]
fn a_setting_the_plan_at_this_height_says_is_wrong_is_named() {
    let text = bridging(9, 2, 100);
    let index = indexed(&text);
    let end = i64::try_from(text.len()).expect("small");
    let at_layer = |layer: usize| {
        let marker = format!(";Z:{}\n", layer * 2);
        let at = text.find(&marker).expect("the layer is there") + marker.len();
        i64::try_from(at).expect("small")
    };

    assert_eq!(
        index.plan_at(at_layer(2)).at_odds,
        vec![PlanMismatch::FanOffOverBridges]
    );
    assert_eq!(
        index.plan_at(at_layer(7)).at_odds,
        vec![PlanMismatch::FanOffOverBridges],
        "a bridge five layers down, which a frame shows, was not counted"
    );
    assert!(
        index.plan_at(at_layer(8)).at_odds.is_empty(),
        "a bridge six layers down was counted"
    );
    assert!(
        index
            .plan_with(at_layer(2), None, Some(100.0))
            .at_odds
            .is_empty(),
        "a fan put back on was still named as off"
    );
    assert!(index.plan_at(end).at_odds.is_empty());

    let starved = bridging(1, 0, 30);
    let index = indexed(&starved);
    let end = i64::try_from(starved.len()).expect("small");
    assert_eq!(
        index.plan_at(end).at_odds,
        vec![PlanMismatch::FlowLowOverWalls]
    );
    assert!(
        index.plan_with(end, Some(1.0), None).at_odds.is_empty(),
        "a flow put back to one was still named as low"
    );
}

/// The height the parts gain since a position is the rise of every layer
/// after its layer that lays anything but supports; a layer of supports alone
/// adds nothing, and a position before any layer has no rise.
#[test]
fn the_rise_since_a_position_counts_the_layers_that_lay_the_part() {
    let text = bridging(4, 0, 100).replace(
        ";Z:4\n;TYPE:Perimeter",
        ";Z:4\n;TYPE:Support material\nG1 X5 Y5 E1\n;TYPE:Perimeter",
    ) + ";LAYER_CHANGE\n;Z:9.9\n;TYPE:Support material\nG1 X0 Y5 E1\n\
           ;LAYER_CHANGE\n;Z:10\n;TYPE:Perimeter\nG1 X0 Y0 E1\n\
           ;LAYER_CHANGE\n;Z:12\n;TYPE:Support material\nG1 X5 Y0 E1\n";
    let index = indexed(&text);
    let end = i64::try_from(text.len()).expect("small");
    let inside = |marker: &str| {
        i64::try_from(text.find(marker).expect("the layer is there") + marker.len()).expect("small")
    };
    assert_eq!(
        index.risen_since(0, end),
        None,
        "a position before any layer has a height"
    );
    assert_eq!(
        index.risen_since(inside(";Z:2\n"), inside(";Z:8\n")),
        Some(6.0),
        "a layer laying the part beside its supports was not counted"
    );
    assert_eq!(
        index.risen_since(inside(";Z:2\n"), inside(";Z:9.9\n")),
        Some(6.0),
        "a layer of supports alone was counted as the part rising"
    );
    assert_eq!(
        index.risen_since(inside(";Z:2\n"), end),
        Some(8.0),
        "the part's layer after an interleaved support layer rose from that \
         layer rather than from the part's own top"
    );
}

/// A command written in lower case, or with its words run together, is read
/// as the same command: a move lays its object's material, and a flow and a
/// fan are set.
#[test]
fn a_lowercase_or_compact_command_is_read_as_the_same_command() {
    let text = "\
m83
m486 s0
g1 x0 y0
g1 x10 y0 e1
G1X10Y20E1
M486S-1
m221 s95
M106S127.5
";
    let plan = indexed(text).plan_at(i64::try_from(text.len()).expect("small"));

    assert_eq!(plan.objects, vec![[0, 0, 10, 20]], "{:?}", plan.objects);
    assert_eq!(plan.flow_factor.and_then(|set| set.file), Some(0.95));
    assert_eq!(plan.fan_percent.and_then(|set| set.file), Some(50.0));
}

/// Two planned colour changes, in `PrusaSlicer` 2.9.6's syntax.
const TWO_COLOUR: &str = include_str!("fixtures/planned-changes/two-colour.gcode");

/// An `M600` whose `;COLOR_CHANGE` is not the line before it, and an `M601`.
const UNNAMED_AND_PAUSE: &str = include_str!("fixtures/planned-changes/unnamed-and-pause.gcode");

/// The offset of the first byte of the `nth` line reading exactly `line`.
fn line_offset(text: &str, line: &str, nth: usize) -> u64 {
    let mut at = 0;
    let mut seen = 0;
    for each in text.split_inclusive('\n') {
        if each.trim_end() == line {
            if seen == nth {
                return u64::try_from(at).expect("a small offset");
            }
            seen += 1;
        }
        at += each.len();
    }
    panic!("the file has no line {nth} reading {line:?}");
}

/// The offset just past the `nth` line reading exactly `line`.
fn line_end(text: &str, line: &str, nth: usize) -> i64 {
    let start = usize::try_from(line_offset(text, line, nth)).expect("a small offset");
    let end = start + text[start..].find('\n').expect("the line ends") + 1;
    i64::try_from(end).expect("a small offset")
}

/// As a signed position.
fn signed(offset: u64) -> i64 {
    i64::try_from(offset).expect("a small offset")
}

/// Each `M600` is a planned change at its own line's first byte, on the layer
/// whose `;LAYER_CHANGE` it follows and whose `;Z:` is its height, carrying the
/// colour the `;COLOR_CHANGE` line before it names.
#[test]
fn each_m600_is_indexed_with_its_offset_layer_height_and_colour() {
    let index = indexed(TWO_COLOUR);
    let changes = index.planned_changes();

    assert_eq!(
        changes,
        vec![
            PlannedChange {
                index: 0,
                kind: PlannedChangeKind::ColorChange,
                offset_bytes: line_offset(TWO_COLOUR, "M600", 0),
                layer: 3,
                z_mm: 0.6,
                color: Some("#FF0000".to_owned()),
            },
            PlannedChange {
                index: 1,
                kind: PlannedChangeKind::ColorChange,
                offset_bytes: line_offset(TWO_COLOUR, "M600", 1),
                layer: 5,
                z_mm: 1.0,
                color: Some("#0000FF".to_owned()),
            },
        ]
    );
    assert_eq!(index.planned_change(1), Some(&changes[1]));
    assert_eq!(index.planned_change(2), None);
}

/// Each stretch between changes feeds the net of its own extrusion moves — the
/// purge, perimeters, infill and primes it lays less the retractions it makes
/// — in the colour the file starts in or its change loads. Each layer lays 4
/// mm of perimeter and 5 mm of infill.
#[test]
fn each_segment_feeds_the_net_of_its_own_moves_in_its_own_colour() {
    let segments = indexed(TWO_COLOUR).planned_segments();

    assert_eq!(
        segments,
        vec![
            PlannedSegment {
                segment: 0,
                color: Some("#FFFFFF".to_owned()),
                // The 10 mm purge, two layers of 9 mm, and the third layer's
                // retraction before its change.
                filament_mm: 27.2,
            },
            PlannedSegment {
                segment: 1,
                color: Some("#FF0000".to_owned()),
                // The prime, the unretraction and two layers, less the fifth
                // layer's retraction before the second change.
                filament_mm: 18.3,
            },
            PlannedSegment {
                segment: 2,
                color: Some("#0000FF".to_owned()),
                // The prime, the unretraction and two layers, less the last
                // retraction.
                filament_mm: 17.1,
            },
        ]
    );
}

/// The colour expected changes the moment a change's line is read, the next
/// change is the one after the position, and the minutes to it are the latest
/// `M73 C` the position has read.
#[test]
fn the_plan_names_the_colour_the_next_change_and_its_minutes_by_position() {
    let index = indexed(TWO_COLOUR);
    let first = index.planned_change(0).cloned();
    let second = index.planned_change(1).cloned();
    let at = |position: i64| index.plan_at(position);

    let start = at(line_end(TWO_COLOUR, "M73 C2", 0));
    assert_eq!(start.expected_color.as_deref(), Some("#FFFFFF"));
    assert_eq!(start.next_change, first);
    assert_eq!(start.minutes_to_next_change, Some(2));
    assert_eq!(start.change_waiting, None);

    let at_first = signed(line_offset(TWO_COLOUR, "M600", 0));
    let before = at(at_first);
    assert_eq!(before.expected_color.as_deref(), Some("#FFFFFF"));
    assert_eq!(before.next_change, first);
    assert_eq!(before.minutes_to_next_change, Some(0));

    let between = at(line_end(TWO_COLOUR, "M600", 0));
    assert_eq!(between.expected_color.as_deref(), Some("#FF0000"));
    assert_eq!(between.next_change, second);
    assert_eq!(between.minutes_to_next_change, Some(0));
    let counting = at(line_end(TWO_COLOUR, "M73 C1", 1));
    assert_eq!(counting.minutes_to_next_change, Some(1));
    assert_eq!(counting.layer, Some(3));

    let after = at(line_end(TWO_COLOUR, "M600", 1));
    assert_eq!(after.expected_color.as_deref(), Some("#0000FF"));
    assert_eq!(after.next_change, None);
    assert_eq!(after.minutes_to_next_change, None);
    let end = at(signed(index.bytes()));
    assert_eq!(end.expected_color.as_deref(), Some("#0000FF"));
    assert_eq!(index.expected_color_at(-1).as_deref(), Some("#FFFFFF"));
}

/// A job stands at a change from its line's first byte to a few kilobytes
/// past it, and at no change anywhere else.
#[test]
fn a_job_waits_at_a_change_from_its_line_to_just_past_it() {
    let index = indexed(TWO_COLOUR);
    let first = line_offset(TWO_COLOUR, "M600", 0);
    let second = line_offset(TWO_COLOUR, "M600", 1);
    let waiting = |position: u64| index.change_waiting_at(position).map(|change| change.index);

    assert_eq!(waiting(first - 1), None);
    assert_eq!(waiting(first), Some(0));
    assert_eq!(waiting(first + PLANNED_CHANGE_REACH_BYTES), Some(0));
    assert!(first + PLANNED_CHANGE_REACH_BYTES + 1 < second);
    assert_eq!(waiting(first + PLANNED_CHANGE_REACH_BYTES + 1), None);
    assert_eq!(waiting(second - 1), None);
    assert_eq!(waiting(second), Some(1));
    assert_eq!(waiting(second + PLANNED_CHANGE_REACH_BYTES), Some(1));
    assert_eq!(waiting(second + PLANNED_CHANGE_REACH_BYTES + 1), None);
}

/// An `M600` whose `;COLOR_CHANGE` is not on the line just before it, and an
/// `M601`, are planned changes with no colour; a change made after its layer
/// laid material belongs to the next layer.
#[test]
fn an_m600_with_no_colour_line_and_an_m601_are_indexed_with_no_colour() {
    let index = indexed(UNNAMED_AND_PAUSE);

    assert_eq!(
        index.planned_changes(),
        vec![
            PlannedChange {
                index: 0,
                kind: PlannedChangeKind::ColorChange,
                offset_bytes: line_offset(UNNAMED_AND_PAUSE, "M600", 0),
                layer: 2,
                z_mm: 0.4,
                color: None,
            },
            PlannedChange {
                index: 1,
                kind: PlannedChangeKind::Pause,
                offset_bytes: line_offset(UNNAMED_AND_PAUSE, "M601", 0),
                layer: 4,
                z_mm: 0.8,
                color: None,
            },
        ]
    );
    let segments = index.planned_segments();
    assert_eq!(segments.len(), 3);
    assert!(segments.iter().all(|segment| segment.color.is_none()));
    assert_eq!(index.plan_at(signed(index.bytes())).expected_color, None);
}

/// A file planning no change plans no segment, and its plan carries none of
/// the four fields about changes.
#[test]
fn a_file_planning_no_change_carries_nothing_about_changes() {
    let index = indexed(PLATE);
    let plan = index.plan_at(signed(index.bytes()));

    assert!(index.planned_changes().is_empty());
    assert!(index.planned_segments().is_empty());
    let fields = printobserver_types::serde_json::to_value(&plan).expect("the plan serializes");
    for field in [
        "expected_color",
        "next_change",
        "minutes_to_next_change",
        "change_waiting",
    ] {
        assert!(fields.get(field).is_none(), "{field} is in {fields}");
    }
}