|
| 1 | +from pathlib import Path |
| 2 | +from qtpy import QtWidgets, QtCore, QtGui |
| 3 | + |
| 4 | +import tttrlib |
| 5 | + |
| 6 | +import chisurf.gui.decorators |
| 7 | +import chisurf.settings |
| 8 | + |
| 9 | +VERBOSE = False |
| 10 | + |
| 11 | +def enable_file_drop_for_open(line_edit: QtWidgets.QLineEdit, open_func): |
| 12 | + """ |
| 13 | + Enable dropping a *single file* onto a QLineEdit. |
| 14 | + Calls `open_func(path_str)` after dropping the file. |
| 15 | + """ |
| 16 | + line_edit.setAcceptDrops(True) |
| 17 | + |
| 18 | + def dragEnterEvent(event: QtGui.QDragEnterEvent): |
| 19 | + if event.mimeData().hasUrls(): |
| 20 | + urls = event.mimeData().urls() |
| 21 | + # Accept only if exactly one URL and it is an existing file |
| 22 | + if len(urls) == 1: |
| 23 | + if Path(urls[0].toLocalFile()).is_file(): |
| 24 | + event.acceptProposedAction() |
| 25 | + return |
| 26 | + event.ignore() |
| 27 | + |
| 28 | + def dropEvent(event: QtGui.QDropEvent): |
| 29 | + if event.mimeData().hasUrls(): |
| 30 | + path_str = event.mimeData().urls()[0].toLocalFile() |
| 31 | + if Path(path_str).is_file(): |
| 32 | + event.acceptProposedAction() |
| 33 | + open_func(path_str) # Call the function to actually open the file |
| 34 | + return |
| 35 | + event.ignore() |
| 36 | + |
| 37 | + # Monkey-patch the lineEdit's events: |
| 38 | + line_edit.dragEnterEvent = dragEnterEvent |
| 39 | + line_edit.dropEvent = dropEvent |
| 40 | + |
| 41 | + |
| 42 | +def enable_folder_drop(line_edit: QtWidgets.QLineEdit): |
| 43 | + """ |
| 44 | + Enable dropping a *single folder* onto a QLineEdit. |
| 45 | + Sets the lineEdit text to the dropped folder path. |
| 46 | + """ |
| 47 | + line_edit.setAcceptDrops(True) |
| 48 | + |
| 49 | + def dragEnterEvent(event: QtGui.QDragEnterEvent): |
| 50 | + if event.mimeData().hasUrls(): |
| 51 | + urls = event.mimeData().urls() |
| 52 | + # Accept only if exactly one URL and it is an existing directory |
| 53 | + if len(urls) == 1: |
| 54 | + if Path(urls[0].toLocalFile()).is_dir(): |
| 55 | + event.acceptProposedAction() |
| 56 | + return |
| 57 | + event.ignore() |
| 58 | + |
| 59 | + def dropEvent(event: QtGui.QDropEvent): |
| 60 | + if event.mimeData().hasUrls(): |
| 61 | + folder_str = event.mimeData().urls()[0].toLocalFile() |
| 62 | + if Path(folder_str).is_dir(): |
| 63 | + event.acceptProposedAction() |
| 64 | + line_edit.setText(folder_str) |
| 65 | + return |
| 66 | + event.ignore() |
| 67 | + |
| 68 | + # Monkey-patch the lineEdit's events: |
| 69 | + line_edit.dragEnterEvent = dragEnterEvent |
| 70 | + line_edit.dropEvent = dropEvent |
| 71 | + |
| 72 | + |
| 73 | + |
| 74 | +class PTUSplitter(QtWidgets.QWidget): |
| 75 | + |
| 76 | + @chisurf.gui.decorators.init_with_ui("ptu_splitter/wizard.ui", |
| 77 | + path=chisurf.settings.plugin_path) |
| 78 | + def __init__(self, *args, **kwargs): |
| 79 | + # NO super() call here (the decorator handles it). |
| 80 | + self._tttr = None |
| 81 | + |
| 82 | + # Set up drag & drop on lineedits |
| 83 | + enable_file_drop_for_open(self.lineEdit, self._open_input_file) |
| 84 | + enable_folder_drop(self.lineEdit_2) |
| 85 | + |
| 86 | + # Fill combo box with supported types + "Auto" |
| 87 | + self.populate_supported_types() |
| 88 | + |
| 89 | + # Connect your UI elements (change names if different in .ui) |
| 90 | + self.toolButton.clicked.connect(self.browse_and_open_input_file) |
| 91 | + self.toolButton_2.clicked.connect(self.browse_output_folder) |
| 92 | + self.pushButton.clicked.connect(self.split_file) |
| 93 | + |
| 94 | + # Initialize progress bar to 0 |
| 95 | + self.progressBar.setValue(0) |
| 96 | + |
| 97 | + # -------------------------------------------------------------------------- |
| 98 | + # Private helper to open a file (browse or drag & drop) |
| 99 | + # -------------------------------------------------------------------------- |
| 100 | + def _open_input_file(self, file_path: str): |
| 101 | + """ |
| 102 | + Loads the specified file into the TTTR object. |
| 103 | + Also updates lineEdit (input path) and lineEdit_2 (default output folder). |
| 104 | + """ |
| 105 | + p = Path(file_path) |
| 106 | + if not p.is_file(): |
| 107 | + QtWidgets.QMessageBox.warning(self, "Invalid File", |
| 108 | + f"'{file_path}' is not a valid file.") |
| 109 | + return |
| 110 | + |
| 111 | + # Update the lineEdit to reflect the chosen file |
| 112 | + self.lineEdit.setText(str(p)) |
| 113 | + |
| 114 | + # Default output folder is file's parent |
| 115 | + self.lineEdit_2.setText(str(p.parent)) |
| 116 | + |
| 117 | + # Create the TTTR object |
| 118 | + if self.tttr_type is None: |
| 119 | + self._tttr = tttrlib.TTTR(str(p)) |
| 120 | + else: |
| 121 | + self._tttr = tttrlib.TTTR(str(p), self.tttr_type) |
| 122 | + |
| 123 | + if VERBOSE: |
| 124 | + QtWidgets.QMessageBox.information( |
| 125 | + self, "File Loaded", |
| 126 | + f"Successfully opened {p.name}." |
| 127 | + ) |
| 128 | + |
| 129 | + def populate_supported_types(self): |
| 130 | + """Populates the comboBox with supported container types plus an 'Auto' option.""" |
| 131 | + self.comboBox.clear() |
| 132 | + self.comboBox.insertItem(0, "Auto") |
| 133 | + self.comboBox.insertItems(1, list(tttrlib.TTTR.get_supported_container_names())) |
| 134 | + |
| 135 | + def browse_and_open_input_file(self): |
| 136 | + """File dialog for selecting a PTU file, then open it.""" |
| 137 | + dialog = QtWidgets.QFileDialog(self, "Select PTU File") |
| 138 | + dialog.setFileMode(QtWidgets.QFileDialog.ExistingFile) |
| 139 | + # Optionally: dialog.setNameFilter("PTU Files (*.ptu)") |
| 140 | + |
| 141 | + if dialog.exec_(): |
| 142 | + selected_files = dialog.selectedFiles() |
| 143 | + if selected_files: |
| 144 | + self._open_input_file(selected_files[0]) |
| 145 | + |
| 146 | + |
| 147 | + def browse_output_folder(self): |
| 148 | + """Open a File Dialog to select an output folder.""" |
| 149 | + dialog = QtWidgets.QFileDialog(self, "Select Output Folder") |
| 150 | + dialog.setFileMode(QtWidgets.QFileDialog.Directory) |
| 151 | + if dialog.exec_(): |
| 152 | + selected_dirs = dialog.selectedFiles() |
| 153 | + if selected_dirs: |
| 154 | + self.lineEdit_2.setText(selected_dirs[0]) |
| 155 | + |
| 156 | + def split_file(self): |
| 157 | + """ |
| 158 | + Split the loaded TTTR file into multiple .ptu files. |
| 159 | + Each file will contain `photons_per_file` photons. |
| 160 | + Updates self.progressBar and disables user input during splitting. |
| 161 | + """ |
| 162 | + # Ensure we have TTTR data: |
| 163 | + if self._tttr is None: |
| 164 | + QtWidgets.QMessageBox.warning( |
| 165 | + self, "No Data Loaded", |
| 166 | + "Please choose and load a PTU file before splitting." |
| 167 | + ) |
| 168 | + return |
| 169 | + |
| 170 | + # Ensure valid output folder |
| 171 | + out_folder = self.output_folder |
| 172 | + if out_folder is None: |
| 173 | + QtWidgets.QMessageBox.warning( |
| 174 | + self, "Invalid Output Folder", |
| 175 | + "Please specify a valid output folder." |
| 176 | + ) |
| 177 | + return |
| 178 | + |
| 179 | + # Disable UI elements while splitting |
| 180 | + self._set_user_input_enabled(False) |
| 181 | + |
| 182 | + t = self._tttr |
| 183 | + total_photons = len(t) |
| 184 | + chunk_size = self.photons_per_file |
| 185 | + |
| 186 | + if total_photons == 0: |
| 187 | + QtWidgets.QMessageBox.warning(self, "Empty File", "No photons to split!") |
| 188 | + self._set_user_input_enabled(True) |
| 189 | + return |
| 190 | + |
| 191 | + n_full_chunks = total_photons // chunk_size |
| 192 | + remainder = total_photons % chunk_size |
| 193 | + total_files = n_full_chunks + (1 if remainder else 0) |
| 194 | + |
| 195 | + # Create sub-folder "filename_stem_chunkSize" |
| 196 | + input_file = self.tttr_input_filename |
| 197 | + output_subfolder = out_folder / f"{input_file.stem}_{chunk_size // 1000}k" |
| 198 | + output_subfolder.mkdir(parents=True, exist_ok=True) |
| 199 | + |
| 200 | + # Retrieve header |
| 201 | + header = t.header |
| 202 | + |
| 203 | + # Loop over each chunk (including remainder if present) |
| 204 | + for i in range(total_files): |
| 205 | + # progress 0..100 |
| 206 | + progress = int((i / total_files) * 100) |
| 207 | + self.progressBar.setValue(progress) |
| 208 | + QtWidgets.QApplication.processEvents() |
| 209 | + |
| 210 | + start = i * chunk_size |
| 211 | + stop = start + chunk_size |
| 212 | + if stop > total_photons: |
| 213 | + stop = total_photons # leftover chunk |
| 214 | + |
| 215 | + c = t[start:stop] |
| 216 | + out_name = f"{input_file.stem}_{i:05d}.ptu" |
| 217 | + fn = output_subfolder / out_name |
| 218 | + c.write(fn.as_posix(), header) |
| 219 | + |
| 220 | + # Finalize progress |
| 221 | + self.progressBar.setValue(100) |
| 222 | + |
| 223 | + if VERBOSE: |
| 224 | + QtWidgets.QMessageBox.information( |
| 225 | + self, |
| 226 | + "Splitting Complete", |
| 227 | + f"Created {total_files} files in:\n{output_subfolder}" |
| 228 | + ) |
| 229 | + |
| 230 | + # Re-enable UI elements |
| 231 | + self._set_user_input_enabled(True) |
| 232 | + |
| 233 | + def _set_user_input_enabled(self, enabled: bool): |
| 234 | + """ |
| 235 | + Enable/Disable the user input widgets to prevent interaction during splitting. |
| 236 | + """ |
| 237 | + pass |
| 238 | + # Adjust to your specific widget names: |
| 239 | + self.lineEdit.setEnabled(enabled) |
| 240 | + self.lineEdit_2.setEnabled(enabled) |
| 241 | + self.comboBox.setEnabled(enabled) |
| 242 | + self.spinBox.setEnabled(enabled) |
| 243 | + self.toolButton.setEnabled(enabled) |
| 244 | + self.toolButton_2.setEnabled(enabled) |
| 245 | + self.pushButton.setEnabled(enabled) |
| 246 | + |
| 247 | + # -------------------------------------------------------------------------- |
| 248 | + # Properties |
| 249 | + # -------------------------------------------------------------------------- |
| 250 | + @property |
| 251 | + def photons_per_file(self) -> int: |
| 252 | + """Returns the current value from the spinBox as the chunk size.""" |
| 253 | + return int(self.spinBox.value()) * 1000 |
| 254 | + |
| 255 | + @property |
| 256 | + def tttr_type(self) -> str | None: |
| 257 | + """ |
| 258 | + Returns the type from the comboBox or None if 'Auto' is selected. |
| 259 | + """ |
| 260 | + tp = self.comboBox.currentText() |
| 261 | + return None if tp == "Auto" else tp |
| 262 | + |
| 263 | + @property |
| 264 | + def tttr_input_filename(self) -> Path | None: |
| 265 | + """ |
| 266 | + Returns a Path object for the input file if it exists, otherwise None. |
| 267 | + """ |
| 268 | + fn = self.lineEdit.text().strip() |
| 269 | + path = Path(fn) |
| 270 | + return path if path.is_file() else None |
| 271 | + |
| 272 | + @property |
| 273 | + def output_folder(self) -> Path | None: |
| 274 | + """ |
| 275 | + Returns a Path object for the desired output folder, or None if invalid. |
| 276 | + Creates the folder if needed. |
| 277 | + """ |
| 278 | + folder_str = self.lineEdit_2.text().strip() |
| 279 | + if not folder_str: |
| 280 | + return None |
| 281 | + p = Path(folder_str) |
| 282 | + # If the user typed a new folder path, we can decide to create it: |
| 283 | + if not p.exists(): |
| 284 | + try: |
| 285 | + p.mkdir(parents=True, exist_ok=True) |
| 286 | + except Exception as e: |
| 287 | + print(f"Failed to create folder '{p}': {e}") |
| 288 | + return None |
| 289 | + return p |
| 290 | + |
| 291 | + |
| 292 | + |
| 293 | +if __name__ == "plugin": |
| 294 | + brick_mic_wiz = PTUSplitter() |
| 295 | + brick_mic_wiz.show() |
| 296 | + |
| 297 | + |
| 298 | +if __name__ == '__main__': |
| 299 | + import sys |
| 300 | + app = QtWidgets.QApplication(sys.argv) |
| 301 | + app.aboutToQuit.connect(app.deleteLater) |
| 302 | + brick_mic_wiz = PTUSplitter() |
| 303 | + brick_mic_wiz.setWindowTitle('PTU-Splitter') |
| 304 | + brick_mic_wiz.show() |
| 305 | + sys.exit(app.exec_()) |
0 commit comments