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
|
import datetime
import math
import traceback
from typing import Any
from PIL import Image, ImageDraw, ImageFont, PngImagePlugin
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk # type: ignore
# -------------------- Global Variables -------------------- #
grid_width: int = 10
grid_height: int = 10
side_length: float = 30.0
line_color: tuple[int, int, int, int] = (192, 192, 192, 255)
text_color: tuple[int, int, int, int] = (0, 0, 0, 255)
line_thickness: int = 2
output_filename: str = "hex_grid"
default_orientation: str = "pointy"
default_font_path: str = "arial.ttf"
default_font_size: int = 12
# -------------------- Utility Functions -------------------- #
def calculate_pointy_top_hex_points(side: float) -> list[tuple[float, float]]:
"""Calculate the vertices of a pointy-top hexagon relative to center (0,0)."""
return [
(side * math.cos(math.radians(angle)), side * math.sin(math.radians(angle)))
for angle in [30, 90, 150, 210, 270, 330]
]
def calculate_flat_top_hex_points(side: float) -> list[tuple[float, float]]:
"""Calculate the vertices of a flat-top hexagon relative to center (0,0)."""
return [
(side * math.cos(math.radians(angle)), side * math.sin(math.radians(angle)))
for angle in [0, 60, 120, 180, 240, 300]
]
def generate_grid(
g_width: int,
g_height: int,
s_length: float,
l_color: tuple[int, int, int, int],
t_color: tuple[int, int, int, int],
l_thickness: int,
orientation: str,
draw_coords: bool = True,
) -> Image.Image:
"""Generate a hexagonal grid image."""
hex_points: list[tuple[float, float]]
x_spacing: float
y_spacing: float
if orientation == default_orientation:
hex_points = calculate_pointy_top_hex_points(s_length)
x_spacing = 1.5 * s_length
y_spacing = math.sqrt(3) * s_length
elif orientation == "flat":
hex_points = calculate_flat_top_hex_points(s_length)
x_spacing = math.sqrt(3) * s_length
y_spacing = 1.5 * s_length
else:
raise ValueError("Invalid orientation. Choose 'pointy' or 'flat'.")
margin: int = int(s_length)
image_width: int = int(
(g_width * x_spacing)
+ (0.5 * x_spacing if orientation == "flat" else 0)
+ 2 * margin
)
image_height: int = int(
(g_height * y_spacing)
+ (0.5 * y_spacing if orientation == default_orientation else 0)
+ 2 * margin
)
img: Image.Image = Image.new(
"RGBA", (image_width, image_height), (255, 255, 255, 0)
)
draw: Any = ImageDraw.Draw(img)
for row in range(g_height):
for col in range(g_width):
center_x: float = col * x_spacing + margin
center_y: float = row * y_spacing + margin
if orientation == default_orientation and col % 2 == 1:
center_y += y_spacing / 2
elif orientation == "flat" and row % 2 == 1:
center_x += x_spacing / 2
hex_coords: list[tuple[float, float]] = [
(x + center_x, y + center_y) for x, y in hex_points
]
draw.polygon(hex_coords, outline=l_color, width=l_thickness)
if draw_coords:
draw_text(
draw,
f"{col},{row}",
(center_x, center_y),
t_color,
default_font_size,
)
return img
def draw_text(
draw: Any,
text: str,
position: tuple[float, float],
color: tuple[int, int, int, int],
font_size: int,
) -> None:
"""Draw text centered at a given position."""
font: ImageFont.FreeTypeFont | ImageFont.ImageFont
try:
font = ImageFont.truetype(default_font_path, size=font_size)
except IOError:
print(
f"Avertissement : Police '{default_font_path}'"
" non trouvée, utilisation de la police par défaut."
)
font = ImageFont.load_default()
draw.text(position, text, fill=color, font=font, anchor="mm")
def save_image_with_metadata(
image: Image.Image, filename: str, metadata_dict: dict[str, Any]
) -> str:
"""Save the generated grid with metadata from a dictionary."""
png_info = PngImagePlugin.PngInfo()
for key, value in metadata_dict.items():
png_info.add_text(str(key), str(value))
if not filename.lower().endswith(".png"):
filename += ".png"
try:
image.save(filename, "PNG", pnginfo=png_info)
return f"Grid saved as {filename}"
except Exception as e:
raise IOError(f"Failed to save image {filename}: {e}") from e
# -------------------- GTK Interface Functions -------------------- #
def on_generate_clicked(_button: Any | None) -> None:
"""Generate the grid when the button is clicked."""
try:
current_grid_width: int = int(entry_grid_width.get_text())
current_grid_height: int = int(entry_grid_height.get_text())
current_side_length: float = float(entry_side_length.get_text())
current_output_filename: str = entry_output_filename.get_text()
current_orientation: str = default_orientation if radio_pointy_top.get_active() else "flat"
current_line_color: tuple[int, int, int, int] = line_color
current_text_color: tuple[int, int, int, int] = text_color
current_line_thickness: int = line_thickness
if (
current_grid_width <= 0
or current_grid_height <= 0
or current_side_length <= 0
):
raise ValueError("Dimensions and side length must be positive.")
if not current_output_filename:
raise ValueError("Output filename cannot be empty.")
img: Image.Image = generate_grid(
g_width=current_grid_width,
g_height=current_grid_height,
s_length=current_side_length,
l_color=current_line_color,
t_color=current_text_color,
l_thickness=current_line_thickness,
orientation=current_orientation,
draw_coords=True,
)
metadata: dict[str, Any] = {
"grid_width": current_grid_width,
"grid_height": current_grid_height,
"side_length": current_side_length,
"line_color": str(current_line_color),
"text_color": str(current_text_color),
"line_thickness": current_line_thickness,
"orientation": current_orientation,
"generation_date": datetime.datetime.now().isoformat(),
}
success_message: str = save_image_with_metadata(
img, current_output_filename, metadata
)
dialog_success(success_message)
except ValueError as ve:
dialog_error(f"Invalid Input: {ve}")
except IOError as ioe:
dialog_error(f"File Error: {ioe}")
except Exception as e: # pylint: disable=broad-exception-caught
dialog_error(f"An unexpected error occurred: {e}")
traceback.print_exc()
def dialog_success(message: str) -> None:
"""Display a success message dialog."""
dialog = Gtk.MessageDialog(
transient_for=window,
modal=True,
message_type=Gtk.MessageType.INFO,
buttons=Gtk.ButtonsType.OK,
text="Success",
secondary_text=message,
)
dialog.run() # type: ignore
dialog.destroy()
def dialog_error(message: str) -> None:
"""Display an error message dialog."""
dialog = Gtk.MessageDialog(
transient_for=window,
modal=True,
message_type=Gtk.MessageType.ERROR,
buttons=Gtk.ButtonsType.OK,
text="Error",
secondary_text=str(message),
)
dialog.run() # type: ignore
dialog.destroy()
# -------------------- Main GTK Window Setup -------------------- #
window = Gtk.Window(title="Hexagonal Grid Generator")
window.set_border_width(10)
window.set_default_size(400, 350)
window.connect("destroy", Gtk.main_quit)
vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
window.add(vbox)
grid_layout = Gtk.Grid(column_spacing=10, row_spacing=5)
vbox.pack_start(grid_layout, True, True, 0)
row_index: int = 0
# --- Widgets ---
label_grid_width = Gtk.Label(label="Grid Width:", xalign=0)
entry_grid_width = Gtk.Entry()
entry_grid_width.set_text(str(grid_width))
grid_layout.attach(label_grid_width, 0, row_index, 1, 1)
grid_layout.attach(entry_grid_width, 1, row_index, 1, 1)
row_index += 1
label_grid_height = Gtk.Label(label="Grid Height:", xalign=0)
entry_grid_height = Gtk.Entry()
entry_grid_height.set_text(str(grid_height))
grid_layout.attach(label_grid_height, 0, row_index, 1, 1)
grid_layout.attach(entry_grid_height, 1, row_index, 1, 1)
row_index += 1
label_side_length = Gtk.Label(label="Side Length:", xalign=0)
entry_side_length = Gtk.Entry()
entry_side_length.set_text(str(side_length))
grid_layout.attach(label_side_length, 0, row_index, 1, 1)
grid_layout.attach(entry_side_length, 1, row_index, 1, 1)
row_index += 1
label_output_filename = Gtk.Label(label="Output Filename:", xalign=0)
entry_output_filename = Gtk.Entry()
entry_output_filename.set_text(output_filename)
grid_layout.attach(label_output_filename, 0, row_index, 1, 1)
grid_layout.attach(entry_output_filename, 1, row_index, 1, 1)
row_index += 1
label_orientation = Gtk.Label(label="Orientation:", xalign=0)
radio_pointy_top = Gtk.RadioButton.new_with_label_from_widget(None, "Pointy Top")
radio_flat_top = Gtk.RadioButton.new_with_label_from_widget(
radio_pointy_top, "Flat Top"
)
radio_flat_top.set_active(True)
hbox_orientation = Gtk.Box(spacing=6)
hbox_orientation.pack_start(radio_pointy_top, False, False, 0)
hbox_orientation.pack_start(radio_flat_top, False, False, 0)
grid_layout.attach(label_orientation, 0, row_index, 1, 1)
grid_layout.attach(hbox_orientation, 1, row_index, 1, 1)
row_index += 1
button_box = Gtk.Box(spacing=10)
vbox.pack_start(button_box, False, False, 0)
generate_button = Gtk.Button(label="Generate")
generate_button.connect("clicked", on_generate_clicked)
button_box.pack_start(generate_button, True, True, 0)
close_button = Gtk.Button(label="Close")
close_button.connect("clicked", lambda _: Gtk.main_quit()) # type: ignore
button_box.pack_start(close_button, True, True, 0)
window.show_all()
Gtk.main() |
Partager