retroflow 0.3.0__tar.gz → 0.4.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. {retroflow-0.3.0 → retroflow-0.4.2}/PKG-INFO +52 -3
  2. {retroflow-0.3.0 → retroflow-0.4.2}/README.md +51 -2
  3. {retroflow-0.3.0 → retroflow-0.4.2}/pyproject.toml +1 -1
  4. {retroflow-0.3.0 → retroflow-0.4.2}/src/retroflow/__init__.py +1 -1
  5. {retroflow-0.3.0 → retroflow-0.4.2}/src/retroflow/generator.py +142 -15
  6. {retroflow-0.3.0 → retroflow-0.4.2}/src/retroflow/renderer.py +3 -3
  7. {retroflow-0.3.0 → retroflow-0.4.2}/tests/unit/test_generator.py +251 -0
  8. {retroflow-0.3.0 → retroflow-0.4.2}/uv.lock +1 -1
  9. {retroflow-0.3.0 → retroflow-0.4.2}/.github/workflows/publish.yml +0 -0
  10. {retroflow-0.3.0 → retroflow-0.4.2}/.github/workflows/test.yml +0 -0
  11. {retroflow-0.3.0 → retroflow-0.4.2}/.gitignore +0 -0
  12. {retroflow-0.3.0 → retroflow-0.4.2}/.python-version +0 -0
  13. {retroflow-0.3.0 → retroflow-0.4.2}/CLAUDE.md +0 -0
  14. {retroflow-0.3.0 → retroflow-0.4.2}/LICENSE +0 -0
  15. {retroflow-0.3.0 → retroflow-0.4.2}/codecov.yml +0 -0
  16. {retroflow-0.3.0 → retroflow-0.4.2}/src/retroflow/layout.py +0 -0
  17. {retroflow-0.3.0 → retroflow-0.4.2}/src/retroflow/parser.py +0 -0
  18. {retroflow-0.3.0 → retroflow-0.4.2}/src/retroflow/py.typed +0 -0
  19. {retroflow-0.3.0 → retroflow-0.4.2}/src/retroflow/router.py +0 -0
  20. {retroflow-0.3.0 → retroflow-0.4.2}/tests/conftest.py +0 -0
  21. {retroflow-0.3.0 → retroflow-0.4.2}/tests/integration/__init__.py +0 -0
  22. {retroflow-0.3.0 → retroflow-0.4.2}/tests/integration/test_flowchart_generation.py +0 -0
  23. {retroflow-0.3.0 → retroflow-0.4.2}/tests/unit/__init__.py +0 -0
  24. {retroflow-0.3.0 → retroflow-0.4.2}/tests/unit/test_coverage_extras.py +0 -0
  25. {retroflow-0.3.0 → retroflow-0.4.2}/tests/unit/test_layout.py +0 -0
  26. {retroflow-0.3.0 → retroflow-0.4.2}/tests/unit/test_parser.py +0 -0
  27. {retroflow-0.3.0 → retroflow-0.4.2}/tests/unit/test_renderer.py +0 -0
  28. {retroflow-0.3.0 → retroflow-0.4.2}/tests/unit/test_router.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: retroflow
3
- Version: 0.3.0
3
+ Version: 0.4.2
4
4
  Summary: Generate beautiful ASCII and PNG flowcharts from simple text descriptions
5
5
  Project-URL: Homepage, https://github.com/ronikobrosly/retroflow
6
6
  Project-URL: Repository, https://github.com/ronikobrosly/retroflow
@@ -123,9 +123,10 @@ print(flowchart)
123
123
 
124
124
  - **Simple syntax**: Define flowcharts using intuitive `A -> B` arrow notation
125
125
  - **ASCII output**: Generate text-based flowcharts for terminals and documentation
126
+ - **PNG export**: Save high-resolution PNG images with customizable fonts
126
127
  - **Intelligent layout**: Automatic node positioning using NetworkX with barycenter heuristic
127
128
  - **Cycle detection**: Handles cyclic graphs gracefully with back-edge routing
128
- - **Customizable**: Adjust text width, box sizes, spacing, and shadows
129
+ - **Customizable**: Adjust text width, box sizes, spacing, shadows, and fonts
129
130
  - **Unicode box-drawing**: Beautiful boxes with optional shadow effects
130
131
 
131
132
  ## Usage
@@ -184,6 +185,32 @@ generator.save_txt("""
184
185
  """, "flowchart.txt")
185
186
  ```
186
187
 
188
+ ### Export to PNG
189
+
190
+ Save your flowchart as a high-resolution PNG image:
191
+
192
+ ```python
193
+ generator = FlowchartGenerator()
194
+
195
+ generator.save_png("""
196
+ A -> B
197
+ B -> C
198
+ """, "flowchart.png")
199
+ ```
200
+
201
+ Customize the PNG output with various options:
202
+
203
+ ```python
204
+ generator.save_png(
205
+ "A -> B\nB -> C",
206
+ "flowchart.png",
207
+ font_size=24, # Larger font = higher resolution (default: 16)
208
+ bg_color="#1a1a2e", # Background color (default: "#FFFFFF")
209
+ fg_color="#00ff00", # Text color (default: "#000000")
210
+ padding=40, # Padding around diagram in pixels (default: 20)
211
+ )
212
+ ```
213
+
187
214
  ## Configuration
188
215
 
189
216
  ### FlowchartGenerator Options
@@ -194,10 +221,31 @@ generator = FlowchartGenerator(
194
221
  min_box_width=10, # Minimum box width (default: 10)
195
222
  horizontal_spacing=12, # Space between boxes horizontally (default: 12)
196
223
  vertical_spacing=6, # Space between boxes vertically (default: 6)
197
- shadow=True # Whether to draw box shadows (default: True)
224
+ shadow=True, # Whether to draw box shadows (default: True)
225
+ font="Cascadia Code", # Font for PNG output (default: None, uses system font)
198
226
  )
199
227
  ```
200
228
 
229
+ ### Font Configuration
230
+
231
+ You can specify a font for PNG output either at initialization or per-call:
232
+
233
+ ```python
234
+ # Set font for all PNG exports from this generator
235
+ generator = FlowchartGenerator(font="Cascadia Code")
236
+ generator.save_png("A -> B", "flowchart.png")
237
+
238
+ # Or override the font for a specific export
239
+ generator.save_png("A -> B", "flowchart.png", font="Monaco")
240
+ ```
241
+
242
+ Common monospace fonts that work well:
243
+ - **Windows**: `Cascadia Code`, `Consolas`, `Courier New`
244
+ - **macOS**: `Monaco`, `Menlo`, `SF Mono`
245
+ - **Linux**: `DejaVu Sans Mono`, `Ubuntu Mono`, `Liberation Mono`
246
+
247
+ If the specified font isn't found, RetroFlow automatically falls back to available system fonts.
248
+
201
249
  ## Input Format
202
250
 
203
251
  The input format uses a simple arrow syntax:
@@ -232,6 +280,7 @@ The main class for generating flowcharts.
232
280
  |--------|-------------|
233
281
  | `generate(input_text)` | Generate ASCII flowchart string |
234
282
  | `save_txt(input_text, filename)` | Save flowchart to a text file |
283
+ | `save_png(input_text, filename, ...)` | Save flowchart as a PNG image |
235
284
 
236
285
  ### Convenience Functions
237
286
 
@@ -94,9 +94,10 @@ print(flowchart)
94
94
 
95
95
  - **Simple syntax**: Define flowcharts using intuitive `A -> B` arrow notation
96
96
  - **ASCII output**: Generate text-based flowcharts for terminals and documentation
97
+ - **PNG export**: Save high-resolution PNG images with customizable fonts
97
98
  - **Intelligent layout**: Automatic node positioning using NetworkX with barycenter heuristic
98
99
  - **Cycle detection**: Handles cyclic graphs gracefully with back-edge routing
99
- - **Customizable**: Adjust text width, box sizes, spacing, and shadows
100
+ - **Customizable**: Adjust text width, box sizes, spacing, shadows, and fonts
100
101
  - **Unicode box-drawing**: Beautiful boxes with optional shadow effects
101
102
 
102
103
  ## Usage
@@ -155,6 +156,32 @@ generator.save_txt("""
155
156
  """, "flowchart.txt")
156
157
  ```
157
158
 
159
+ ### Export to PNG
160
+
161
+ Save your flowchart as a high-resolution PNG image:
162
+
163
+ ```python
164
+ generator = FlowchartGenerator()
165
+
166
+ generator.save_png("""
167
+ A -> B
168
+ B -> C
169
+ """, "flowchart.png")
170
+ ```
171
+
172
+ Customize the PNG output with various options:
173
+
174
+ ```python
175
+ generator.save_png(
176
+ "A -> B\nB -> C",
177
+ "flowchart.png",
178
+ font_size=24, # Larger font = higher resolution (default: 16)
179
+ bg_color="#1a1a2e", # Background color (default: "#FFFFFF")
180
+ fg_color="#00ff00", # Text color (default: "#000000")
181
+ padding=40, # Padding around diagram in pixels (default: 20)
182
+ )
183
+ ```
184
+
158
185
  ## Configuration
159
186
 
160
187
  ### FlowchartGenerator Options
@@ -165,10 +192,31 @@ generator = FlowchartGenerator(
165
192
  min_box_width=10, # Minimum box width (default: 10)
166
193
  horizontal_spacing=12, # Space between boxes horizontally (default: 12)
167
194
  vertical_spacing=6, # Space between boxes vertically (default: 6)
168
- shadow=True # Whether to draw box shadows (default: True)
195
+ shadow=True, # Whether to draw box shadows (default: True)
196
+ font="Cascadia Code", # Font for PNG output (default: None, uses system font)
169
197
  )
170
198
  ```
171
199
 
200
+ ### Font Configuration
201
+
202
+ You can specify a font for PNG output either at initialization or per-call:
203
+
204
+ ```python
205
+ # Set font for all PNG exports from this generator
206
+ generator = FlowchartGenerator(font="Cascadia Code")
207
+ generator.save_png("A -> B", "flowchart.png")
208
+
209
+ # Or override the font for a specific export
210
+ generator.save_png("A -> B", "flowchart.png", font="Monaco")
211
+ ```
212
+
213
+ Common monospace fonts that work well:
214
+ - **Windows**: `Cascadia Code`, `Consolas`, `Courier New`
215
+ - **macOS**: `Monaco`, `Menlo`, `SF Mono`
216
+ - **Linux**: `DejaVu Sans Mono`, `Ubuntu Mono`, `Liberation Mono`
217
+
218
+ If the specified font isn't found, RetroFlow automatically falls back to available system fonts.
219
+
172
220
  ## Input Format
173
221
 
174
222
  The input format uses a simple arrow syntax:
@@ -203,6 +251,7 @@ The main class for generating flowcharts.
203
251
  |--------|-------------|
204
252
  | `generate(input_text)` | Generate ASCII flowchart string |
205
253
  | `save_txt(input_text, filename)` | Save flowchart to a text file |
254
+ | `save_png(input_text, filename, ...)` | Save flowchart as a PNG image |
206
255
 
207
256
  ### Convenience Functions
208
257
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "retroflow"
3
- version = "0.3.0"
3
+ version = "0.4.2"
4
4
  description = "Generate beautiful ASCII and PNG flowcharts from simple text descriptions"
5
5
  authors = [{name = "Roni Kobrosly", email = "roni.kobrosly@gmail.com"}]
6
6
  readme = "README.md"
@@ -19,7 +19,7 @@ from .parser import ParseError, Parser, parse_flowchart
19
19
  from .renderer import BoxRenderer, Canvas, LineRenderer
20
20
  from .router import BoxInfo, EdgeRoute, EdgeRouter
21
21
 
22
- __version__ = "0.3.0"
22
+ __version__ = "0.4.2"
23
23
 
24
24
  __all__ = [
25
25
  "FlowchartGenerator",
@@ -6,7 +6,9 @@ beautiful ASCII flowcharts.
6
6
  """
7
7
 
8
8
  from pathlib import Path
9
- from typing import Dict, List, Tuple
9
+ from typing import Dict, List, Optional, Tuple
10
+
11
+ from PIL import Image, ImageDraw, ImageFont
10
12
 
11
13
  from .layout import LayoutResult, NetworkXLayout
12
14
  from .parser import Parser
@@ -40,6 +42,7 @@ class FlowchartGenerator:
40
42
  horizontal_spacing: int = 12,
41
43
  vertical_spacing: int = 6,
42
44
  shadow: bool = True,
45
+ font: Optional[str] = None,
43
46
  ):
44
47
  """
45
48
  Initialize the flowchart generator.
@@ -50,12 +53,14 @@ class FlowchartGenerator:
50
53
  horizontal_spacing: Space between boxes horizontally
51
54
  vertical_spacing: Space between boxes vertically
52
55
  shadow: Whether to draw box shadows
56
+ font: Font name for PNG output (e.g., "Cascadia Code", "Monaco")
53
57
  """
54
58
  self.max_text_width = max_text_width
55
59
  self.min_box_width = min_box_width
56
60
  self.horizontal_spacing = horizontal_spacing
57
61
  self.vertical_spacing = vertical_spacing
58
62
  self.shadow = shadow
63
+ self.font = font
59
64
 
60
65
  self.parser = Parser()
61
66
  self.layout_engine = NetworkXLayout()
@@ -121,6 +126,128 @@ class FlowchartGenerator:
121
126
  output_path = Path(filename)
122
127
  output_path.write_text(flowchart, encoding="utf-8")
123
128
 
129
+ def save_png(
130
+ self,
131
+ input_text: str,
132
+ filename: str,
133
+ font_size: int = 16,
134
+ bg_color: str = "#FFFFFF",
135
+ fg_color: str = "#000000",
136
+ padding: int = 20,
137
+ font: Optional[str] = None,
138
+ ) -> None:
139
+ """
140
+ Generate flowchart and save as a high-resolution PNG image.
141
+
142
+ The PNG rendering is faithful to the ASCII version, using a monospace
143
+ font to preserve the exact character layout and box-drawing characters.
144
+
145
+ Args:
146
+ input_text: Multi-line string with connections like "A -> B"
147
+ filename: Output filename (should end in .png)
148
+ font_size: Font size in points (higher = higher resolution)
149
+ bg_color: Background color as hex string (e.g., "#FFFFFF")
150
+ fg_color: Foreground/text color as hex string (e.g., "#000000")
151
+ padding: Padding around the diagram in pixels
152
+ font: Font name to use (overrides instance font if provided)
153
+
154
+ Example:
155
+ >>> generator = FlowchartGenerator(font="Cascadia Code")
156
+ >>> generator.save_png("A -> B -> C", "flowchart.png", font_size=24)
157
+ """
158
+ ascii_art = self.generate(input_text)
159
+ lines = ascii_art.split("\n")
160
+
161
+ # Use provided font, fall back to instance font, then system defaults
162
+ font_name = font or self.font
163
+ loaded_font = self._load_monospace_font(font_size, font_name)
164
+
165
+ # Calculate character dimensions using a reference character
166
+ bbox = loaded_font.getbbox("M")
167
+ char_width = bbox[2] - bbox[0]
168
+ char_height = bbox[3] - bbox[1]
169
+ line_height = int(char_height * 1.2) # Add some line spacing
170
+
171
+ # Calculate image dimensions
172
+ max_line_len = max(len(line) for line in lines) if lines else 0
173
+ img_width = char_width * max_line_len + padding * 2
174
+ img_height = line_height * len(lines) + padding * 2
175
+
176
+ # Ensure minimum dimensions
177
+ img_width = max(img_width, 100)
178
+ img_height = max(img_height, 100)
179
+
180
+ # Create image and draw text
181
+ img = Image.new("RGB", (img_width, img_height), bg_color)
182
+ draw = ImageDraw.Draw(img)
183
+
184
+ y = padding
185
+ for line in lines:
186
+ draw.text((padding, y), line, font=loaded_font, fill=fg_color)
187
+ y += line_height
188
+
189
+ # Save the image
190
+ output_path = Path(filename)
191
+ img.save(output_path, "PNG")
192
+
193
+ def _load_monospace_font(
194
+ self, font_size: int, font_name: Optional[str] = None
195
+ ) -> ImageFont.FreeTypeFont:
196
+ """
197
+ Load a monospace font for PNG rendering.
198
+
199
+ Tries the following in order:
200
+ 1. User-specified font name if provided
201
+ 2. Common system monospace fonts
202
+ 3. Pillow's default font
203
+
204
+ Args:
205
+ font_size: Font size in points
206
+ font_name: Optional font name (e.g., "Cascadia Code", "Monaco")
207
+
208
+ Returns:
209
+ A PIL ImageFont object
210
+ """
211
+ # Build list of fonts to try
212
+ fonts_to_try = []
213
+
214
+ # Add user-specified font first
215
+ if font_name:
216
+ fonts_to_try.append(font_name)
217
+
218
+ # Common monospace fonts across different systems
219
+ fonts_to_try.extend(
220
+ [
221
+ # Linux
222
+ "DejaVuSansMono",
223
+ "DejaVu Sans Mono",
224
+ "/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf",
225
+ # macOS
226
+ "Monaco",
227
+ "Menlo",
228
+ "/System/Library/Fonts/Monaco.ttf",
229
+ "/System/Library/Fonts/Menlo.ttc",
230
+ # Windows
231
+ "Consolas",
232
+ "Cascadia Code",
233
+ "Courier New",
234
+ "C:/Windows/Fonts/consola.ttf",
235
+ ]
236
+ )
237
+
238
+ for font in fonts_to_try:
239
+ try:
240
+ return ImageFont.truetype(font, font_size)
241
+ except OSError:
242
+ continue
243
+
244
+ # Fall back to Pillow's default font
245
+ try:
246
+ return ImageFont.load_default(size=font_size)
247
+ except TypeError:
248
+ # Older Pillow versions don't support size parameter
249
+ return ImageFont.load_default()
250
+
124
251
  def _calculate_all_box_dimensions(
125
252
  self, layout_result: LayoutResult
126
253
  ) -> Dict[str, BoxDimensions]:
@@ -343,16 +470,16 @@ class FlowchartGenerator:
343
470
  canvas.set(src_port_x, src_port_y, LINE_CHARS["tee_down"])
344
471
 
345
472
  # Calculate path
346
- # Start below source (after shadow)
347
- start_y = src_port_y + (2 if self.shadow else 1)
473
+ # Start below source (through shadow - arrow lines overwrite shadows)
474
+ start_y = src_port_y + 1
348
475
  # End at target top
349
476
  end_y = tgt_port_y
350
477
 
351
478
  if src_port_x == tgt_port_x:
352
- # Direct vertical line
353
- self._draw_vertical_line(canvas, src_port_x, start_y, end_y - 1)
354
- # Draw arrow at target
355
- canvas.set(tgt_port_x, tgt_port_y, ARROW_CHARS["down"])
479
+ # Direct vertical line (stop before arrow position)
480
+ self._draw_vertical_line(canvas, src_port_x, start_y, end_y - 2)
481
+ # Draw arrow one row above target box (doesn't overwrite border)
482
+ canvas.set(tgt_port_x, tgt_port_y - 1, ARROW_CHARS["down"])
356
483
  else:
357
484
  # Need to route with horizontal segment
358
485
  mid_y = start_y + (end_y - start_y) // 2
@@ -375,11 +502,11 @@ class FlowchartGenerator:
375
502
  else:
376
503
  canvas.set(tgt_port_x, mid_y, LINE_CHARS["corner_top_left"])
377
504
 
378
- # Vertical from mid to target
379
- self._draw_vertical_line(canvas, tgt_port_x, mid_y + 1, end_y - 1)
505
+ # Vertical from mid to target (stop before arrow position)
506
+ self._draw_vertical_line(canvas, tgt_port_x, mid_y + 1, end_y - 2)
380
507
 
381
- # Draw arrow at target
382
- canvas.set(tgt_port_x, tgt_port_y, ARROW_CHARS["down"])
508
+ # Draw arrow one row above target box (doesn't overwrite border)
509
+ canvas.set(tgt_port_x, tgt_port_y - 1, ARROW_CHARS["down"])
383
510
 
384
511
  def _calculate_port_x(
385
512
  self, box_x: int, box_width: int, port_idx: int, port_count: int
@@ -531,8 +658,8 @@ class FlowchartGenerator:
531
658
  canvas.set(route_x, entry_y, LINE_CHARS["corner_top_left"])
532
659
  # else leave existing corner/tee
533
660
 
534
- # 8. Horizontal line from margin to target
535
- for x in range(route_x + 1, entry_x):
661
+ # 8. Horizontal line from margin to target (stop before arrow position)
662
+ for x in range(route_x + 1, entry_x - 1):
536
663
  current = canvas.get(x, entry_y)
537
664
  if current == LINE_CHARS["vertical"]:
538
665
  canvas.set(x, entry_y, LINE_CHARS["cross"])
@@ -542,5 +669,5 @@ class FlowchartGenerator:
542
669
  canvas.set(x, entry_y, LINE_CHARS["horizontal"])
543
670
  # else leave horizontal lines alone
544
671
 
545
- # 9. Arrow at target entry point (on left border)
546
- canvas.set(entry_x, entry_y, ARROW_CHARS["right"])
672
+ # 9. Arrow one column before target box (doesn't overwrite border)
673
+ canvas.set(entry_x - 1, entry_y, ARROW_CHARS["right"])
@@ -237,7 +237,7 @@ class LineRenderer:
237
237
  canvas.set(x, y, LINE_CHARS["tee_left"])
238
238
  elif current in (ARROW_CHARS["down"], ARROW_CHARS["up"]):
239
239
  pass # Don't overwrite arrows
240
- elif current == " " or current == LINE_CHARS["vertical"]:
240
+ elif current in (" ", LINE_CHARS["vertical"], BOX_CHARS["shadow"]):
241
241
  canvas.set(x, y, LINE_CHARS["vertical"])
242
242
 
243
243
  # Draw arrow at end
@@ -274,7 +274,7 @@ class LineRenderer:
274
274
  canvas.set(x, y, LINE_CHARS["tee_up"])
275
275
  elif current in (ARROW_CHARS["left"], ARROW_CHARS["right"]):
276
276
  pass # Don't overwrite arrows
277
- elif current == " " or current == LINE_CHARS["horizontal"]:
277
+ elif current in (" ", LINE_CHARS["horizontal"], BOX_CHARS["shadow"]):
278
278
  canvas.set(x, y, LINE_CHARS["horizontal"])
279
279
 
280
280
  # Draw arrow at end
@@ -289,7 +289,7 @@ class LineRenderer:
289
289
  """
290
290
  current = canvas.get(x, y)
291
291
 
292
- if current == " ":
292
+ if current in (" ", BOX_CHARS["shadow"]):
293
293
  canvas.set(x, y, LINE_CHARS[f"corner_{corner_type}"])
294
294
  elif current == LINE_CHARS["horizontal"]:
295
295
  if "top" in corner_type:
@@ -3,6 +3,8 @@
3
3
  import os
4
4
  import tempfile
5
5
 
6
+ from PIL import Image
7
+
6
8
  from retroflow.generator import FlowchartGenerator
7
9
  from retroflow.renderer import ARROW_CHARS, BOX_CHARS
8
10
 
@@ -18,6 +20,7 @@ class TestFlowchartGeneratorInit:
18
20
  assert gen.horizontal_spacing == 12
19
21
  assert gen.vertical_spacing == 6
20
22
  assert gen.shadow is True
23
+ assert gen.font is None
21
24
 
22
25
  def test_custom_max_text_width(self):
23
26
  """Test FlowchartGenerator with custom max_text_width."""
@@ -44,6 +47,11 @@ class TestFlowchartGeneratorInit:
44
47
  gen = FlowchartGenerator(shadow=False)
45
48
  assert gen.shadow is False
46
49
 
50
+ def test_custom_font(self):
51
+ """Test FlowchartGenerator with custom font."""
52
+ gen = FlowchartGenerator(font="Cascadia Code")
53
+ assert gen.font == "Cascadia Code"
54
+
47
55
  def test_all_custom_parameters(self):
48
56
  """Test FlowchartGenerator with all custom parameters."""
49
57
  gen = FlowchartGenerator(
@@ -225,6 +233,249 @@ class TestFlowchartGeneratorSaveTxt:
225
233
  os.remove(filename)
226
234
 
227
235
 
236
+ class TestFlowchartGeneratorSavePng:
237
+ """Tests for FlowchartGenerator.save_png method."""
238
+
239
+ def test_save_png_creates_file(self, generator, simple_input):
240
+ """Test that save_png creates a file."""
241
+ with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:
242
+ filename = f.name
243
+
244
+ try:
245
+ generator.save_png(simple_input, filename)
246
+ assert os.path.exists(filename)
247
+ finally:
248
+ if os.path.exists(filename):
249
+ os.remove(filename)
250
+
251
+ def test_save_png_creates_valid_image(self, generator, simple_input):
252
+ """Test that save_png creates a valid PNG image."""
253
+ with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:
254
+ filename = f.name
255
+
256
+ try:
257
+ generator.save_png(simple_input, filename)
258
+ # Should be openable as a valid image
259
+ with Image.open(filename) as img:
260
+ assert img.format == "PNG"
261
+ assert img.mode == "RGB"
262
+ assert img.width > 0
263
+ assert img.height > 0
264
+ finally:
265
+ if os.path.exists(filename):
266
+ os.remove(filename)
267
+
268
+ def test_save_png_custom_font_size(self, generator, simple_input):
269
+ """Test that larger font_size produces larger image."""
270
+ with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:
271
+ filename_small = f.name
272
+ with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:
273
+ filename_large = f.name
274
+
275
+ try:
276
+ generator.save_png(simple_input, filename_small, font_size=12)
277
+ generator.save_png(simple_input, filename_large, font_size=24)
278
+
279
+ with Image.open(filename_small) as img_small:
280
+ small_width, small_height = img_small.width, img_small.height
281
+ with Image.open(filename_large) as img_large:
282
+ large_width, large_height = img_large.width, img_large.height
283
+
284
+ # Larger font should produce larger image
285
+ assert large_width > small_width
286
+ assert large_height > small_height
287
+ finally:
288
+ for fn in [filename_small, filename_large]:
289
+ if os.path.exists(fn):
290
+ os.remove(fn)
291
+
292
+ def test_save_png_custom_colors(self, generator, simple_input):
293
+ """Test save_png with custom background and foreground colors."""
294
+ with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:
295
+ filename = f.name
296
+
297
+ try:
298
+ generator.save_png(
299
+ simple_input,
300
+ filename,
301
+ bg_color="#000000",
302
+ fg_color="#00FF00",
303
+ )
304
+ with Image.open(filename) as img:
305
+ # Check that image was created with correct format
306
+ assert img.format == "PNG"
307
+ assert img.mode == "RGB"
308
+
309
+ # Check corners are the background color (black)
310
+ pixels = img.load()
311
+ # Top-left corner should be background color
312
+ assert pixels[0, 0] == (0, 0, 0)
313
+ finally:
314
+ if os.path.exists(filename):
315
+ os.remove(filename)
316
+
317
+ def test_save_png_custom_padding(self, generator, simple_input):
318
+ """Test that larger padding produces larger image."""
319
+ with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:
320
+ filename_small = f.name
321
+ with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:
322
+ filename_large = f.name
323
+
324
+ try:
325
+ generator.save_png(simple_input, filename_small, padding=10)
326
+ generator.save_png(simple_input, filename_large, padding=50)
327
+
328
+ with Image.open(filename_small) as img_small:
329
+ small_width, small_height = img_small.width, img_small.height
330
+ with Image.open(filename_large) as img_large:
331
+ large_width, large_height = img_large.width, img_large.height
332
+
333
+ # Larger padding should produce larger image
334
+ assert large_width > small_width
335
+ assert large_height > small_height
336
+ finally:
337
+ for fn in [filename_small, filename_large]:
338
+ if os.path.exists(fn):
339
+ os.remove(fn)
340
+
341
+ def test_save_png_with_invalid_font(self, generator, simple_input):
342
+ """Test that invalid font name falls back gracefully."""
343
+ with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:
344
+ filename = f.name
345
+
346
+ try:
347
+ # Should not raise, should fall back to system/default font
348
+ generator.save_png(
349
+ simple_input,
350
+ filename,
351
+ font="NonexistentFontName12345",
352
+ )
353
+ assert os.path.exists(filename)
354
+ with Image.open(filename) as img:
355
+ assert img.format == "PNG"
356
+ finally:
357
+ if os.path.exists(filename):
358
+ os.remove(filename)
359
+
360
+ def test_save_png_with_instance_font(self, simple_input):
361
+ """Test that instance font is used when set."""
362
+ with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:
363
+ filename = f.name
364
+
365
+ try:
366
+ # Create generator with font specified
367
+ gen = FlowchartGenerator(font="DejaVu Sans Mono")
368
+ gen.save_png(simple_input, filename)
369
+ assert os.path.exists(filename)
370
+ with Image.open(filename) as img:
371
+ assert img.format == "PNG"
372
+ finally:
373
+ if os.path.exists(filename):
374
+ os.remove(filename)
375
+
376
+ def test_save_png_overwrites_existing(self, generator, simple_input):
377
+ """Test that save_png overwrites existing file."""
378
+ with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:
379
+ filename = f.name
380
+ # Write some dummy data
381
+ f.write(b"dummy content")
382
+
383
+ try:
384
+ generator.save_png(simple_input, filename)
385
+ # File should now be a valid PNG, not the dummy content
386
+ with Image.open(filename) as img:
387
+ assert img.format == "PNG"
388
+ finally:
389
+ if os.path.exists(filename):
390
+ os.remove(filename)
391
+
392
+ def test_save_png_with_branching(self, generator, branching_input):
393
+ """Test save_png with branching flowchart."""
394
+ with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:
395
+ filename = f.name
396
+
397
+ try:
398
+ generator.save_png(branching_input, filename)
399
+ with Image.open(filename) as img:
400
+ assert img.format == "PNG"
401
+ # Branching flowchart should be wider
402
+ assert img.width > 100
403
+ finally:
404
+ if os.path.exists(filename):
405
+ os.remove(filename)
406
+
407
+ def test_save_png_with_cyclic(self, generator, cyclic_input):
408
+ """Test save_png with cyclic flowchart."""
409
+ with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:
410
+ filename = f.name
411
+
412
+ try:
413
+ generator.save_png(cyclic_input, filename)
414
+ with Image.open(filename) as img:
415
+ assert img.format == "PNG"
416
+ finally:
417
+ if os.path.exists(filename):
418
+ os.remove(filename)
419
+
420
+ def test_save_png_minimum_dimensions(self, generator):
421
+ """Test that save_png enforces minimum image dimensions."""
422
+ with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:
423
+ filename = f.name
424
+
425
+ try:
426
+ # Very simple input
427
+ generator.save_png("A -> B", filename, font_size=8, padding=5)
428
+ with Image.open(filename) as img:
429
+ # Should enforce minimum dimensions
430
+ assert img.width >= 100
431
+ assert img.height >= 100
432
+ finally:
433
+ if os.path.exists(filename):
434
+ os.remove(filename)
435
+
436
+
437
+ class TestFlowchartGeneratorLoadFont:
438
+ """Tests for FlowchartGenerator._load_monospace_font method."""
439
+
440
+ def test_load_font_returns_font(self, generator):
441
+ """Test that _load_monospace_font returns a font object."""
442
+ font = generator._load_monospace_font(16)
443
+ assert font is not None
444
+ # Should be able to get bounding box
445
+ bbox = font.getbbox("M")
446
+ assert bbox is not None
447
+ assert len(bbox) == 4
448
+
449
+ def test_load_font_respects_size(self, generator):
450
+ """Test that different font sizes produce different bbox sizes."""
451
+ font_small = generator._load_monospace_font(12)
452
+ font_large = generator._load_monospace_font(24)
453
+
454
+ bbox_small = font_small.getbbox("M")
455
+ bbox_large = font_large.getbbox("M")
456
+
457
+ # Larger font should have larger bounding box
458
+ small_width = bbox_small[2] - bbox_small[0]
459
+ large_width = bbox_large[2] - bbox_large[0]
460
+ assert large_width > small_width
461
+
462
+ def test_load_font_with_invalid_name(self, generator):
463
+ """Test that invalid font name falls through to system fonts."""
464
+ font = generator._load_monospace_font(16, "NonexistentFont12345")
465
+ assert font is not None
466
+ # Should still be usable
467
+ bbox = font.getbbox("M")
468
+ assert bbox is not None
469
+
470
+ def test_load_font_with_valid_name(self, generator):
471
+ """Test loading font by name."""
472
+ # Try a font that should exist on most systems
473
+ font = generator._load_monospace_font(16, "DejaVu Sans Mono")
474
+ assert font is not None
475
+ bbox = font.getbbox("M")
476
+ assert bbox is not None
477
+
478
+
228
479
  class TestFlowchartGeneratorInternalMethods:
229
480
  """Tests for FlowchartGenerator internal methods."""
230
481
 
@@ -622,7 +622,7 @@ wheels = [
622
622
 
623
623
  [[package]]
624
624
  name = "retroflow"
625
- version = "0.3.0"
625
+ version = "0.4.1"
626
626
  source = { editable = "." }
627
627
  dependencies = [
628
628
  { name = "networkx", version = "3.2.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.10'" },
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes