2024-11-20 15:52:10 +01:00
|
|
|
#!/usr/bin/python3
|
|
|
|
|
|
|
|
from PyQt6.QtWidgets import QPlainTextEdit
|
2024-12-09 17:26:28 +01:00
|
|
|
from PyQt6.QtCore import Qt
|
2024-11-20 15:52:10 +01:00
|
|
|
|
|
|
|
|
|
|
|
class BinaryTextEdit(QPlainTextEdit): # rewrite QPlainTextEdit.keyPressEvent because it has no .setValidator()
|
|
|
|
def keyPressEvent(self, event):
|
|
|
|
allowed_keys = {"", "0", "1"}
|
|
|
|
|
|
|
|
if event.text() in allowed_keys:
|
|
|
|
cursor = self.textCursor()
|
2024-12-09 17:26:28 +01:00
|
|
|
position = cursor.position()
|
2024-11-20 17:19:07 +01:00
|
|
|
text = self.toPlainText()
|
|
|
|
text_length = len(text)
|
2024-11-20 15:52:10 +01:00
|
|
|
|
2024-12-09 17:26:28 +01:00
|
|
|
if not (position + 1) % 9 == 0 or event.text() in {"", None}: # dont overwrite the separator character
|
2024-11-20 16:20:04 +01:00
|
|
|
super().keyPressEvent(event)
|
2024-11-20 15:52:10 +01:00
|
|
|
|
2024-12-09 16:53:33 +01:00
|
|
|
# skip over the separator character when the cursor is right before it.
|
2024-12-09 17:26:28 +01:00
|
|
|
if (position + 2) % 9 == 0 and not event.text() in {"", None}:
|
|
|
|
if position == text_length - 1: # append to the input if the cursor is at the end
|
2024-12-09 16:53:33 +01:00
|
|
|
self.insertPlainText(" 00000000")
|
2024-11-20 17:19:07 +01:00
|
|
|
|
2024-12-09 17:26:28 +01:00
|
|
|
cursor.setPosition(position + 2)
|
|
|
|
self.setTextCursor(cursor)
|
|
|
|
|
|
|
|
elif event.key() == Qt.Key.Key_Backspace or event.key() == Qt.Key.Key_Delete:
|
|
|
|
# delete last byte when backspace or delete is pressed
|
|
|
|
text = self.toPlainText()
|
|
|
|
|
|
|
|
if len(text) >= 9:
|
|
|
|
cursor = self.textCursor()
|
|
|
|
position = cursor.position()
|
|
|
|
|
|
|
|
text = text[:-9] # delete last byte
|
|
|
|
|
|
|
|
self.setPlainText(text)
|
|
|
|
|
|
|
|
# calculate the new cursor position (by subtracting 9, we set the position to the same bit but one byte
|
|
|
|
# before and by floor dividing this by 9 we get the "byte index" and when we multiply this by 9, we get
|
|
|
|
# the character position of the first bit in that byte.)
|
|
|
|
position = (position - 9) // 9 * 9
|
|
|
|
|
|
|
|
cursor.setPosition(position)
|
|
|
|
|
2024-11-20 16:20:04 +01:00
|
|
|
self.setTextCursor(cursor)
|
2024-11-20 15:52:10 +01:00
|
|
|
|
|
|
|
else:
|
|
|
|
event.ignore()
|