Bread_Editor/bread_editor/editor.py

67 lines
2.1 KiB
Python

#!/usr/bin/python3
from PyQt6.QtWidgets import QWidget, QVBoxLayout
from PyQt6.QtGui import QFont, QTextCharFormat, QColor
from bread_editor.binary_text_edit import BinaryTextEdit
from bread_editor.highlighting import Higlighter
class BitEditor:
font = QFont("Ubuntu Mono", 12)
one_format = QTextCharFormat()
one_format.setBackground(QColor(200, 150, 100))
def __init__(self, app, file):
self.app = app
self.file = file
self.not_saved = False
self.setup_gui()
def setup_gui(self):
# widget that contains the text input
self.widget = QWidget(self.app.gui.main_window.openFileTabs, objectName=self.file.path)
self.widget_layout = QVBoxLayout()
self.input = BinaryTextEdit()
self.input.setOverwriteMode(True)
self.widget_layout.addWidget(self.input)
self.input.setPlainText(self.app.utils.bstring_to_oz(self.file.content))
self.input.textChanged.connect(self.on_edit)
self.bit_highlighter = Higlighter()
self.bit_highlighter.add_mapping("1", self.one_format)
self.update_style()
self.widget.setLayout(self.widget_layout)
self.tab_index = self.app.gui.main_window.openFileTabs.addTab( # add a tab for the file in the top files list
self.widget,
self.file.name
)
def on_edit(self):
self.not_saved = True
def update_style(self):
square = self.app.settings.square_bits
spacing = 200 if square else 100 # add spacing when setting is checked
self.font.setLetterSpacing(QFont.SpacingType.PercentageSpacing, spacing)
self.input.setFont(self.font)
self.cursor_width = self.input.fontMetrics().averageCharWidth()
# set the cursor with to match the letter spacing
self.input.setCursorWidth(self.cursor_width + 1) # + 1 because else it somehow draws a 1px wide vertical line
highlight_ones = self.app.settings.highlight_ones
highlighter_document = self.input.document() if highlight_ones else None
self.bit_highlighter.setDocument(highlighter_document)