Content shown and hidden by layer

One floor plan on four layers a reader shows and hides: the furniture and the dimensions shown, the notes hidden until asked for, and a draft mark that is looked at but never printed.

Python write_layers.py 296 lines
  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
"""Draws one plan on four layers a reader can show and hide.

The Python twin of the `write_layers` example in Rust. The walls are the page's own
ink and are always there. Everything else belongs to a layer: the furniture and the
dimensions start shown, the notes start hidden, and the draft mark is looked at but
never printed. Open the file and the reader's layers panel lists all four; print it
and the draft mark is gone without anyone touching that panel.

The page is held in `Words`, once per language, and `HQF_PDF_LANG` picks which set is
drawn. A layer's name is language too: the reader's panel shows it, and the legend
under the plan names the same field, so the panel and the page can never disagree.

Usage: python examples/write_layers.py [out.pdf] [font.ttf]
       HQF_PDF_LANG=fr python examples/write_layers.py
"""

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path
from typing import Callable

import _language
import _licence
import _out

import hqf_pdf

# The plan's outer wall: where it sits on the page and how big it is.
PLAN = (80.0, 380.0, 435.0, 320.0)

# The two distances the plan is measured at. Neither is language.
ALONG = "7.25 m"
ACROSS = "5.00 m"


@dataclass(frozen=True)
class Words:
    """Every word the page draws, in one language.

    A layer's name is here: the reader's panel shows it, and so does the legend. The
    two distances are not: a metre is a metre.
    """

    # The line at the head of the page.
    title: str
    # What stands under it, saying what a layer is.
    intro: str
    # What each layer is called, in the order they are added. The reader's panel lists
    # these, and the legend names them again.
    layers: tuple[str, str, str, str]
    # What the legend says each layer holds and how it starts.
    holdings: tuple[str, str, str, str]
    # The notes the hidden layer holds, in the order they are placed.
    notes: tuple[str, str, str]
    # The word the draft mark is stamped in.
    draft: str
    # The two lines under the legend, saying that the draft mark takes itself off the
    # printed page.
    printing: tuple[str, str]


# The page in English.
ENGLISH = Words(
    title="One plan, four layers",
    intro=(
        "The walls are always there. Everything else is a layer the reader can show "
        "and hide."
    ),
    layers=("Furniture", "Dimensions", "Notes", "Draft"),
    holdings=(
        "shown; turn it off and the rooms stand empty",
        "shown; the distances around the plan",
        "hidden; turn it on to read them",
        "shown on screen, never printed",
    ),
    notes=(
        "Table seats six.",
        "Bed against the party wall.",
        "Counter, waste under.",
    ),
    draft="DRAFT",
    printing=(
        "The draft mark carries its own answer for the printer, so nothing has to",
        "be switched off before the page is printed.",
    ),
)

# The page in French.
FRENCH = Words(
    title="Un plan, quatre calques",
    intro=(
        "Les murs sont toujours là. Tout le reste est un calque à afficher ou "
        "masquer."
    ),
    layers=("Mobilier", "Cotes", "Notes", "Brouillon"),
    holdings=(
        "affiché ; désactivez-le et les pièces sont vides",
        "affiché ; les distances autour du plan",
        "masqué ; activez-le pour les lire",
        "affiché à l'écran, jamais imprimé",
    ),
    notes=(
        "Table pour six personnes.",
        "Lit contre le mur mitoyen.",
        "Plan de travail, poubelle dessous.",
    ),
    draft="BROUILLON",
    printing=(
        "La mention de brouillon porte sa propre consigne pour l'imprimante :",
        "rien n'a besoin d'être masqué avant d'imprimer la page.",
    ),
)


# Every language the example is written in. A language is added by writing its own set
# of words and naming it here.
WORDS = {_language.ENGLISH: ENGLISH, _language.FRENCH: FRENCH}


def walls(content: hqf_pdf.Content) -> None:
    """Draws the walls: the outer room and the partition that splits it."""
    x, y, width, height = PLAN
    content.save_state()
    content.set_stroke(hqf_pdf.Rgb.gray(0.15))
    content.set_line_width(3.0)
    content.rect(x, y, width, height)
    content.stroke()
    content.move_to(x + 265.0, y)
    content.line_to(x + 265.0, y + 190.0)
    content.stroke()
    content.restore_state()


def furniture(content: hqf_pdf.Content) -> None:
    """Draws the furniture: a table, a bed and a counter, each a filled outline."""
    x, y, _, height = PLAN
    pieces = [
        (x + 40.0, y + height - 110.0, 120.0, 70.0),
        (x + 300.0, y + height - 130.0, 90.0, 110.0),
        (x + 290.0, y + 30.0, 110.0, 40.0),
    ]
    content.save_state()
    content.set_fill(hqf_pdf.Rgb(0.85, 0.88, 0.93))
    content.set_stroke(hqf_pdf.Rgb(0.35, 0.45, 0.6))
    content.set_line_width(1.0)
    for px, py, pw, ph in pieces:
        content.rect(px, py, pw, ph)
        content.fill()
        content.rect(px, py, pw, ph)
        content.stroke()
    content.restore_state()


def dimensions(content: hqf_pdf.Content, font: hqf_pdf.FontHandle) -> None:
    """Draws a line under the plan and one beside it, each with the distance it
    stands for."""
    x, y, width, height = PLAN
    below = y - 26.0
    beside = x - 46.0

    content.save_state()
    content.set_stroke(hqf_pdf.Rgb(0.2, 0.5, 0.35))
    content.set_fill(hqf_pdf.Rgb(0.2, 0.5, 0.35))
    content.set_line_width(0.8)

    content.move_to(x, below)
    content.line_to(x + width, below)
    content.move_to(x, below - 5.0)
    content.line_to(x, below + 5.0)
    content.move_to(x + width, below - 5.0)
    content.line_to(x + width, below + 5.0)
    content.move_to(beside, y)
    content.line_to(beside, y + height)
    content.move_to(beside - 5.0, y)
    content.line_to(beside + 5.0, y)
    content.move_to(beside - 5.0, y + height)
    content.line_to(beside + 5.0, y + height)
    content.stroke()

    content.draw_text(font, 9.0, x + width / 2.0 - 18.0, below + 8.0, ALONG)
    content.draw_text(font, 9.0, beside + 6.0, y + height / 2.0, ACROSS)
    content.restore_state()


def notes(content: hqf_pdf.Content, font: hqf_pdf.FontHandle, words: Words) -> None:
    """Draws what someone reading the plan wants said, and a reader who is only
    looking at the rooms does not."""
    x, y, _, height = PLAN
    places = [
        (x + 44.0, y + height - 130.0),
        (x + 292.0, y + height - 148.0),
        (x + 292.0, y + 16.0),
    ]
    content.save_state()
    content.set_fill(hqf_pdf.Rgb(0.7, 0.25, 0.1))
    for (nx, ny), line in zip(places, words.notes):
        content.draw_text(font, 8.0, nx, ny, line)
    content.restore_state()


def legend(content: hqf_pdf.Content, font: hqf_pdf.FontHandle, words: Words) -> None:
    """Draws the legend under the plan: what each layer holds and how it starts."""
    baseline = 300.0
    for name, what in zip(words.layers, words.holdings):
        content.draw_text(font, 10.0, 80.0, baseline, name)
        content.save_state()
        content.set_fill(hqf_pdf.Rgb.gray(0.35))
        content.draw_text(font, 10.0, 170.0, baseline, what)
        content.restore_state()
        baseline -= 18.0

    content.save_state()
    content.set_fill(hqf_pdf.Rgb.gray(0.35))
    content.draw_text(
        font,
        10.0,
        80.0,
        baseline - 12.0,
        words.printing[0],
    )
    content.draw_text(font, 10.0, 80.0, baseline - 26.0, words.printing[1])
    content.restore_state()


def on_layer(
    content: hqf_pdf.Content,
    layer: hqf_pdf.LayerHandle,
    body: Callable[[hqf_pdf.Content], None],
) -> None:
    """Draws `body` inside `layer`, so a reader shows and hides all of it at once."""
    content.begin_layer(layer)
    body(content)
    content.end_marked()


def main() -> None:
    language = _language.from_environment()
    words = _language.words_of(WORDS, language)

    # A named file is written as named; the default one carries the language, so the two
    # languages do not overwrite each other in `tmp/`.
    out = _out.output_path(Path(_language.file_name("layers.pdf", language)).stem)

    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    font = document.add_font(hqf_pdf.Font.from_path(_out.font_path()))

    furniture_layer = document.add_layer(hqf_pdf.Layer(words.layers[0]))
    dimensions_layer = document.add_layer(hqf_pdf.Layer(words.layers[1]))
    notes_layer = document.add_layer(hqf_pdf.Layer(words.layers[2]).visible(False))
    draft_layer = document.add_layer(
        hqf_pdf.Layer(words.layers[3]).on_screen(True).printed(False)
    )

    content = hqf_pdf.Content()
    content.draw_text(font, 15.0, 80.0, 750.0, words.title)
    content.save_state()
    content.set_fill(hqf_pdf.Rgb.gray(0.35))
    content.draw_text(
        font,
        10.0,
        80.0,
        730.0,
        words.intro,
    )
    content.restore_state()

    walls(content)
    on_layer(content, furniture_layer, furniture)
    on_layer(content, dimensions_layer, lambda target: dimensions(target, font))
    on_layer(content, notes_layer, lambda target: notes(target, font, words))

    def draft(target: hqf_pdf.Content) -> None:
        x, y, width, height = PLAN
        stamp = hqf_pdf.Stamp(
            font,
            words.draft,
            slant=hqf_pdf.Slant.Up,
            color=hqf_pdf.Rgb(0.8, 0.3, 0.3),
        )
        stamp.draw(target, x, y, width, height)

    on_layer(content, draft_layer, draft)
    legend(content, font, words)

    page = hqf_pdf.Page.a4()
    page.set_content(content)
    document.add_page(page)

    written = document.write(out)
    print(f"wrote {out}: {written} bytes, {len(words.layers)} layers")


if __name__ == "__main__":
    main()