write_till_receipt.rs

Le fichier Rust de l’exemple « Un ticket de caisse sur un rouleau de papier ». Le ticket qu’une caisse imprime sur un rouleau de 80 mm de large : six articles, la TVA ventilée par taux, le rendu de monnaie calculé sur le billet donné, et le code-barres que le magasin lit quand le ticket revient.

Rust 1043 lignes

À quoi sert cet exemple

Une caisse de comptoir imprime sur un rouleau de 80 mm de large, et un rouleau n’a pas de bord du bas : le papier est coupé là où le panier s’arrête. La page fait donc la longueur de ce qui a été acheté, et aucun chiffre n’y est écrit d’avance. Une ligne vaut sa quantité fois son prix unitaire, la TVA de chaque taux est prise sur le TTC qui la contient, et la monnaie rendue est ce qui reste du billet tendu. Passez un article de plus et le rouleau grandit d’une ligne, les totaux toujours en dessous.

Ce que montre cet exemple

   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
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
//! Creates the receipt a shop's till prints on a roll: the shop at the head,
//! the basket line by line, the tax gathered by rate, what was handed over and
//! what was handed back, and the ticket's own barcode at the foot.
//!
//! The roll is 80 mm across, which is the paper a counter printer takes, and
//! the page is as long as this basket makes it. Every figure on it is worked
//! out rather than written down: a line comes to its quantity times its unit
//! price, the tax at each rate is taken out of the gross that carries it, the
//! total is the sum of the lines, and the change is what is left of the note
//! handed over.
//!
//! The barcode is what the shop scans when the ticket comes back — a return, an
//! exchange, a warranty claim. `Code128::automatic` reads the number and picks
//! the code set for it: a ticket number of nothing but digits goes into code
//! set C, two digits to a symbol, and takes 112 modules where code set B would
//! spell it out over 189.
//!
//! Whether that barcode scans is not for the page to say, and not for an eye: a
//! scanner says. `scripts/check_barcode.sh` points a decoder at the rendered
//! page and reads the number back.
//!
//! Every word the ticket prints is held in `Words`, once per language, and
//! `HQF_PDF_LANG` picks which one it is printed in. What is not language stays
//! out of it: the shop, the date, the till, the amounts, the rates and the
//! ticket number read the same whichever set of words is drawn.
//!
//! Usage: `cargo run --example write_till_receipt -- tmp/receipt.pdf
//! [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_till_receipt --
//! tmp/ticket.pdf`

use std::env;
use std::fs;
use std::path::{Path, PathBuf};

use hqf_pdf::content::Content;
use hqf_pdf::cos::Name;
use hqf_pdf::{Code128, Dash, Document, Font, FontHandle, Page, Rgb};

#[path = "shared/out.rs"]
mod out;

#[path = "shared/licence.rs"]
mod licence;

#[path = "shared/language.rs"]
mod language;

#[path = "shared/failure.rs"]
mod failure;

use language::Language;

/// The font the example draws with when none is given on the command line.
fn default_font() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fonts")
        .join("DejaVuSans.ttf")
}

/// The roll, in points: 80 mm across, cut long enough for this basket.
const PAGE_WIDTH: f64 = 226.772;
const PAGE_HEIGHT: f64 = 486.0;

/// The margins the printer keeps clear, and the middle a centred line sits on.
const LEFT: f64 = 14.0;
const RIGHT: f64 = PAGE_WIDTH - LEFT;
const CENTRE: f64 = PAGE_WIDTH / 2.0;

/// Where the first baseline sits, in points down from the top of the roll.
const HEAD_TOP: f64 = 24.0;

/// The steps the ticket comes down the roll by: between two lines of a block,
/// between two blocks, from one article to the next, and from an article to the
/// quantity line under it.
const LINE: f64 = 10.0;
const BLOCK: f64 = 13.0;
const ITEM: f64 = 20.0;
const SUB: f64 = 8.0;

/// The sizes the ticket is set at: the shop's name, the small print, the body
/// of the basket, the line the ticket ends on, and the total.
const SHOP_SIZE: f64 = 13.0;
const SMALL: f64 = 6.5;
const BODY: f64 = 8.0;
const THANKS_SIZE: f64 = 7.5;
const TOTAL_SIZE: f64 = 11.0;

/// The near-black a till prints in, and the grey the labels and the small print
/// are set in.
const INK: Rgb = Rgb {
    r: 0.1,
    g: 0.1,
    b: 0.12,
};
const MUTED: Rgb = Rgb {
    r: 0.42,
    g: 0.42,
    b: 0.45,
};

/// The shop: its name, where it stands, what to ring, and the number it is
/// registered for tax under. It is the same shop whichever language the ticket
/// is printed in.
const SHOP: &str = "Comptoir Vaugelade";
const ADDRESS: &str = "18 rue des Trois-Fontaines";
const TOWN: &str = "13290 Les Milles";
const PHONE: &str = "+33 4 42 00 71 30";
const REGISTRATION: &str = "FR 41 802 337 190";

/// When the basket was rung up, at which till, and by whom.
const DATE: &str = "2026-08-31";
const TIME: &str = "18:42";
const TILL: &str = "04";
const CASHIER: &str = "Naïma";

/// The ticket's own number: the till, the day, and the basket's place in the
/// day. Nothing but digits, which is what sends it into code set C.
const TICKET: &str = "04202608310731";

/// The currency every amount on the ticket is in.
const CURRENCY: &str = "EUR";

/// What was handed over, in cents.
const TENDERED: i64 = 6000;

/// The width of the narrowest bar, in points. Everything else is a whole number
/// of these.
const MODULE: f64 = 1.0;

/// How tall the bars are drawn, in points.
const BAR_HEIGHT: f64 = 34.0;

/// The right edge of two of the three columns of figures in the tax table. The
/// third ends at the right margin, and the rate is set from the left one.
const NET_RIGHT: f64 = 120.0;
const TAX_RIGHT: f64 = 166.0;

/// A rate of tax: the reduced rate a grocer charges on food, and the standard
/// rate on everything else.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Rate {
    /// The reduced rate.
    Reduced,
    /// The standard rate.
    Standard,
}

impl Rate {
    /// The rate itself, in tenths of a percent.
    const fn tenths(self) -> i64 {
        match self {
            Self::Reduced => 55,
            Self::Standard => 200,
        }
    }

    /// The letter the ticket marks a line with, and the tax table names.
    const fn letter(self) -> &'static str {
        match self {
            Self::Reduced => "A",
            Self::Standard => "B",
        }
    }

    /// The rate as the ticket writes it: a point before the tenth, and a
    /// no-break space before the sign.
    fn shown(self) -> String {
        let tenths = self.tenths();
        format!("{}.{}\u{00A0}%", tenths / 10, tenths % 10)
    }
}

/// Both rates, in the order the tax table sets them out.
const RATES: [Rate; 2] = [Rate::Reduced, Rate::Standard];

/// One line of the basket: how many were scanned, what one of them costs in
/// cents, and the rate of tax it carries. What the article is called is a word,
/// and is held in `Words` at the place the line has here.
#[derive(Debug)]
struct Article {
    /// How many of it were scanned.
    quantity: i64,
    /// What one of them costs, in cents.
    unit: i64,
    /// The rate of tax it carries.
    rate: Rate,
}

/// The basket, in the order it was scanned.
const BASKET: [Article; 6] = [
    Article {
        quantity: 1,
        unit: 120,
        rate: Rate::Reduced,
    },
    Article {
        quantity: 2,
        unit: 890,
        rate: Rate::Reduced,
    },
    Article {
        quantity: 3,
        unit: 105,
        rate: Rate::Reduced,
    },
    Article {
        quantity: 1,
        unit: 1240,
        rate: Rate::Reduced,
    },
    Article {
        quantity: 1,
        unit: 675,
        rate: Rate::Standard,
    },
    Article {
        quantity: 1,
        unit: 995,
        rate: Rate::Standard,
    },
];

/// Every word the ticket prints, in one language.
///
/// What is not language stays out of it: the shop, its address, the date, the
/// till, the cashier, the amounts, the rates and the ticket number are drawn
/// from constants of their own and read the same in every language.
#[derive(Debug)]
struct Words {
    /// What the file says it is, and the line under the shop's name.
    title: &'static str,
    tagline: &'static str,
    /// What the shop's tax registration stands under.
    registration: &'static str,
    /// The five marks at the head of the ticket.
    date: &'static str,
    time: &'static str,
    till: &'static str,
    served: &'static str,
    receipt: &'static str,
    /// The two column heads over the basket.
    item: &'static str,
    amount: &'static str,
    /// The six articles, in the order the basket holds them.
    articles: [&'static str; 6],
    /// The line that adds the basket up before tax, and the four column heads
    /// of the tax table.
    net_total: &'static str,
    rate: &'static str,
    net: &'static str,
    tax: &'static str,
    gross: &'static str,
    /// What the ticket comes to, what was handed over, what was handed back,
    /// and how many articles were sold.
    total: &'static str,
    cash: &'static str,
    change: &'static str,
    count: &'static str,
    /// The two lines under the barcode.
    keep: &'static str,
    thanks: &'static str,
}

impl Words {
    /// The words the ticket is printed in, in `language`.
    fn of(language: Language) -> &'static Self {
        language::pick(&WORDS, language)
    }
}

/// The ticket in English.
const ENGLISH: Words = Words {
    title: "Till receipt",
    tagline: "Grocer and general store",
    registration: "VAT no.",
    date: "DATE",
    time: "TIME",
    till: "TILL",
    served: "SERVED BY",
    receipt: "RECEIPT",
    item: "ITEM",
    amount: "AMOUNT",
    articles: [
        "Sourdough loaf",
        "Coffee beans 1 kg",
        "Whole milk 1 L",
        "Olive oil 75 cl",
        "Washing powder 2 kg",
        "Batteries AA, 8",
    ],
    net_total: "TOTAL BEFORE TAX",
    rate: "RATE",
    net: "NET",
    tax: "TAX",
    gross: "GROSS",
    total: "TOTAL",
    cash: "CASH",
    change: "CHANGE",
    count: "ARTICLES SOLD",
    keep: "Keep this ticket for any return or exchange.",
    thanks: "Thank you for your visit — see you soon",
};

/// The ticket in French.
const FRENCH: Words = Words {
    title: "Ticket de caisse",
    tagline: "Épicerie et bazar",
    registration: "N° TVA",
    date: "DATE",
    time: "HEURE",
    till: "CAISSE",
    served: "SERVI PAR",
    receipt: "TICKET",
    item: "ARTICLE",
    amount: "MONTANT",
    articles: [
        "Pain au levain",
        "Café en grains 1 kg",
        "Lait entier 1 l",
        "Huile d’olive 75 cl",
        "Lessive en poudre 2 kg",
        "Piles AA ×8",
    ],
    net_total: "TOTAL HORS TAXES",
    rate: "TAUX",
    net: "HT",
    tax: "TVA",
    gross: "TTC",
    total: "TOTAL",
    cash: "ESPÈCES",
    change: "RENDU",
    count: "ARTICLES VENDUS",
    keep: "Conservez ce ticket pour tout retour ou échange.",
    thanks: "Merci de votre visite — à bientôt",
};

/// The ticket in Dutch.
const DUTCH: Words = Words {
    title: "Kassabon",
    tagline: "Kruidenier en huishoudzaak",
    registration: "Btw-nr.",
    date: "DATUM",
    time: "TIJD",
    till: "KASSA",
    served: "GEHOLPEN DOOR",
    receipt: "BON",
    item: "ARTIKEL",
    amount: "BEDRAG",
    articles: [
        "Zuurdesembrood",
        "Koffiebonen 1 kg",
        "Volle melk 1 l",
        "Olijfolie 75 cl",
        "Waspoeder 2 kg",
        "Batterijen AA, 8",
    ],
    net_total: "TOTAAL EXCL. BTW",
    rate: "TARIEF",
    net: "NETTO",
    tax: "BTW",
    gross: "BRUTO",
    total: "TOTAAL",
    cash: "CONTANT",
    change: "WISSELGELD",
    count: "VERKOCHTE ARTIKELEN",
    keep: "Bewaar deze bon voor ruilen of retourneren.",
    thanks: "Bedankt voor uw bezoek — tot ziens",
};

/// The ticket in Portuguese.
const PORTUGUESE: Words = Words {
    title: "Talão de caixa",
    tagline: "Mercearia e drogaria",
    registration: "NIF",
    date: "DATA",
    time: "HORA",
    till: "CAIXA",
    served: "ATENDIDO POR",
    receipt: "TALÃO",
    item: "ARTIGO",
    amount: "MONTANTE",
    articles: [
        "Pão de massa-mãe",
        "Café em grão 1 kg",
        "Leite gordo 1 l",
        "Azeite 75 cl",
        "Detergente em pó 2 kg",
        "Pilhas AA, 8",
    ],
    net_total: "TOTAL SEM IMPOSTOS",
    rate: "TAXA",
    net: "LÍQUIDO",
    tax: "IMPOSTO",
    gross: "BRUTO",
    total: "TOTAL",
    cash: "NUMERÁRIO",
    change: "TROCO",
    count: "ARTIGOS VENDIDOS",
    keep: "Guarde este talão para qualquer devolução ou troca.",
    thanks: "Obrigado pela visita — até breve",
};

/// The ticket in Italian.
const ITALIAN: Words = Words {
    title: "Scontrino",
    tagline: "Alimentari e drogheria",
    registration: "P. IVA",
    date: "DATA",
    time: "ORA",
    till: "CASSA",
    served: "OPERATORE",
    receipt: "SCONTRINO",
    item: "ARTICOLO",
    amount: "IMPORTO",
    articles: [
        "Pagnotta a lievito madre",
        "Caffè in grani 1 kg",
        "Latte intero 1 l",
        "Olio d’oliva 75 cl",
        "Detersivo 2 kg",
        "Pile AA, 8",
    ],
    net_total: "TOTALE IMPONIBILE",
    rate: "ALIQUOTA",
    net: "NETTO",
    tax: "IMPOSTA",
    gross: "LORDO",
    total: "TOTALE",
    cash: "CONTANTI",
    change: "RESTO",
    count: "ARTICOLI VENDUTI",
    keep: "Conservare lo scontrino per resi o cambi.",
    thanks: "Grazie della visita — a presto",
};

/// The ticket in Spanish.
const SPANISH: Words = Words {
    title: "Tique de caja",
    tagline: "Ultramarinos y droguería",
    registration: "NIF IVA",
    date: "DATE",
    time: "HORA",
    till: "CAJA",
    served: "ATENDIDO POR",
    receipt: "TIQUE",
    item: "ARTÍCULO",
    amount: "IMPORTE",
    articles: [
        "Pan de masa madre",
        "Café en grano 1 kg",
        "Leche entera 1 L",
        "Aceite de oliva 75 cl",
        "Detergente 2 kg",
        "Pilas AA, 8",
    ],
    net_total: "TOTAL SIN IMPUESTOS",
    rate: "TIPO",
    net: "BASE",
    tax: "IMPUESTO",
    gross: "TOTAL",
    total: "TOTAL",
    cash: "EFECTIVO",
    change: "CAMBIO",
    count: "ARTÍCULOS VENDIDOS",
    keep: "Conserve este tique para cualquier devolución o cambio.",
    thanks: "Gracias por su visita — hasta pronto",
};

/// The ticket in German.
const GERMAN: Words = Words {
    title: "Kassenbon",
    tagline: "Lebensmittel und Gemischtwaren",
    registration: "USt-IdNr.",
    date: "DATUM",
    time: "UHRZEIT",
    till: "KASSE",
    served: "BEDIENT VON",
    receipt: "BELEG",
    item: "ARTIKEL",
    amount: "BETRAG",
    articles: [
        "Sauerteigbrot",
        "Kaffeebohnen 1 kg",
        "Vollmilch 1 l",
        "Olivenöl 0,75 l",
        "Waschpulver 2 kg",
        "Batterien AA, 8",
    ],
    net_total: "SUMME VOR STEUER",
    rate: "SATZ",
    net: "NETTO",
    tax: "STEUER",
    gross: "BRUTTO",
    total: "SUMME",
    cash: "BAR",
    change: "RÜCKGELD",
    count: "VERKAUFTE ARTIKEL",
    keep: "Bon für Rückgabe oder Umtausch aufbewahren.",
    thanks: "Danke für Ihren Besuch — bis bald",
};

/// Every language the example is written in. A language is added by writing its
/// own set of words and naming it here.
static WORDS: [(Language, &Words); 7] = [
    (Language::English, &ENGLISH),
    (Language::French, &FRENCH),
    (Language::German, &GERMAN),
    (Language::Spanish, &SPANISH),
    (Language::Italian, &ITALIAN),
    (Language::Portuguese, &PORTUGUESE),
    (Language::Dutch, &DUTCH),
];

/// An amount of cents, its thousands parted by a no-break space and its
/// decimals by a point, which is how every language this example is written in
/// writes one.
///
/// The currency is named once at the head of the column of amounts and once on
/// the line of the total; the figures themselves are bare, as a till prints
/// them.
fn money(cents: i64) -> String {
    let (whole, fraction) = (cents / 100, cents % 100);
    let digits = whole.to_string();
    let mut out = String::with_capacity(digits.len() + 8);
    for (index, digit) in digits.chars().enumerate() {
        if index > 0 && (digits.len() - index) % 3 == 0 {
            out.push('\u{00A0}');
        }
        out.push(digit);
    }
    format!("{out}.{fraction:02}")
}

/// What one line of the basket comes to, in cents.
const fn line_total(article: &Article) -> i64 {
    article.quantity * article.unit
}

/// What the whole basket comes to, in cents.
fn total() -> i64 {
    BASKET.iter().map(line_total).sum()
}

/// How many articles were sold, all lines together.
fn sold() -> i64 {
    BASKET.iter().map(|article| article.quantity).sum()
}

/// What the lines carrying `rate` come to, in cents, tax included.
fn gross_at(rate: Rate) -> i64 {
    BASKET
        .iter()
        .filter(|article| article.rate == rate)
        .map(line_total)
        .sum()
}

/// What `gross` holds of tax at `rate`, in cents, rounded to the nearest cent.
///
/// The prices a shop shows already carry their tax, so the tax is taken out of
/// the gross rather than added to a net: at a rate of `t` tenths of a percent,
/// it is `gross × t / (1000 + t)`.
const fn tax_of(gross: i64, rate: Rate) -> i64 {
    let tenths = rate.tenths();
    let denominator = 1000 + tenths;
    (gross * tenths * 2 + denominator) / (denominator * 2)
}

/// The bars the ticket carries.
///
/// The number is nothing but digits, so `automatic` takes code set C for it and
/// draws it in a little over half the bars code set B would spell it out in.
///
/// # Errors
///
/// If the ticket number holds a character Code 128 cannot carry, or none at
/// all.
fn ticket_code() -> Result<Code128, hqf_pdf::Error> {
    Code128::automatic(TICKET)
}

/// Draws a line of text, left-aligned, in a colour of its own.
fn text(content: &mut Content, font: &FontHandle, size: f64, x: f64, y: f64, color: Rgb, s: &str) {
    let _ = content.set_fill(color);
    content.begin_text();
    let _ = content.set_font(font, size);
    let _ = content.text_origin(x, y);
    content.show_glyphs(&font.glyphs(s));
    content.end_text();
}

/// Draws a line of text whose right edge sits at `right`.
fn text_right(
    content: &mut Content,
    font: &FontHandle,
    size: f64,
    right: f64,
    y: f64,
    color: Rgb,
    s: &str,
) {
    text(
        content,
        font,
        size,
        right - font.measure(s, size),
        y,
        color,
        s,
    );
}

/// Draws a line of text set across the middle of the roll.
fn text_centre(content: &mut Content, font: &FontHandle, size: f64, y: f64, color: Rgb, s: &str) {
    text(
        content,
        font,
        size,
        CENTRE - font.measure(s, size) / 2.0,
        y,
        color,
        s,
    );
}

/// Draws a row with something at the left margin and something at the right.
fn row(
    content: &mut Content,
    font: &FontHandle,
    size: f64,
    y: f64,
    color: Rgb,
    left: &str,
    right: &str,
) {
    text(content, font, size, LEFT, y, color, left);
    text_right(content, font, size, RIGHT, y, color, right);
}

/// Draws the row of dashes a till prints between the parts of a ticket.
fn dashes(content: &mut Content, y: f64) -> Result<(), hqf_pdf::Error> {
    content.set_stroke(MUTED)?;
    content.set_line_width(0.5)?;
    content.set_dash(&Dash::on_off(2.0, 2.0)?)?;
    content.move_to(LEFT, y)?;
    content.line_to(RIGHT, y)?;
    content.stroke();
    content.set_solid();
    Ok(())
}

/// Draws the shop at the head of the roll, and hands back the baseline it ends
/// on.
fn head(content: &mut Content, font: &FontHandle, words: &Words, top: f64) -> f64 {
    let mut y = top;
    text_centre(content, font, SHOP_SIZE, y, INK, SHOP);
    y -= 12.0;
    text_centre(content, font, SMALL, y, MUTED, words.tagline);
    y -= LINE;
    text_centre(content, font, SMALL, y, INK, ADDRESS);
    y -= SUB;
    text_centre(content, font, SMALL, y, INK, TOWN);
    y -= SUB;
    text_centre(content, font, SMALL, y, INK, PHONE);
    y -= SUB;
    let registered = format!("{} {REGISTRATION}", words.registration);
    text_centre(content, font, SMALL, y, MUTED, &registered);
    y
}

/// Draws when the basket was rung up, at which till, by whom and under which
/// number, and hands back the baseline it ends on.
fn marks(content: &mut Content, font: &FontHandle, words: &Words, top: f64) -> f64 {
    let mut y = top;
    let day = format!("{} {DATE}", words.date);
    let hour = format!("{} {TIME}", words.time);
    row(content, font, SMALL, y, INK, &day, &hour);
    y -= LINE;
    let till = format!("{} {TILL}", words.till);
    let served = format!("{} {CASHIER}", words.served);
    row(content, font, SMALL, y, INK, &till, &served);
    y -= LINE;
    row(content, font, SMALL, y, INK, words.receipt, TICKET);
    y
}

/// Draws the basket, one article to two lines: what it is against what it came
/// to, and under that how many at what price and which rate it carries. Hands
/// back the baseline it ends on.
fn basket(content: &mut Content, font: &FontHandle, words: &Words, top: f64) -> f64 {
    let mut y = top;
    for (article, name) in BASKET.iter().zip(words.articles) {
        let amount = money(line_total(article));
        row(content, font, BODY, y, INK, name, &amount);

        let counted = format!("{} × {}", article.quantity, money(article.unit));
        text(content, font, SMALL, LEFT + SUB, y - SUB, MUTED, &counted);
        let letter = article.rate.letter();
        text_right(content, font, SMALL, RIGHT, y - SUB, MUTED, letter);
        y -= ITEM;
    }
    y + ITEM - SUB
}

/// Draws what the basket comes to before tax and the tax gathered by rate, and
/// hands back the baseline it ends on.
fn taxes(content: &mut Content, font: &FontHandle, words: &Words, top: f64) -> f64 {
    let mut y = top;
    let before_tax: i64 = RATES
        .iter()
        .map(|&rate| {
            let gross = gross_at(rate);
            gross - tax_of(gross, rate)
        })
        .sum();
    let amount = money(before_tax);
    row(content, font, BODY, y, INK, words.net_total, &amount);

    y -= BLOCK;
    text(content, font, SMALL, LEFT, y, MUTED, words.rate);
    text_right(content, font, SMALL, NET_RIGHT, y, MUTED, words.net);
    text_right(content, font, SMALL, TAX_RIGHT, y, MUTED, words.tax);
    text_right(content, font, SMALL, RIGHT, y, MUTED, words.gross);

    for rate in RATES {
        y -= LINE;
        let gross = gross_at(rate);
        let tax = tax_of(gross, rate);
        let named = format!("{} {}", rate.letter(), rate.shown());
        text(content, font, SMALL, LEFT, y, INK, &named);
        text_right(content, font, SMALL, NET_RIGHT, y, INK, &money(gross - tax));
        text_right(content, font, SMALL, TAX_RIGHT, y, INK, &money(tax));
        text_right(content, font, SMALL, RIGHT, y, INK, &money(gross));
    }
    y
}

/// Draws what the ticket came to, what was handed over and what was handed
/// back, and hands back the baseline it ends on.
fn settlement(content: &mut Content, font: &FontHandle, words: &Words, top: f64) -> f64 {
    let mut y = top;
    let due = total();
    let paid = format!("{}\u{00A0}{CURRENCY}", money(due));
    row(content, font, TOTAL_SIZE, y, INK, words.total, &paid);

    y -= BLOCK;
    row(content, font, BODY, y, INK, words.cash, &money(TENDERED));
    y -= LINE;
    let change = money(TENDERED - due);
    row(content, font, BODY, y, INK, words.change, &change);
    y -= LINE;
    row(
        content,
        font,
        SMALL,
        y,
        MUTED,
        words.count,
        &sold().to_string(),
    );
    y
}

/// Draws the ticket's own barcode and the two lines under it, and hands back
/// the baseline it ends on.
fn foot(
    content: &mut Content,
    font: &FontHandle,
    words: &Words,
    top: f64,
) -> Result<f64, Box<dyn std::error::Error>> {
    let code = ticket_code()?;
    let width = f64::from(u32::try_from(code.module_count())?) * MODULE;

    // The quiet zone is the caller's: nothing else is drawn beside the bars,
    // and the roll leaves far more than the ten modules a scanner needs.
    let mut y = top - BAR_HEIGHT;
    content.set_fill(Rgb::gray(0.0))?;
    content.draw_barcode(&code, (PAGE_WIDTH - width) / 2.0, y, width, BAR_HEIGHT)?;

    y -= LINE;
    text_centre(content, font, SMALL, y, INK, TICKET);
    y -= LINE;
    text_centre(content, font, SMALL, y, MUTED, words.keep);
    y -= 12.0;
    text_centre(content, font, THANKS_SIZE, y, INK, words.thanks);
    Ok(y)
}

/// Draws the whole ticket, and hands back the baseline it ends on.
fn ticket(
    content: &mut Content,
    font: &FontHandle,
    words: &Words,
) -> Result<f64, Box<dyn std::error::Error>> {
    let mut y = head(content, font, words, PAGE_HEIGHT - HEAD_TOP);

    y -= BLOCK;
    dashes(content, y)?;
    y = marks(content, font, words, y - BLOCK);

    y -= BLOCK;
    dashes(content, y)?;
    y -= BLOCK;
    let heading = format!("{}\u{00A0}{CURRENCY}", words.amount);
    row(content, font, SMALL, y, MUTED, words.item, &heading);
    y = basket(content, font, words, y - 12.0);

    y -= BLOCK;
    dashes(content, y)?;
    y = taxes(content, font, words, y - BLOCK);

    y -= BLOCK;
    dashes(content, y)?;
    y = settlement(content, font, words, y - 16.0);

    foot(content, font, words, y - 18.0)
}

fn main() -> std::process::ExitCode {
    failure::reported(run())
}

fn run() -> Result<(), Box<dyn std::error::Error>> {
    let language = Language::from_environment()?;
    let words = Words::of(language);

    let mut args = env::args().skip(1);
    // A named file is written as named; the default one carries the language,
    // so the two languages do not overwrite each other in `tmp/`.
    let path = args
        .next()
        .unwrap_or_else(|| language.file_name(&out::default_path("till_receipt")));
    let font_path = args.next().map_or_else(default_font, PathBuf::from);

    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    doc.set_info(Name::new("Title"), &format!("{} {TICKET}", words.title));

    let font = doc.add_font(Font::parse(fs::read(&font_path)?)?);

    let mut content = Content::new();
    ticket(&mut content, &font, words)?;

    let mut page = Page::new(PAGE_WIDTH, PAGE_HEIGHT);
    page.content = content.into_bytes();
    doc.add_page(page)?;

    let bytes = doc.to_bytes()?;
    if let Some(parent) = Path::new(&path).parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(&path, &bytes)?;

    println!(
        "wrote {path}: {} bytes, ticket {TICKET}, {} articles, {}\u{00A0}{CURRENCY}",
        bytes.len(),
        sold(),
        money(total())
    );
    Ok(())
}

#[cfg(test)]
mod tests {
    use hqf_pdf::{Code128, Content, Document, Font};

    use super::{
        BASKET, BODY, LEFT, RATES, RIGHT, Rate, SMALL, TICKET, WORDS, default_font, gross_at,
        language, line_total, money, tax_of, ticket, ticket_code, total,
    };

    /// The lines two languages are allowed to write the same way, each with
    /// what makes the two the same word.
    const SPARED: [&str; 9] = [
        // A day is headed by the same word in French as in English.
        r#"date: "DATE""#,
        // So is the line a ticket ends on.
        r#"total: "TOTAL""#,
        // Written the same way in Italian.
        r#"net: "NETTO""#,
        // Written the same way in Portuguese.
        r#"date: "DATA""#,
        r#"served: "ATENDIDO POR""#,
        r#"time: "HORA""#,
        // Written the same way in Dutch.
        r#"date: "DATUM""#,
        r#"gross: "BRUTO""#,
        r#"item: "ARTIKEL""#,
    ];

    #[test]
    fn every_language_prints_the_ticket_in_its_own_words() {
        let untranslated = language::untranslated_lines(&WORDS, &SPARED);

        assert!(
            untranslated.is_empty(),
            "the ticket says these in more than one language: {untranslated:?}"
        );
    }

    /// An amount over a thousand holds its thousands apart, and every amount
    /// puts a point before its cents.
    #[test]
    fn an_amount_is_written_with_a_space_between_its_thousands() {
        assert_eq!(money(123_456_789), "1\u{00A0}234\u{00A0}567.89");
        assert_eq!(money(5125), "51.25");
        assert_eq!(money(105), "1.05");
    }

    /// The tax table has to add up to the ticket: every line of the basket is
    /// gathered under one of the two rates, and every net, taxed again the
    /// other way round, comes back to the gross it was taken out of.
    #[test]
    fn the_tax_table_adds_up_to_what_the_ticket_comes_to() {
        let mut gross_sum = 0;

        for rate in RATES {
            let gross = gross_at(rate);
            assert!(gross > 0, "no line carries {}", rate.letter());

            let net = gross - tax_of(gross, rate);
            let grossed_again = (net * (1000 + rate.tenths()) + 500) / 1000;
            assert_eq!(
                grossed_again,
                gross,
                "{net} taxed at {} comes back to {grossed_again}, not to {gross}",
                rate.shown()
            );
            gross_sum += gross;
        }

        assert_eq!(
            gross_sum,
            total(),
            "the rates gather {gross_sum} of a basket that came to {}",
            total()
        );

        // A tax that does not fall on a whole cent goes to the nearer one
        // rather than being cut short: a fifth of 10.00 is 1.666…, and 12.40 at
        // the reduced rate holds 0.646…
        assert_eq!(tax_of(1000, Rate::Standard), 167);
        assert_eq!(tax_of(1240, Rate::Reduced), 65);
    }

    /// The ticket number is nothing but digits, so the bars the ticket carries
    /// are the ones code set C draws, over fewer modules than code set B would
    /// spell the number out in. Both counts are held to the module: code set C
    /// pairs the fourteen digits into seven symbols where code set B spells out
    /// fourteen, each set adding a start symbol and a check symbol, every
    /// symbol covering eleven modules and the stop pattern thirteen.
    #[test]
    fn the_ticket_number_is_drawn_in_the_narrower_code_set() {
        let chosen = ticket_code().expect("the ticket number is digits");
        let spelled = Code128::new(TICKET).expect("the ticket number is printable");

        assert_eq!(
            chosen.module_count(),
            112,
            "code set C draws {TICKET} over {} modules",
            chosen.module_count()
        );
        assert_eq!(
            spelled.module_count(),
            189,
            "code set B draws {TICKET} over {} modules",
            spelled.module_count()
        );
    }

    /// Nothing on the ticket is broken to a width: a line wider than the roll
    /// runs off the paper.
    #[test]
    fn every_language_prints_lines_that_fit_the_roll() {
        let mut doc = Document::new();
        let font = doc.add_font(
            Font::parse(std::fs::read(default_font()).expect("the committed font is there"))
                .expect("the committed font parses"),
        );
        let room = RIGHT - LEFT;

        for (named, words) in WORDS {
            for line in [words.keep, words.thanks, words.tagline, words.net_total] {
                let measured = font.measure(line, SMALL);
                assert!(
                    measured <= room,
                    "the {} ticket sets {line:?} over {measured:.1} points, and it \
                     has {room:.1}",
                    named.code()
                );
            }
        }
    }

    /// An article's name and what it came to share one line, and neither may
    /// run into the other.
    #[test]
    fn every_article_leaves_room_for_what_it_came_to() {
        let mut doc = Document::new();
        let font = doc.add_font(
            Font::parse(std::fs::read(default_font()).expect("the committed font is there"))
                .expect("the committed font parses"),
        );
        let room = RIGHT - LEFT;

        for (named, words) in WORDS {
            for (article, name) in BASKET.iter().zip(words.articles) {
                let amount = money(line_total(article));
                let measured = font.measure(name, BODY) + font.measure(&amount, BODY);
                assert!(
                    measured + SMALL <= room,
                    "the {} ticket sets {name:?} and {amount:?} over {measured:.1} \
                     points, and the line has {room:.1}",
                    named.code()
                );
            }
        }
    }

    /// The roll is cut to a length, and the last line has to land on it.
    #[test]
    fn the_ticket_ends_on_the_paper() {
        let mut doc = Document::new();
        let font = doc.add_font(
            Font::parse(std::fs::read(default_font()).expect("the committed font is there"))
                .expect("the committed font parses"),
        );

        for (named, words) in WORDS {
            let mut content = Content::new();
            let last = ticket(&mut content, &font, words).expect("the ticket draws");
            assert!(
                last >= SMALL,
                "the {} ticket ends on a line at {last:.1} points, and the roll \
                 stops at 0",
                named.code()
            );
        }
    }
}