summaryrefslogtreecommitdiff
path: root/kodereviewer/models/line_model.py
blob: 03d14c6e7b050a90b70f84f29786a3ba52e9abf7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
"""Model used for line numbers in Editor.qml"""
import logging
from enum import auto, IntEnum
from typing import Optional

import rich
from PySide6.QtCore import QAbstractListModel, QByteArray, QModelIndex, QObject, QPersistentModelIndex, QStandardPaths, QUrl, Qt, Signal, Slot, Property
from PySide6.QtQuick import QQuickTextDocument
from PySide6.QtQml import QmlElement

QML_IMPORT_NAME = "org.deprecated.kodereviewer"
QML_IMPORT_MAJOR_VERSION = 1

logger = logging.getLogger(__name__)


@QmlElement
class LineModel(QAbstractListModel):

    _document: QQuickTextDocument | None

    class Roles(IntEnum):
        LineHeight = Qt.ItemDataRole.UserRole + 1

    def __init__(self, *args, **kwargs):
        self._document = None
        super().__init__(*args, **kwargs)


    def get_document(self):
        return self._document

    def set_document(self, document):
        logger.debug('setting document')
        if document == self._document:
            logger.debug(f'Document {document} == {self._document}')
            return
        logger.debug(f'Setting document {document}')
        self._document = document
        self.documentChanged.emit()
        self.resetModel()

    documentChanged = Signal()
    document = Property(QObject, fget=get_document, fset=set_document,
                        notify=documentChanged)

    def data(self,
             index: QModelIndex | QPersistentModelIndex,
             role: int = Qt.ItemDataRole.DisplayRole) -> object:

        if not index.isValid():
            logger.debug('index not valid')
            return

        if self._document is None:
            logger.debug('document none')
            return

        row = index.row()
        if row < 0 or row > self.rowCount():
            logger.debug(f'row: {row}')
            return

        if role == self.Roles.LineHeight:
            text_doc = self._document.textDocument()
            return int(text_doc.documentLayout().blockBoundingRect(text_doc.findBlockByNumber(row)).height())
        logger.debug('found role ?')


    def rowCount(self, parent: QModelIndex | QPersistentModelIndex = QModelIndex()) -> int:
        if self._document is None:
            logger.debug('rowCount: _document is None')
            return 0
        return self._document.textDocument().blockCount();

    def roleNames(self) -> dict[int, QByteArray]:
        return {
            self.Roles.LineHeight: QByteArray(b'lineHeight'),
        }


    @Slot()
    def resetModel(self) -> None:
        logger.debug('reseting model?')
        self.beginResetModel()
        self.endResetModel()