From 79f9219e9ae83a2249bd9b062aa0f6e533ce2e28 Mon Sep 17 00:00:00 2001 From: Andreas Huber Date: Sun, 31 Oct 2021 12:30:06 +0100 Subject: [PATCH] save selection to file if above threshold --- bigtext.py | 21 +++++++++++++++------ logFileModel.py | 12 ++++++++++++ 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/bigtext.py b/bigtext.py index 5c75fa9..9736092 100644 --- a/bigtext.py +++ b/bigtext.py @@ -238,17 +238,26 @@ class InnerBigText(QWidget): you_sure.setStandardButtons(QMessageBox.StandardButton.Cancel) you_sure.addButton(QPushButton(self.tr("Copy {0} to Clipboard").format(bytes_human_readable)), QMessageBox.ButtonRole.AcceptRole) - # TODO add save dialog - # you_sure.addButton(QPushButton(self.tr("Write to File")), QMessageBox.ButtonRole.YesRole) + you_sure.addButton(QPushButton(self.tr("Write to File")), QMessageBox.ButtonRole.YesRole) you_sure.setDefaultButton(QMessageBox.StandardButton.Cancel) result = you_sure.exec() - if result != QMessageBox.StandardButton.Yes: + if result == 1: # second custom button has the number 1 + dialog = QFileDialog(self) + (selected_file, _filter) = dialog.getSaveFileName( + caption=self.tr("Save File"), + directory=os.path.dirname(self.model.get_file()) + ) + if selected_file: + self.model.write_range(start, end, selected_file) + return + + if result == QMessageBox.StandardButton.Cancel.value: # abort return - selected_text = self.model.read_range(start, end) - cb = QApplication.clipboard() - cb.setText(selected_text) + selected_text = self.model.read_range(start, end) + cb = QApplication.clipboard() + cb.setText(selected_text) def paintEvent(self, event: QPaintEvent) -> None: # print("paintEvent") diff --git a/logFileModel.py b/logFileModel.py index b195605..05dbccb 100644 --- a/logFileModel.py +++ b/logFileModel.py @@ -56,6 +56,18 @@ class LogFileModel: bytes = f.read(end_byte - start_byte) return bytes.decode("utf8", errors="ignore") + def write_range(self, start_byte: int, end_byte: int, file: str): + print("write range: %d - %d -> %s" % (start_byte, end_byte, file)) + with self._lock, open(self._file, 'rb') as source, open(file, "w+b") as target: + offset = start_byte + source.seek(offset) + while offset < end_byte: + new_offset = min(offset + 1024 * 1024, end_byte) + buffer_size = new_offset - offset + buffer = source.read(buffer_size) + target.write(buffer) + offset = new_offset + def data(self, byte_offset, scroll_lines, lines) -> List[Line]: # print("data(%s, %s, %s)" % (byte_offset, scroll_lines, lines)) lines_before_offset: List[Line] = []