You seem to be losing context of the code we had, here is the full code for all the files we are working with so you can update all of them while still including the code that was in them for all the other functionality that is functional and doesn't need modifications: #main.py:"import sys
import json
from PyQt6.QtWidgets import (
QApplication,
QMainWindow,
QVBoxLayout,
QSplitter,
QWidget,
QPushButton,
QTabWidget,
QMessageBox,
QListWidget
)
from PyQt6.QtGui import QFontDatabase, QFont
from PyQt6.QtCore import Qt
from room_designer import RoomDesigner
from settings_gui import SettingsWindow
from room_designer_ui import RoomDesignerUI
from performance_window import PerformanceWindow
from placement_generator import PlacementGenerator
from logger import logger
from config import SETTINGS_FILE, DEFAULT_SETTINGS, MESSAGES # Language and settings config
class MainWindow(QMainWindow):
def init(self):
super().init()
# Window Configuration
self.setWindowTitle("OptiPlace: Optimal Object Placement")
self.setGeometry(100, 100, 1200, 800)
# Load Custom Font
self.load_custom_font()
# Initialize Main Widget and Layout
self.central_widget = QWidget(self)
self.setCentralWidget(self.central_widget)
self.main_layout = QVBoxLayout(self.central_widget)
# Tabs for the application
self.tabs = QTabWidget()
self.main_layout.addWidget(self.tabs)
# Settings
self.settings = self.load_settings()
# Initialize the tabs and subcomponents
self.init_room_designer_tab()
self.init_performance_tab()
self.init_settings_tab()
# Placement Generator
self.placement_generator = PlacementGenerator(model_path=self.settings.get("model_path"))
self.placement_generator.finished.connect(self.show_suggestions)
self.placement_generator.error.connect(self.handle_error)
# Apply Saved Settings (Themes, Language, etc.)
self.load_and_apply_settings()
def load_custom_font(self):
"""Load a custom font into the application."""
custom_font_path = "resources/Nvidia-font.ttf"
font_id = QFontDatabase.addApplicationFont(custom_font_path)
if font_id == -1:
logger.error(f"Failed to load custom font: {custom_font_path}")
else:
font_families = QFontDatabase.applicationFontFamilies(font_id)
if font_families:
font = QFont(font_families[0]) # Use the first family
self.setFont(font)
logger.info(f"Custom font applied successfully: {font_families[0]}")
def init_room_designer_tab(self):
"""Initialize the Room Designer tab."""
# Tab layout
self.room_designer_tab = QWidget()
self.room_designer_layout = QVBoxLayout(self.room_designer_tab)
# Add the RoomDesignerUI (including canvas + controls)
self.room_designer_ui = RoomDesignerUI()
self.room_designer_layout.addWidget(self.room_designer_ui)
# Add Room Designer Tab
self.tabs.addTab(self.room_designer_tab, "Room Designer")
def init_performance_tab(self):
"""Initialize the Performance tab."""
# Placeholder Performance Tab
self.performance_placeholder = QWidget()
self.performance_placeholder_layout = QVBoxLayout(self.performance_placeholder)
self.performance_placeholder_button = QPushButton("Open Performance Window")
self.performance_placeholder_button.clicked.connect(self.show_performance_window)
self.performance_placeholder_layout.addWidget(self.performance_placeholder_button)
self.tabs.addTab(self.performance_placeholder, "Performance")
def init_settings_tab(self):
"""Initialize the Settings tab."""
self.settings_tab = SettingsWindow()
self.tabs.addTab(self.settings_tab, "Settings")
def load_settings(self):
"""Load settings from the settings file or return default settings."""
try:
with open(SETTINGS_FILE, "r") as file:
return json.load(file)
except (FileNotFoundError, json.JSONDecodeError):
logger.warning("No valid settings file found or file is malformed. Applying default settings.")
return DEFAULT_SETTINGS
def load_and_apply_settings(self):
"""Load settings and apply them dynamically."""
# UI Language
self.apply_language_settings()
# Lighting Mode
lighting_mode = self.settings.get("Lighting Mode", "Dark")
if lighting_mode == "Dark":
self.apply_dark_mode()
else:
self.apply_light_mode()
# Log the applied settings
logger.info(f"Applied settings: {self.settings}")
def apply_language_settings(self):
"""Update UI text based on the selected language."""
language = self.settings.get("UI Language", "English")
logger.info(f"Applying UI language: {language}")
# Update tab labels
self.tabs.setTabText(0, MESSAGES[language]["Room Designer"])
self.tabs.setTabText(1, MESSAGES[language]["Performance"])
self.tabs.setTabText(2, MESSAGES[language]["Settings"])
# Update window title
self.setWindowTitle(MESSAGES[language]["Window Title"])
def apply_dark_mode(self):
"""Apply dark mode to the main window, excluding the RoomDesigner."""
try:
with open("resources/dark.qss", "r") as file:
stylesheet = file.read()
# Exclude RoomDesigner from the stylesheet
stylesheet += "\nRoomDesigner { background-color: #f0f0f0; }" # Or any desired background
self.setStyleSheet(stylesheet) # Apply to MainWindow
logger.info("Dark mode applied (excluding RoomDesigner).")
except FileNotFoundError:
logger.error("Dark mode stylesheet not found.")
def apply_light_mode(self):
"""Apply light mode to the main window, excluding the RoomDesigner."""
try:
with open("resources/light.qss", "r") as file:
stylesheet = file.read()
# Exclude RoomDesigner (important for grid visibility)
stylesheet += "\nRoomDesigner { background-color: #f0f0f0; }" # Or any desired background for RoomDesigner
self.setStyleSheet(stylesheet) # Apply to MainWindow
logger.info("Light mode applied (excluding RoomDesigner).")
except FileNotFoundError:
logger.error("Light mode stylesheet not found.")
def generate_suggestions(self):
"""Trigger the placement suggestion algorithm."""
walls_data = self.room_designer.get_walls_data()
try:
# Preprocess walls
usable_space = RoomDesigner.calculate_usable_space(walls_data)
# Generate grid
grid = RoomDesigner.generate_grid(usable_space, self.room_designer.grid_size)
# Define objects to place
objects = [
{"type": "TV", "size": (100, 50)},
{"type": "chair", "size": (30, 30)},
{"type": "chair", "size": (30, 30)},
{"type": "chair", "size": (30, 30)},
{"type": "console", "size": (5, 5)},
# Add more objects here...
]
# Place objects
placements = RoomDesigner.place_objects(grid, objects)
# Visualize placements
self.room_designer.show_placements(placements)
except Exception as e:
logger.error(f"Failed to generate suggestions: {e}")
QMessageBox.critical(self, "Error", f"Failed to generate suggestions: {e}")
def show_suggestions(self, placements):
"""Display placement suggestions."""
self.generate_button.setDisabled(False)
self.room_designer.show_placements(placements)
def handle_error(self, error_message):
"""Handle errors from the PlacementGenerator."""
self.generate_button.setDisabled(False)
QMessageBox.critical(self, "Error", error_message)
def show_performance_window(self):
"""Open the Performance Window."""
self.performance_window = PerformanceWindow()
self.performance_window.show()
if name == "main":
app = QApplication(sys.argv)
# Apply Base Styles (excluding RoomDesigner)
try:
with open("resources/light.qss", "r") as file:
stylesheet = file.read()
# Exclude RoomDesigner in base style to avoid override
stylesheet += "\nRoomDesigner { background-color: #f0f0f0; }"
app.setStyleSheet(stylesheet)
except FileNotFoundError:
logger.warning("Base stylesheet not found.")
window = MainWindow()
window.show()
sys.exit(app.exec())", #room_designer.py:"from PyQt6.QtWidgets import (
QGraphicsView,
QGraphicsScene,
QGraphicsLineItem,
QGraphicsPixmapItem,
QVBoxLayout,
QHBoxLayout,
QPushButton,
QSlider,
QListWidget,
QWidget,
QLabel,
QComboBox,
QSpinBox,
QMessageBox
)
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QPainter, QPen, QMouseEvent, QPixmap
from room_designer_canvas import RoomDesignerCanvas
from PyQt6.QtCore import QLineF, QFile, QRectF
from shapely.geometry import Point # For geometric computations
from logger import logger
class RoomDesigner(QWidget):
def init(self, history_log=None, parent=None):
super().init(parent)
self.history_log = history_log # Reference to QListWidget for logging actions
self.canvas = None # Custom canvas instance
# Check if layout already exists
if self.layout() is None:
self.layout = QVBoxLayout(self) # Create layout if not set
# Attributes
self.grid_visible = False # Toggle grid visibility
self.grid_size = 50 # Size of the grid
self.current_line_item = None # Currently drawn line
self.walls = [] # List to store walls as QGraphicsLineItems
self.snap_to_grid_enabled = False # Toggle snapping to grid
self.vertices = set() # Set to store unique vertices of walls
self.objects_to_place = [] # List to store objects (type and quantity) added by the user
# NEW: Action History Log (stores actions as dictionaries)
self.actions_history = []
self.current_history_index = -1 # Pointer to "current" action in history
# Main Layout and Components
self.main_layout = QVBoxLayout(self)
self.setLayout(self.main_layout)
# Graphics View and Scene
self.scene = QGraphicsScene()
self.view = QGraphicsView(self.scene)
self.view.setRenderHint(QPainter.RenderHint.Antialiasing)
self.main_layout.addWidget(self.view)
# Ensure the scene rect covers the viewport
self.view.setSceneRect(0, 0, self.view.viewport().width(), self.view.viewport().height())
# Controls for specifying objects to place
self.controls_layout = QHBoxLayout()
# Toggle Snap Button
self.snap_toggle_button = QPushButton("Snap to Grid: OFF")
self.snap_toggle_button.setCheckable(True)
self.snap_toggle_button.toggled.connect(self.toggle_snap_to_grid)
self.controls_layout.addWidget(self.snap_toggle_button)
# Dropdown for object type
self.object_type_dropdown = QComboBox()
self.object_type_dropdown.addItems(["TV", "chair", "console"])
self.controls_layout.addWidget(QLabel("Object Type:"))
self.controls_layout.addWidget(self.object_type_dropdown)
# Spin box for quantity
self.object_quantity_spinbox = QSpinBox()
self.object_quantity_spinbox.setMinimum(1)
self.object_quantity_spinbox.setMaximum(20)
self.controls_layout.addWidget(QLabel("Quantity:"))
self.controls_layout.addWidget(self.object_quantity_spinbox)
# Add Object Button
self.add_object_button = QPushButton("Add Object")
self.add_object_button.clicked.connect(self.add_object)
self.controls_layout.addWidget(self.add_object_button)
# Generate Button
self.generate_button = QPushButton("Generate Placement")
self.generate_button.clicked.connect(self.generate_placement)
self.controls_layout.addWidget(self.generate_button)
# Add controls to the main layout
self.main_layout.addLayout(self.controls_layout)
def generate_vertices(self, threshold=10.0):
"""Generate vertices for all walls. Merge nearby vertices into one vertex."""
self.vertices = set()
# Extract start and end points from all walls
for wall in self.walls:
line = wall.line()
self.vertices.add((line.x1(), line.y1()))
self.vertices.add((line.x2(), line.y2()))
# Snap vertices that are close together and snap them to grid points
snapped_vertices = set()
for vertex in self.vertices:
snapped_vertex = self.snap_to_grid(vertex) # Snap vertex to the grid
if not any(Point(snapped_vertex).distance(Point(v)) < threshold for v in snapped_vertices):
snapped_vertices.add(snapped_vertex)
self.vertices = snapped_vertices
logger.info(f"Generated {len(self.vertices)} unique vertices after snapping.")
return self.vertices
def snap_to_grid(self, point):
"""Snap a point to the closest point on the grid."""
x, y = point
snapped_x = round(x / self.grid_size) * self.grid_size
snapped_y = round(y / self.grid_size) * self.grid_size
return (snapped_x, snapped_y)
def toggle_snap_to_grid(self, enabled):
"""Toggle snapping of new line endpoints to the nearest grid point."""
self.snap_to_grid_enabled = enabled
state = "ON" if enabled else "OFF"
self.snap_toggle_button.setText(f"Snap to Grid: {state}")
logger.info(f"Snap to Grid toggled {state}.")
def set_zoom(self, value):
"""Set the zoom level based on the slider's value."""
scale_factor = value / 100.0
self.view.resetTransform()
self.view.scale(scale_factor, scale_factor)
def mousePressEvent(self, event):
"""Start drawing a line when the left mouse button is pressed."""
if event.button() == Qt.MouseButton.LeftButton:
# Get mouse position relative to the *view* (not the widget)
view_pos = event.pos() # <---- Get the position relative to the view
scene_pos = self.view.mapToScene(view_pos) # <---- Now map it correctly!
self.current_line_item = QGraphicsLineItem(QLineF(scene_pos, scene_pos))
pen = QPen(Qt.GlobalColor.black, 2)
self.current_line_item.setPen(pen)
self.scene.addItem(self.current_line_item)
self.drawing = True
# Capture mouse events for the view during line drawing
self.view.grabMouse()
def mouseMoveEvent(self, event):
if self.current_line_item and self.drawing:
end_point = self.view.mapToScene(event.pos())
start_point = self.current_line_item.line().p1()
# Determine horizontal or vertical based on larger mouse movement
if abs(end_point.x() - start_point.x()) > abs(end_point.y() - start_point.y()):
# Horizontal Line
end_point.setY(start_point.y())
else:
# Vertical Line
end_point.setX(start_point.x())
line = self.current_line_item.line()
line.setP2(end_point)
self.current_line_item.setLine(line)
def mouseReleaseEvent(self, event):
"""Finalize the line when the left mouse button is released."""
if event.button() == Qt.MouseButton.LeftButton and self.current_line_item:
self.walls.append(self.current_line_item)
self.current_line_item = None
self.drawing = False
# Release the mouse grab
self.view.releaseMouse()
def get_walls_data(self):
"""Export the walls as a list of line coordinates."""
walls_data = []
for wall in self.walls:
line = wall.line()
walls_data.append([line.x1(), line.y1(), line.x2(), line.y2()])
return walls_data
def show_placements(self, placements):
"""Display placements (e.g., icons) in the scene, resizing them to fit the grid."""
grid_size = self.grid_size # Assume `grid_size` is already defined in the class
for placement in placements:
x = placement["x"]
y = placement["y"]
resource = placement["resource"]
# Construct the file path for the icon
icon_path = f"resources/icons/{resource}.png"
# Check if the icon file exists
if not QFile.exists(icon_path):
logger.error(f"Missing icon for resource '{resource}'. Expected path: '{icon_path}'")
continue # Skip this placement if the required icon is missing
# Load the image
pixmap = QPixmap(icon_path)
if pixmap.isNull():
logger.error(f"Unable to load pixmap for resource '{resource}'. Path: '{icon_path}'")
continue # Skip this placement if the pixmap failed to load
# Resize the pixmap to fit into a single grid square
scaled_pixmap = pixmap.scaled(
grid_size, grid_size,
aspectRatioMode=Qt.AspectRatioMode.KeepAspectRatio,
transformMode=Qt.TransformationMode.SmoothTransformation
)
# Add the icon to the scene
try:
icon = QGraphicsPixmapItem(scaled_pixmap)
icon.setPos(x, y)
self.scene.addItem(icon)
logger.info(f"Successfully added '{resource}' to the scene at position ({x}, {y}).")
except Exception as e:
logger.error(f"Failed to display resource '{resource}' at position ({x}, {y}): {e}")
def align_walls(self):
"""
Snap all walls to the grid by rounding their coordinates
to the nearest multiple of grid_size.
"""
for wall in self.walls:
line = wall.line()
# Snap start and end points to the grid
x1 = round(line.x1() / self.grid_size) * self.grid_size
y1 = round(line.y1() / self.grid_size) * self.grid_size
x2 = round(line.x2() / self.grid_size) * self.grid_size
y2 = round(line.y2() / self.grid_size) * self.grid_size
# Update the line with snapped coordinates
wall.setLine(x1, y1, x2, y2)
def auto_align(self):
"""Automatically align walls after drawing."""
self.align_walls()
def toggle_grid(self):
"""Toggle the visibility of the grid."""
self.grid_visible = not self.grid_visible
self.scene.update() # Force scene redraw
def drawBackground(self, painter, rect):
"""Draw the grid on the background if grid visibility is enabled."""
if not self.grid_visible:
return # Skip drawing the grid if it is not visible
painter.setPen(QPen(Qt.GlobalColor.lightGray, 0.5))
left = int(rect.left()) - (int(rect.left()) % self.grid_size)
top = int(rect.top()) - (int(rect.top()) % self.grid_size)
# Draw vertical grid lines
for x in range(left, int(rect.right()), self.grid_size):
painter.drawLine(x, int(rect.top()), x, int(rect.bottom()))
# Draw horizontal grid lines
for y in range(top, int(rect.bottom()), self.grid_size):
painter.drawLine(int(rect.left()), y, int(rect.right()), y)
def align_objects_to_top(self):
"""Align all objects (walls) to the top edge."""
if not self.walls:
return
# Find the minimum y-coordinate of all walls
min_y = min(min(wall.line().y1(), wall.line().y2()) for wall in self.walls)
# Align all walls to this y-coordinate
for wall in self.walls:
line = wall.line()
dy = min(line.y1(), line.y2()) - min_y
# Adjust the line vertically
y1 = line.y1() - dy
y2 = line.y2() - dy
wall.setLine(line.x1(), y1, line.x2(), y2)
def align_objects_to_left(self):
"""Align all objects (walls) to the left edge."""
if not self.walls:
return
# Find the minimum x-coordinate of all walls
min_x = min(min(wall.line().x1(), wall.line().x2()) for wall in self.walls)
# Align all walls to this x-coordinate
for wall in self.walls:
line = wall.line()
dx = min(line.x1(), line.x2()) - min_x
# Adjust the line horizontally
x1 = line.x1() - dx
x2 = line.x2() - dx
wall.setLine(x1, line.y1(), x2, line.y2())
def add_to_history(self, action_name, action_data):
"""Add an action to the history log"""
# Cut off future actions if we're adding after an undo
if self.current_history_index < len(self.actions_history) - 1:
self.actions_history = self.actions_history[:self.current_history_index + 1]
# Add new action and update index
self.actions_history.append({"name": action_name, "data": action_data})
self.current_history_index += 1
# Reflect update in the GUI
self.update_history_log()
logger.info(f"Action added to history: {action_name}")
def update_history_log(self):
"""Update the QListWidget to reflect the current history."""
self.history_log.clear()
for i, action in enumerate(self.actions_history):
prefix = ">> " if i == self.current_history_index else ""
self.history_log.addItem(f"{prefix}{action['name']}")
# Update undo/redo button states (if Undo and Redo buttons are passed in or linked)
if hasattr(self, "undo_button") and hasattr(self, "redo_button"):
self.undo_button.setEnabled(self.current_history_index >= 0)
self.redo_button.setEnabled(self.current_history_index < len(self.actions_history) - 1)
def undo_action(self):
"""Undo the last action."""
if self.current_history_index < 0:
logger.warning("No action to undo.")
return
action = self.actions_history[self.current_history_index]
action_name = action["name"]
action_data = action["data"]
# Perform undo based on the action type
if action_name == "Line Drawn":
self.scene.removeItem(action_data["line"])
self.walls.remove(action_data["line"])
# Update history index
self.current_history_index -= 1
self.update_history_log()
def redo_action(self):
"""Redo the next action."""
if self.current_history_index >= len(self.actions_history) - 1:
logger.warning("No action to redo.")
return
self.current_history_index += 1
action = self.actions_history[self.current_history_index]
action_name = action["name"]
action_data = action["data"]
# Perform redo based on the action type
if action_name == "Line Drawn":
self.scene.addItem(action_data["line"])
self.walls.append(action_data["line"])
self.update_history_log()
### --- Clear All Walls --- ###
def clear_scene(self):
"""Remove all lines on the canvas and reset history."""
if QMessageBox.warning(self, "Warning", "Are you sure you want to clear all walls?",
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No) == QMessageBox.StandardButton.No:
return # User canceled the clear action
# Clear walls from the scene
for wall in self.walls:
self.scene.removeItem(wall)
self.walls.clear()
# Log the action
self.add_to_history("Clear All Walls", {"walls": []})
### --- OBJECT PLACEMENT --- ###
def add_object(self):
"""Add the selected object type and quantity to the list."""
object_type = self.object_type_dropdown.currentText()
quantity = self.object_quantity_spinbox.value()
self.objects_to_place.append({"type": object_type, "quantity": quantity})
logger.info(f"Added {quantity} {object_type}(s) to the placement list.")
def generate_placement(self):
"""Generate optimal placements based on user-defined walls and objects."""
walls_data = self.get_walls_data()
if not walls_data:
logger.warning("No walls defined. Cannot generate placement.")
return
# Preprocess walls to ensure they form a valid circuit
logger.info("Preprocessing walls to form a closed circuit.")
self.form_closed_circuit()
# Calculate usable space
usable_space = self.calculate_usable_space(walls_data)
if usable_space is None:
logger.error("Failed to calculate usable space. Cannot generate placement.")
return
# Divide usable space into grid cells
grid = self.generate_grid(usable_space)
if not grid:
logger.warning("No grid cells available for placement. Room might be too small.")
return
# Place the objects
placements = self.place_objects(grid, self.objects_to_place)
if not placements:
logger.warning("No objects could be placed. Check available space and constraints.")
return
# Visualize results
self.visualize_placements(placements)
logger.info(f"Successfully completed placement. Placed {len(placements)} objects.")
def calculate_usable_space(self, walls_data):
"""Calculate the enclosed room area based on the walls."""
from shapely.geometry import Polygon, LineString
# Convert walls into line segments
walls = [LineString([(line[0], line[1]), (line[2], line[3])]) for line in walls_data]
# Attempt to create a closed polygon from the walls
room_polygon = Polygon([point for wall in walls for point in wall.coords])
# Automatic fix: Simplify the polygon if redundant vertices exist
if not room_polygon.is_valid:
logger.error("Room polygon is invalid: Contains self-intersections or other geometry issues.")
logger.error(f"Polygon bounds: {room_polygon.bounds}")
logger.error(f"Polygon WKT before fixes: {room_polygon.wkt}")
room_polygon = room_polygon.simplify(0.001) # Simplify geometry
if not room_polygon.is_valid:
logger.error("Fix attempt failed: Polygon still invalid after simplification.")
return None
logger.info(f"Successfully calculated usable area: Bounding box {room_polygon.bounds}")
return room_polygon
def generate_grid(self, usable_space):
"""Divide the usable area into a grid."""
from shapely.geometry import box
min_x, min_y, max_x, max_y = usable_space.bounds
grid = []
# Create a grid of usable cells
for x in range(int(min_x), int(max_x), self.grid_size):
for y in range(int(min_y), int(max_y), self.grid_size):
cell = box(x, y, x + self.grid_size, y + self.grid_size)
if usable_space.contains(cell):
grid.append(cell)
return grid
def place_objects(self, grid, objects):
"""Place objects intelligently in the grid avoiding collisions."""
placements = []
placed_cells = set() # Track occupied grid cells
for obj in objects:
obj_type = obj["type"]
obj_width, obj_height = obj["size"]
quantity = obj["quantity"]
for _ in range(quantity):
# Try finding a valid cell for placement
for cell in grid:
cell_rect = QRectF(cell[0], cell[1], self.grid_size, self.grid_size)
# Skip cells already occupied
if cell_rect in placed_cells:
continue
# Ensure object fits within cell (no overlap)
fits = all(not cell_rect.intersects(other) for other in placed_cells)
if fits:
placements.append({
"type": obj_type,
"x": cell[0],
"y": cell[1],
})
placed_cells.add(cell_rect)
break
return placements
def visualize_placements(self, placements):
"""Display the placements on the canvas."""
grid_size = self.grid_size
for placement in placements:
x, y = placement["position"]
obj_type = placement["type"]
icon_path = f"resources/icons/{obj_type}.png"
# Check if the icon exists
if not QFile.exists(icon_path):
logger.error(f"Missing icon for {obj_type}. Path: {icon_path}")
continue
pixmap = QPixmap(icon_path)
scaled_pixmap = pixmap.scaled(
grid_size, grid_size,
aspectRatioMode=Qt.AspectRatioMode.KeepAspectRatio,
transformMode=Qt.TransformationMode.SmoothTransformation
)
icon = QGraphicsPixmapItem(scaled_pixmap)
icon.setPos(x, y)
self.scene.addItem(icon)
def form_closed_circuit(self):
"""
Ensure that the walls form a connected closed circuit by identifying gaps and correcting them.
Remove redundant or overlapping walls to avoid self-intersections.
"""
from shapely.geometry import Point, LineString
if not self.walls:
logger.warning("No walls present to close.")
return
logger.info("Attempting to form a closed circuit for the walls.")
# Extract wall endpoints
endpoints = []
wall_segments = [] # Track unique wall segments
for wall in self.walls:
line = wall.line()
start, end = (line.x1(), line.y1()), (line.x2(), line.y2())
endpoints += [start, end]
wall_segments.append(LineString([start, end]))
# Remove duplicate or overlapping walls
unique_walls = []
for i, wall in enumerate(wall_segments):
duplicate = False
for j, other in enumerate(unique_walls):
# If the wall geometrically equals any existing wall, skip it
if wall.equals(other):
duplicate = True
logger.warning(f"Detected duplicate wall: {wall.wkt}. Removing it.")
break
if not duplicate:
unique_walls.append(wall)
# Replace the scene's walls with the filtered ones
self.walls = []
for wall in unique_walls:
line_item = QGraphicsLineItem(QLineF(*wall.coords[0], *wall.coords[1]))
line_item.setPen(QPen(Qt.GlobalColor.black, 2))
self.scene.addItem(line_item)
self.walls.append(line_item)
# Identify unconnected points
endpoint_count = {}
for endpoint in endpoints:
endpoint_count[endpoint] = endpoint_count.get(endpoint, 0) + 1
# Find endpoints with odd connections (unconnected or dangling)
dangling_points = [pt for pt, count in endpoint_count.items() if count % 2 != 0]
if not dangling_points:
logger.info(f"All walls are connected. Total walls: {len(self.walls)}.")
return
logger.info(f"Found {len(dangling_points)} dangling points: {dangling_points}")
# Pair up dangling points and close gaps
while len(dangling_points) > 1:
start = dangling_points.pop(0)
end = dangling_points.pop(0)
# Create a line to connect the gap
new_line = QGraphicsLineItem(QLineF(*start, *end))
new_line.setPen(QPen(Qt.GlobalColor.black, 1))
self.scene.addItem(new_line)
self.walls.append(new_line)
logger.info(f"Added a new wall to close the gap: Start {start}, End {end}")
logger.info(f"After closing gaps: Total walls: {len(self.walls)}; Remaining gaps: {len(dangling_points)}")
def set_canvas(self, canvas):
"""Set a custom canvas (RoomDesignerCanvas) to handle drawing and interactions."""
if self.canvas is not None:
# Remove the existing canvas from the layout
self.layout.removeWidget(self.canvas)
self.canvas = canvas
self.layout.addWidget(self.canvas) # Add canvas to layout
def toggle_grid(self):
if self.canvas:
self.canvas.toggle_grid()",#room_designer_canvas.py:"import math
from PyQt6.QtWidgets import QWidget, QMessageBox
from PyQt6.QtGui import QPainter, QPen, QColor, QMouseEvent
from PyQt6.QtCore import Qt, QPointF, QRectF
class RoomDesignerCanvas(QWidget):
def init(self, grid_size=50, parent=None):
super().init(parent)
# Canvas settings
self.grid_size = grid_size # Grid size for snapping
self.grid_color = QColor(230, 230, 230) # Light gray for grid
self.wall_color = QColor(0, 0, 0) # Black for walls
self.snapping_point_color = QColor(0, 150, 255, 150) # Translucent blue
# Interactive drawing and editing
self.walls = [] # List of walls (each wall is a QLineF)
self.vertices = [] # List of vertices (tuples)
self.selected_vertex = None # Currently selected point for dragging
self.current_drawing_wall = None # Temporary wall segment being drawn
self.snap_threshold = 10.0 # Radius for snapping points
self.hovered_vertex = None # Currently hovered vertex
# Control interactivity states
self.grid_visible = True # Show/hide grid
self.snapping_enabled = True # Enable snapping
self.shift_pressed = False # Constrain wall angle while Shift is held for snapping
# --- PAINTING ---
def paintEvent(self, event):
"""Main painting routine."""
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
# Draw grid
if self.grid_visible:
self.draw_grid(painter)
# Draw walls
self.draw_walls(painter)
# Draw snapping points
self.draw_snapping_points(painter)
# Draw temporary wall (if drawing)
self.draw_temporary_wall(painter)
def draw_grid(self, painter):
"""Draw snapping grid."""
pen = QPen(QColor(230, 230, 230), 1, Qt.PenStyle.DotLine)
painter.setPen(pen)
for x in range(0, self.width(), self.grid_size):
painter.drawLine(x, 0, x, self.height())
for y in range(0, self.height(), self.grid_size):
painter.drawLine(0, y, self.width(), y)
def draw_walls(self, painter):
"""Draw walls."""
pen = QPen(QColor(0, 0, 0), 2)
painter.setPen(pen)
for wall in self.walls:
painter.drawLine(wall)
# Highlight hovered vertex (if any)
if self.hovered_vertex is not None:
painter.setBrush(QColor(255, 100, 100)) # Red highlight
painter.drawEllipse(QPointF(*self.hovered_vertex), 6, 6)
def toggle_grid(self):
"""Toggle the visibility of the grid."""
self.grid_visible = not self.grid_visible
self.update() # Redraw the canvas
def draw_snapping_points(self, painter):
"""Draw snapping points."""
if not self.snapping_enabled:
return
pen = QPen(Qt.NoPen)
painter.setPen(pen)
painter.setBrush(self.snapping_point_color)
for vertex in self.vertices:
painter.drawEllipse(QPointF(*vertex), 5, 5)
def draw_temporary_wall(self, painter):
"""Draw the wall currently being actively drawn."""
if self.current_drawing_wall:
pen = QPen(QColor(100, 100, 255, 150), 2, Qt.PenStyle.DashLine)
painter.setPen(pen)
painter.drawLine(self.current_drawing_wall)
# --- INTERACTIVITY ---
def mousePressEvent(self, event: QMouseEvent):
"""Start drawing or interacting with walls."""
if event.button() == Qt.MouseButton.LeftButton:
pos = event.position()
snapped_vertex = self.snap_to_vertex(pos)
if snapped_vertex:
# Start a new wall from the snapped vertex
self.current_drawing_wall = QRectF(snapped_vertex, snapped_vertex)
else:
# Freely place a new wall
self.current_drawing_wall = QRectF(pos, pos)
elif event.button() == Qt.MouseButton.RightButton:
# Remove hovered wall/vertex
self.delete_closest_vertex_or_wall(event.position())
def mouseMoveEvent(self, event: QMouseEvent):
"""Handle snapping and updating wall creation."""
pos = event.position()
self.hovered_vertex = self.snap_to_vertex(pos)
# Update current drawing wall if in drawing mode
if self.current_drawing_wall:
snapped_pos = self.snap_to_vertex(pos) or pos
# Constrain angles if Shift is pressed
if self.shift_pressed:
snapped_pos = self.constrain_to_angle(self.current_drawing_wall.p1(), snapped_pos)
self.current_drawing_wall.setP2(snapped_pos)
self.update()
def mouseReleaseEvent(self, event: QMouseEvent):
"""Finish drawing or editing walls."""
if event.button() == Qt.MouseButton.LeftButton:
if self.current_drawing_wall:
# Add the completed wall to our list
new_wall = self.current_drawing_wall
# Add unique vertices
self.add_vertex(new_wall.p1())
self.add_vertex(new_wall.p2())
self.walls.append(new_wall)
self.current_drawing_wall = None
self.update()
# --- HELPER FUNCTIONS ---
def snap_to_vertex(self, pos: QPointF):
"""Snap a point to the nearest vertex or grid."""
for vertex in self.vertices:
if math.dist(vertex, (pos.x(), pos.y())) <= self.snap_threshold:
return QPointF(*vertex)
if self.snapping_enabled:
return QPointF(
round(pos.x() / self.grid_size) * self.grid_size,
round(pos.y() / self.grid_size) * self.grid_size
)
return None
def delete_closest_vertex_or_wall(self, pos: QPointF):
"""Delete a wall or vertex near the given position."""
for wall in self.walls:
if wall.contains(pos): # Check overlap
self.walls.remove(wall)
self.update()
return
for vertex in self.vertices:
if math.dist(vertex, (pos.x(), pos.y())) <= self.snap_threshold:
self.vertices.remove(vertex)
self.update()
return
def constrain_to_angle(self, p1, p2):
"""Snap a line to specific angles."""
dx, dy = p2.x() - p1.x(), p2.y() - p1.y()
angle = round(math.atan2(dy, dx) / (math.pi / 4)) * (math.pi / 4) # Snap to 45-degree increments
length = math.hypot(dx, dy)
return QPointF(
p1.x() + length * math.cos(angle),
p1.y() + length * math.sin(angle)
)
def add_vertex(self, pos: QPointF):
"""Add vertex to the set, ensuring uniqueness."""
vertex = (pos.x(), pos.y())
if vertex not in self.vertices:
self.vertices.append(vertex)",#room_designer_ui.py:"from PyQt6.QtWidgets import (
QWidget,
QVBoxLayout,
QSplitter,
QPushButton,
QListWidget,
QComboBox,
QLabel,
QSpinBox,
)
from PyQt6.QtCore import Qt
from room_designer import RoomDesigner
from room_designer_canvas import RoomDesignerCanvas
class RoomDesignerUI(QWidget):
def init(self, parent=None):
super().init(parent)
# Main layout for the Room Designer UI (splitter and controls)
self.main_layout = QVBoxLayout(self)
self.setLayout(self.main_layout)
# Splitter to separate Canvas (left) and Controls (right)
self.splitter = QSplitter(Qt.Orientation.Horizontal)
# --- History Log ---
self.history_log = QListWidget() # Initialize FIRST to avoid AttributeError
# --- Left: Room Designer Canvas ---
# Integrate RoomDesigner and RoomDesignerCanvas
self.room_designer = RoomDesigner(history_log=self.history_log)
self.room_designer.set_canvas(RoomDesignerCanvas(grid_size=50)) # Set custom canvas
self.splitter.addWidget(self.room_designer) # Add higher-level RoomDesigner logic
# --- Right: Control Panel ---
self.control_panel = QWidget()
self.control_layout = QVBoxLayout(self.control_panel)
# Add buttons to the control panel
self.setup_controls()
# Add control panel to splitter
self.splitter.addWidget(self.control_panel)
# Set splitter stretch factors (after adding widgets)
self.splitter.setStretchFactor(0, 3) # Left (canvas): 3 parts
self.splitter.setStretchFactor(1, 1) # Right (controls): 1 part
# Add the splitter to the main layout
self.main_layout.addWidget(self.splitter)
def setup_controls(self):
"""Set up the control buttons and link to the RoomDesigner or its canvas."""
# Auto-Align Button
self.auto_align_button = QPushButton("Auto-Align")
self.auto_align_button.clicked.connect(self.room_designer.auto_align) # Uses RoomDesigner logic
# Fix Walls Button
self.fix_walls_button = QPushButton("Fix Walls")
self.fix_walls_button.clicked.connect(self.room_designer.form_closed_circuit) # RoomDesigner logic
# Show/Hide Grid Button
self.grid_button = QPushButton("Show/Hide Grid")
self.grid_button.clicked.connect(self.room_designer.canvas.toggle_grid) # Canvas interaction
# Align to Top Button
self.align_top_button = QPushButton("Align to Top")
self.align_top_button.clicked.connect(self.room_designer.align_objects_to_top) # RoomDesigner logic
# Align to Left Button
self.align_left_button = QPushButton("Align to Left")
self.align_left_button.clicked.connect(self.room_designer.align_objects_to_left) # RoomDesigner logic
# Clear Walls Button
self.clear_button = QPushButton("Clear All Walls")
self.clear_button.clicked.connect(self.room_designer.clear_scene) # RoomDesigner logic
# Undo and Redo Buttons
self.undo_button = QPushButton("Undo")
self.undo_button.clicked.connect(self.room_designer.undo_action) # RoomDesigner history
self.redo_button = QPushButton("Redo")
self.redo_button.clicked.connect(self.room_designer.redo_action) # RoomDesigner history
self.undo_button.setToolTip("Undo the last action")
self.redo_button.setToolTip("Redo the previously undone action")
# Add controls to control layout
self.control_layout.addWidget(self.auto_align_button)
self.control_layout.addWidget(self.fix_walls_button)
self.control_layout.addWidget(self.grid_button)
self.control_layout.addWidget(self.align_top_button)
self.control_layout.addWidget(self.align_left_button)
self.control_layout.addWidget(self.clear_button)
self.control_layout.addWidget(self.undo_button)
self.control_layout.addWidget(self.redo_button)
self.control_layout.addWidget(self.history_log)
self.control_layout.addStretch(1)"