Source for: lesson10.py [raw]

  1from fonts import adjust_widths_by_letter
  2from hyphen import insert_soft_hyphens
  3
  4
  5class Box():
  6
  7    def __init__(self, x=0, y=0, w=1, h=1, stretchy=False, letter="x"):
  8        """Accept arguments to define our box, and store them."""
  9        self.x = x
 10        self.y = y
 11        self.w = w
 12        self.h = h
 13        self.stretchy = stretchy
 14        self.letter = letter
 15
 16    def __repr__(self):
 17        return 'Box(%s, %s, %s, %s, "%s")' % (
 18            self.x, self.y, self.w, self.h, self.letter
 19        )
 20
 21
 22p_and_p = open("pride-and-prejudice.txt").read()
 23p_and_p = insert_soft_hyphens(p_and_p)  # Insert invisible hyphens
 24text_boxes = []
 25for l in p_and_p:
 26    text_boxes.append(Box(letter=l, stretchy=l == " "))
 27adjust_widths_by_letter(text_boxes)
 28
 29# A few pages all the same size
 30pages = [Box(i * 35, 0, 30, 50) for i in range(10)]
 31
 32
 33def hyphenbox():
 34    b = Box(letter="-")
 35    adjust_widths_by_letter([b])
 36    return b
 37
 38
 39# We add a "separation" constant so you can see the boxes individually
 40separation = .05
 41
 42
 43def layout(_boxes):
 44    """Layout boxes along pages.
 45
 46    Keep in mind that this function modifies the boxes themselves, so
 47    you should be very careful about trying to call layout() more than once
 48    on the same boxes.
 49
 50    Specifically, some spaces will become 0-width and not stretchy.
 51    """
 52
 53    # Because we modify the box list, we will work on a copy
 54    boxes = _boxes[:]
 55    # We start at page 0
 56    page = 0
 57    # The 1st box should be placed in the correct page
 58    previous = boxes.pop(0)
 59    previous.x = pages[page].x
 60    previous.y = pages[page].y
 61    row = []
 62    while boxes:
 63        # We take the new 1st box
 64        box = boxes.pop(0)
 65        # And put it next to the other
 66        box.x = previous.x + previous.w + separation
 67        # At the same vertical location
 68        box.y = previous.y
 69
 70        # Handle breaking on newlines
 71        break_line = False
 72        # But if it's a newline
 73        if (box.letter == "\n"):
 74            break_line = True
 75            # Newlines take no horizontal space ever
 76            box.w = 0
 77            box.stretchy = False
 78
 79        # Or if it's too far to the right, and is a
 80        # good place to break the line...
 81        elif (box.x + box.w) > (
 82            pages[page].x + pages[page].w
 83        ) and box.letter in (
 84            " ", "\xad"
 85        ):
 86            if box.letter == "\xad":
 87                # Add a visible hyphen in the row
 88                h_b = hyphenbox()
 89                h_b.x = previous.x + previous.w + separation
 90                h_b.y = previous.y
 91                _boxes.append(h_b)  # So it's drawn
 92                row.append(h_b)  # So it's justified
 93            break_line = True
 94            # We adjust the row
 95            # Remove all right-margin spaces
 96            while row[-1].letter == " ":
 97                row.pop()
 98            slack = (pages[page].x + pages[page].w) - (
 99                row[-1].x + row[-1].w
100            )
101            # Get a list of all the ones that are stretchy
102            stretchies = [b for b in row if b.stretchy]
103            if not stretchies:  # Nothing stretches do as before.
104                bump = slack / len(row)
105                # The 1st box gets 0 bumps, the 2nd gets 1 and so on
106                for i, b in enumerate(row):
107                    b.x += bump * i
108            else:
109                bump = slack / len(stretchies)
110                # Each stretchy gets wider
111                for b in stretchies:
112                    b.w += bump
113                # And we put each thing next to the previous one
114                for j, b in enumerate(row[1:], 1):
115                    b.x = row[j - 1].x + row[j - 1].w + separation
116
117        if break_line:
118            # We start a new row
119            row = []
120            # We go all the way left and a little down
121            box.x = pages[page].x
122            box.y = previous.y + previous.h + separation
123
124        # But if we go too far down
125        if box.y + box.h > pages[page].y + pages[page].h:
126            # We go to the next page
127            page += 1
128            # And put the box at the top-left
129            box.x = pages[page].x
130            box.y = pages[page].y
131
132        # Put the box in the row
133        row.append(box)
134
135        # Collapse all left-margin space
136        if all(b.letter == " " for b in row):
137            box.w = 0
138            box.stretchy = False
139            box.x = pages[page].x
140
141        previous = box
142
143
144layout(text_boxes)
145
146
147import svgwrite
148
149
150def draw_boxes(boxes, fname, size, hide_boxes=False):
151    dwg = svgwrite.Drawing(fname, profile="full", size=size)
152    # Draw the pages
153    for page in pages:
154        dwg.add(
155            dwg.rect(
156                insert=(f"{page.x}cm", f"{page.y}cm"),
157                size=(f"{page.w}cm", f"{page.h}cm"),
158                fill="lightblue",
159            )
160        )
161    # Draw all the boxes
162    for box in boxes:
163        # The box color depends on its features
164        color = "green" if box.stretchy else "red"
165        # Make the colored boxes optional
166        if not hide_boxes:
167            dwg.add(
168                dwg.rect(
169                    insert=(f"{box.x}cm", f"{box.y}cm"),
170                    size=(f"{box.w}cm", f"{box.h}cm"),
171                    fill=color,
172                )
173            )
174        # Display the letter in the box
175        if box.letter:
176            dwg.add(
177                dwg.text(
178                    box.letter,
179                    insert=(f"{box.x}cm", f"{box.y + box.h}cm"),
180                    font_size=f"{box.h}cm",
181                    font_family="Arial",
182                )
183            )
184    dwg.save()
185
186
187draw_boxes(
188    text_boxes, "lesson10.svg", ("30cm", "50cm"), hide_boxes=True
189)
190