File indexing completed on 2024-06-09 04:28:25

0001 # SPDX-License-Identifier: CC0-1.0
0002 
0003 from PyQt5.QtCore import QAbstractListModel, Qt, QSize
0004 from PyQt5.QtGui import QImage
0005 import krita
0006 import zipfile
0007 from pathlib import Path
0008 
0009 
0010 class LastDocumentsListModel(QAbstractListModel):
0011 
0012     def __init__(self, devicePixelRatioF, parent=None):
0013         super(LastDocumentsListModel, self).__init__(parent)
0014 
0015         self.rootItem = ('Path',)
0016         self.kritaInstance = krita.Krita.instance()
0017         self.recentDocuments = []
0018         self.devicePixelRatioF = devicePixelRatioF
0019 
0020     def data(self, index, role):
0021         if not index.isValid():
0022             return None
0023 
0024         if index.row() >= len(self.recentDocuments):
0025             return None
0026 
0027         if role == Qt.DecorationRole:
0028             return self.recentDocuments[index.row()]
0029         else:
0030             return None
0031 
0032     def rowCount(self, parent):
0033         return len(self.recentDocuments)
0034 
0035     def headerData(self, section, orientation, role):
0036         if orientation == Qt.Horizontal and role == Qt.DisplayRole:
0037             return self.rootItem[section]
0038 
0039         return None
0040 
0041     def loadRecentDocuments(self):
0042         self.recentDocuments = []
0043         recentDocumentsPaths = self.kritaInstance.recentDocuments()
0044 
0045         for path in recentDocumentsPaths:
0046             if path:
0047                 thumbnail = None
0048                 extension = Path(path).suffix
0049                 page = None
0050                 if extension == '.kra':
0051                     page = zipfile.ZipFile(path, "r")
0052                     thumbnail = QImage.fromData(page.read("mergedimage.png"))
0053                     if thumbnail.isNull():
0054                         thumbnail = QImage.fromData(page.read("preview.png"))
0055                 else:
0056                     thumbnail = QImage(path)
0057 
0058                 if thumbnail.isNull():
0059                     continue
0060 
0061                 thumbSize = QSize(int(200*self.devicePixelRatioF), int(150*self.devicePixelRatioF))
0062                 if thumbnail.width() <= thumbSize.width() or thumbnail.height() <= thumbSize.height():
0063                     thumbnail = thumbnail.scaled(thumbSize, Qt.KeepAspectRatio, Qt.FastTransformation)
0064                 else:
0065                     thumbnail = thumbnail.scaled(thumbSize, Qt.KeepAspectRatio, Qt.SmoothTransformation)
0066                 thumbnail.setDevicePixelRatio(self.devicePixelRatioF)
0067                 self.recentDocuments.append(thumbnail)
0068         self.modelReset.emit()