picpro-gui 0.1.1__py3-none-any.whl

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.
picpro_gui/__init__.py ADDED
@@ -0,0 +1,2 @@
1
+ """Optional Qt interface to the picpro application service."""
2
+ __version__ = '0.1.1'
picpro_gui/__main__.py ADDED
@@ -0,0 +1,39 @@
1
+ """Desktop entry point; Qt is imported only when the GUI is launched."""
2
+
3
+ import argparse
4
+ import sys
5
+ from pathlib import Path
6
+
7
+
8
+ def main() -> int:
9
+ parser = argparse.ArgumentParser(prog='picpro-gui', description='PicPro desktop programmer')
10
+ parser.add_argument('project', nargs='?', type=Path, help='Project file to open')
11
+ arguments = parser.parse_args()
12
+ try:
13
+ from PyQt6.QtCore import QSettings # noqa: PLC0415 - load Qt only when launching
14
+ from PyQt6.QtWidgets import QApplication, QMessageBox # noqa: PLC0415 - load Qt only when launching
15
+
16
+ from picpro_gui.window import PicProGUI # noqa: PLC0415 - keep Qt out of core imports
17
+ except ModuleNotFoundError as error:
18
+ if error.name is None or not error.name.startswith('PyQt6'):
19
+ raise
20
+ sys.stderr.write('PyQt6 is required. Reinstall picpro-gui with your package manager.\n')
21
+ return 1
22
+ app = QApplication(sys.argv)
23
+ app.setApplicationName('PicPro')
24
+ app.setOrganizationName('PicPro')
25
+ try:
26
+ window = PicProGUI(settings=QSettings())
27
+ except Exception as error: # noqa: BLE001 - report startup failures before the event loop starts
28
+ QMessageBox.critical(None, 'Unable to start PicPro', str(error))
29
+ return 1
30
+ if arguments.project is not None:
31
+ window.load_project(arguments.project)
32
+ else:
33
+ window.restore_last_project()
34
+ window.show()
35
+ return app.exec()
36
+
37
+
38
+ if __name__ == '__main__':
39
+ sys.exit(main())
picpro_gui/project.py ADDED
@@ -0,0 +1,118 @@
1
+ """Portable GUI project files, independent of Qt."""
2
+
3
+ import os
4
+ import tempfile
5
+ from dataclasses import dataclass, field
6
+ from pathlib import Path
7
+ from typing import ClassVar
8
+
9
+ import yaml
10
+ from picpro.PicPro import ChipRepository, Target
11
+
12
+
13
+ class ProjectError(ValueError):
14
+ """An invalid or unsupported project file or configuration."""
15
+
16
+
17
+ @dataclass
18
+ class Project:
19
+ chip: str = '12f675'
20
+ port: str = ''
21
+ firmware: Path | None = None
22
+ icsp: bool = False
23
+ pic_id: str | None = None
24
+ fuses: dict[str, str] = field(default_factory=dict)
25
+
26
+ SCHEMA_VERSION: ClassVar[int] = 1
27
+
28
+ @property
29
+ def target(self) -> Target:
30
+ return Target(self.port, self.chip, self.icsp)
31
+
32
+ def validate(self, chips: ChipRepository) -> None:
33
+ try:
34
+ chip = chips.get_chip(self.chip)
35
+ except KeyError as error:
36
+ msg = f'Unknown PIC chip: {self.chip}'
37
+ raise ProjectError(msg) from error
38
+ chip.encode_fuse_data(self.fuses)
39
+ if chip.icsp_only and not self.icsp:
40
+ msg = f'{self.chip} requires ICSP mode.'
41
+ raise ProjectError(msg)
42
+ if self.pic_id:
43
+ try:
44
+ value = bytes.fromhex(self.pic_id)
45
+ except ValueError as error:
46
+ msg = 'PIC ID must contain hexadecimal byte pairs.'
47
+ raise ProjectError(msg) from error
48
+ expected_bytes = 8 if chip.core_bits == 16 else 4
49
+ if len(value) != expected_bytes:
50
+ msg = f'PIC ID must be exactly {expected_bytes} bytes for {self.chip}.'
51
+ raise ProjectError(msg)
52
+
53
+ @classmethod
54
+ def load(cls, path: Path, chips: ChipRepository) -> 'Project':
55
+ path = path.resolve()
56
+ try:
57
+ data = yaml.safe_load(path.read_text(encoding='utf-8'))
58
+ except yaml.YAMLError as error:
59
+ msg = f'Invalid project YAML: {error}'
60
+ raise ProjectError(msg) from error
61
+ if not isinstance(data, dict):
62
+ msg = 'The project must contain a YAML mapping.'
63
+ raise ProjectError(msg)
64
+ version = data.get('schema_version')
65
+ if type(version) is not int or version != cls.SCHEMA_VERSION:
66
+ msg = f'Unsupported project schema version: {version!r}'
67
+ raise ProjectError(msg)
68
+ # Older project files saved the memory choice for the next read.
69
+ unknown = data.keys() - {'schema_version', 'chip', 'port', 'firmware', 'icsp', 'pic_id', 'fuses', 'memory'}
70
+ if unknown:
71
+ msg = f'Unknown project fields: {", ".join(str(key) for key in unknown)}'
72
+ raise ProjectError(msg)
73
+ for name, default in [('chip', None), ('port', '')]:
74
+ if not isinstance(data.get(name, default), str):
75
+ msg = f'{name} must be a string.'
76
+ raise ProjectError(msg)
77
+ for name in ['firmware', 'pic_id']:
78
+ if data.get(name) is not None and not isinstance(data[name], str):
79
+ msg = f'{name} must be a string or null.'
80
+ raise ProjectError(msg)
81
+ if not isinstance(data.get('icsp', False), bool):
82
+ msg = 'icsp must be a boolean.'
83
+ raise ProjectError(msg)
84
+ fuses = data.get('fuses', {})
85
+ if not isinstance(fuses, dict) or any(not isinstance(k, str) or not isinstance(v, str) for k, v in fuses.items()):
86
+ msg = 'fuses must map fuse names to setting names.'
87
+ raise ProjectError(msg)
88
+ firmware = Path(data['firmware']) if data.get('firmware') else None
89
+ if firmware is not None:
90
+ firmware = (path.parent / firmware).resolve()
91
+ project = cls(chip=data['chip'], port=data.get('port', ''), firmware=firmware,
92
+ icsp=data.get('icsp', False), pic_id=data.get('pic_id'), fuses=dict(fuses))
93
+ project.validate(chips)
94
+ return project
95
+
96
+ def save(self, path: Path, chips: ChipRepository) -> None:
97
+ self.validate(chips)
98
+ path = path.resolve()
99
+ firmware = None
100
+ if self.firmware is not None:
101
+ try:
102
+ firmware = Path(os.path.relpath(self.firmware.resolve(), path.parent)).as_posix()
103
+ except ValueError: # Paths on different Windows drives cannot be relative.
104
+ firmware = str(self.firmware.resolve())
105
+ data = {'schema_version': self.SCHEMA_VERSION, 'chip': self.chip, 'port': self.port,
106
+ 'firmware': firmware, 'icsp': self.icsp, 'pic_id': self.pic_id,
107
+ 'fuses': dict(self.fuses)}
108
+ temporary = None
109
+ try:
110
+ with tempfile.NamedTemporaryFile(mode='w', encoding='utf-8', dir=path.parent, prefix=f'.{path.name}.', delete=False) as file:
111
+ temporary = Path(file.name)
112
+ yaml.safe_dump(data, file, sort_keys=False)
113
+ file.flush()
114
+ os.fsync(file.fileno())
115
+ temporary.replace(path)
116
+ finally:
117
+ if temporary is not None:
118
+ temporary.unlink(missing_ok=True)
picpro_gui/socket.py ADDED
@@ -0,0 +1,135 @@
1
+ """Socket and chip placement preview, retained from the original GUI sketch."""
2
+
3
+ from PyQt6.QtCore import Qt
4
+ from PyQt6.QtGui import QBrush, QFont, QResizeEvent
5
+ from PyQt6.QtWidgets import QGraphicsEllipseItem, QGraphicsRectItem, QGraphicsScene, QGraphicsTextItem, QGraphicsView, QWidget
6
+
7
+
8
+ class SocketPreviewWidget(QGraphicsView):
9
+ def __init__(self, chip_pins: int = 14, socket_position: int = 1, parent: QWidget | None = None) -> None:
10
+ super().__init__(parent)
11
+ self.dpi = self.logicalDpiX()
12
+ self.chip_pins: int | None = chip_pins
13
+ self.socket_position = socket_position
14
+ self._scene = QGraphicsScene(self)
15
+ self.setScene(self._scene)
16
+ self.set_chip(chip_pins, socket_position)
17
+
18
+ def set_chip(self, chip_pins: int | None, socket_position: int = 1) -> None:
19
+ if chip_pins is not None and (chip_pins not in (8, 14, 18, 28, 40) or not 1 <= socket_position <= 21 - chip_pins // 2):
20
+ msg = 'Chip pin count or socket position is invalid.'
21
+ raise ValueError(msg)
22
+ self.chip_pins = chip_pins
23
+ self.socket_position = socket_position
24
+ self._scene.clear()
25
+ self.draw_socket()
26
+ if chip_pins is not None:
27
+ self.draw_chip()
28
+ self.fit_socket_to_view()
29
+
30
+ def mm_to_px(self, mm: float) -> float:
31
+ return (mm / 25.4) * self.dpi
32
+
33
+ def resizeEvent(self, event: QResizeEvent | None) -> None: # noqa: N802 - Qt virtual method
34
+ super().resizeEvent(event)
35
+ self.fit_socket_to_view()
36
+
37
+ def fit_socket_to_view(self) -> None:
38
+ items_bbox = self._scene.itemsBoundingRect()
39
+ padding_ratio = 0.1
40
+ pad_w = items_bbox.width() * padding_ratio
41
+ pad_h = items_bbox.height() * padding_ratio
42
+ padded_bbox = items_bbox.adjusted(-pad_w, -pad_h, pad_w, pad_h)
43
+ self.fitInView(padded_bbox, Qt.AspectRatioMode.KeepAspectRatio)
44
+
45
+ def draw_socket(self) -> None:
46
+ start_x = 50
47
+ start_y = 20
48
+
49
+ number_of_pins_in_row = 20
50
+ number_of_rows = 2
51
+ pin_height = self.mm_to_px(1.3)
52
+ pin_width = self.mm_to_px(7)
53
+ vertical_spacing = self.mm_to_px(1.1)
54
+ horizontal_spacing = self.mm_to_px(4)
55
+ horizontal_padding = self.mm_to_px(2.1)
56
+ bottom_padding = self.mm_to_px(6.5)
57
+ top_padding = self.mm_to_px(8.5)
58
+ leaver_length = self.mm_to_px(17)
59
+ leaver_thickens = self.mm_to_px(1.5)
60
+ leaver_top_offset = self.mm_to_px(11)
61
+
62
+ # Drawn socket body
63
+ socket_width = pin_width * number_of_rows + horizontal_spacing + (horizontal_padding * 2)
64
+ socket_height = (pin_height + vertical_spacing) * number_of_pins_in_row - vertical_spacing
65
+ socket = QGraphicsRectItem(start_x, start_y+leaver_top_offset, socket_width, socket_height + top_padding + bottom_padding)
66
+ socket.setBrush(QBrush(Qt.GlobalColor.darkGreen))
67
+ self._scene.addItem(socket)
68
+
69
+ # Drawn leaver
70
+ leaver = QGraphicsRectItem(start_x, start_y, leaver_thickens, leaver_length)
71
+ leaver.setBrush(QBrush(Qt.GlobalColor.lightGray))
72
+ self._scene.addItem(leaver)
73
+
74
+ for i in range(number_of_pins_in_row):
75
+ for col in range(number_of_rows):
76
+ pin_num = i + 1 if col == 0 else 40 - i
77
+ x = start_x + col * (pin_width + horizontal_spacing) + horizontal_padding
78
+ y = start_y + top_padding + leaver_top_offset + i * (pin_height + vertical_spacing)
79
+ pin = QGraphicsRectItem(x, y, pin_width, pin_height)
80
+ pin.setBrush(QBrush(Qt.GlobalColor.lightGray))
81
+ self._scene.addItem(pin)
82
+
83
+ label = QGraphicsTextItem(str(pin_num))
84
+ font = QFont()
85
+ font.setPointSize(round(self.mm_to_px(1.8))) # Set desired point size
86
+ label.setFont(font)
87
+ text_rect = label.boundingRect()
88
+ x_pos = x - text_rect.width() - horizontal_padding if col == 0 else x + pin_width + horizontal_padding
89
+ label.setPos(x_pos, y + (pin_height - text_rect.height()) / 2)
90
+ self._scene.addItem(label)
91
+
92
+ # After setting up your scene:
93
+ self.fit_socket_to_view()
94
+
95
+ def draw_chip(self) -> None:
96
+ number_of_rows = 2
97
+ pin_width = self.mm_to_px(7)
98
+ pin_height = self.mm_to_px(1.3)
99
+ horizontal_spacing = self.mm_to_px(4)
100
+ horizontal_padding = self.mm_to_px(2.1)
101
+ vertical_spacing = self.mm_to_px(1.1)
102
+ leaver_top_offset = self.mm_to_px(11)
103
+ top_padding = self.mm_to_px(8.5)
104
+ chip_key_size = self.mm_to_px(1)
105
+ chip_key_padding = self.mm_to_px(0.5)
106
+ socket_width = pin_width * number_of_rows + horizontal_spacing + (horizontal_padding * 2)
107
+
108
+ if self.chip_pins is None:
109
+ return
110
+ pins_per_side = self.chip_pins // 2
111
+ chip_height = (pin_height + vertical_spacing) * pins_per_side
112
+
113
+ chip_width = self.mm_to_px(16 if self.chip_pins == 40 else 6.15)
114
+
115
+ start_pin = self.socket_position
116
+
117
+ start_x = 50
118
+ start_y = 20
119
+
120
+ # Calculate vertical offset based on socket pin alignment
121
+ # We offset by vertical_spacing / 2 to top since chip_height have 1* vertical_spacing more and this is a good
122
+ # way to render chip body overlying pins
123
+ chip_offset = ((start_pin - 1) % 20) * (pin_height + vertical_spacing) + leaver_top_offset + top_padding - vertical_spacing / 2
124
+
125
+ # Set chip on center of socket in X dimension
126
+ x_position = start_x + (socket_width / 2) - (chip_width / 2)
127
+
128
+ chip_rect = QGraphicsRectItem(x_position, start_y + chip_offset, chip_width, chip_height)
129
+ chip_rect.setBrush(QBrush(Qt.GlobalColor.black))
130
+ self._scene.addItem(chip_rect)
131
+
132
+ # Render chip pin 1 key
133
+ chip_key = QGraphicsEllipseItem(x_position + chip_key_padding, start_y + chip_offset + chip_key_padding, chip_key_size, chip_key_size)
134
+ chip_key.setBrush(QBrush(Qt.GlobalColor.gray))
135
+ self._scene.addItem(chip_key)