File: model.py

package info (click to toggle)
frescobaldi 3.0.0~git20161001.0.eec60717%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 19,792 kB
  • ctags: 5,843
  • sloc: python: 37,853; sh: 180; makefile: 69
file content (197 lines) | stat: -rw-r--r-- 6,578 bytes parent folder | download | duplicates (2)
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# This file is part of the Frescobaldi project, http://www.frescobaldi.org/
#
# Copyright (c) 2008 - 2014 by Wilbert Berendsen
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
# See http://www.gnu.org/licenses/ for more information.

"""
The model containing the snippets data.
"""



import bisect

from PyQt5.QtCore import QAbstractItemModel, QModelIndex, Qt
from PyQt5.QtGui import QKeySequence

import app
import actioncollection

from . import snippets


def model():
    """Returns the global model containing snippets."""
    m = SnippetModel(app.qApp)
    global model
    model = lambda: m
    return m


class SnippetModel(QAbstractItemModel):
    """Presents the snippets as a Qt Model."""
    def __init__(self, parent = None):
        super(SnippetModel, self).__init__(parent)
        self._names = []
        self.load()
        app.settingsChanged.connect(self.slotSettingsChanged)
        app.languageChanged.connect(self.slotLanguageChanged)
        
    # methods needed to be a well-behaved model
    def headerData(self, section, orientation, role=Qt.DisplayRole):
        if role == Qt.DisplayRole and orientation == Qt.Horizontal:
            if section == 0:
                return _("Name")
            elif section == 1:
                return _("Description")
            else:
                return _("Shortcut")
    
    def index(self, row, column, parent=None):
        return self.createIndex(row, column)
    
    def parent(self, index):
        return QModelIndex()
    
    def columnCount(self, parent=QModelIndex()):
        return 3 if not parent.isValid() else 0
    
    def rowCount(self, parent=QModelIndex()):
        return len(self._names) if not parent.isValid() else 0
    
    def data(self, index, role=Qt.DisplayRole):
        name = self.name(index)
        if role == Qt.DisplayRole:
            if index.column() == 0:
                return snippets.get(name).variables.get('name')
            elif index.column() == 1:
                return snippets.title(name)
            else:
                return shortcut(name)
        elif role == Qt.DecorationRole and index.column() == 1:
            return snippets.icon(name)
    
    # slots
    def slotSettingsChanged(self):
        """Called when settings change, e.g. when keyboard shortcuts are altered."""
        self.load()
        
    def slotLanguageChanged(self):
        """Called when the user changes the language."""
        self.headerDataChanged.emit(Qt.Horizontal, 0, 2)
        
    def load(self):
        self.beginResetModel()
        self._names = sorted(snippets.names(), key=snippets.title)
        self.endResetModel()
    
    # interface for getting/altering snippets
    def names(self):
        """Returns the internal list of snippet names in title order. Do not alter!"""
        return self._names
        
    def name(self, index):
        """The internal snippet id for the given QModelIndex."""
        return self._names[index.row()]

    def removeRows(self, row, count, parent=QModelIndex()):
        end = row + count
        self.beginRemoveRows(parent, row, end)
        try:
            for name in self._names[row:end]:
                snippets.delete(name)
            del self._names[row:end]
        finally:
            self.endRemoveRows()
            return True
        
    def saveSnippet(self, name, text, title):
        """Store a snippet.
        
        If name is None or does not exist in names(), a new snippet is created.
        Returns the QModelIndex the snippet was stored at.
        
        Title may be None.
        
        """
        # first, get the old titles list
        titles = list(snippets.title(n) for n in self._names)
        
        oldrow = None
        if name is None:
            name = snippets.name(self._names)
        else:
            try:
                oldrow = self._names.index(name)
            except ValueError:
                pass
        snippets.save(name, text, title)
        # sort the new snippet in
        # if oldrow is not None, it is the row to be removed.
        title = snippets.title(name)
        i = bisect.bisect_right(titles, title)
        
        if oldrow is None:
            # just insert new snippet
            self.beginInsertRows(QModelIndex(), i, i )
            self._names.insert(i, name)
            self.endInsertRows()
            return self.createIndex(i, 0)
        elif i in (oldrow, oldrow+1):
            # just replace
            self._names[oldrow] = name
            self.dataChanged.emit(self.createIndex(oldrow, 0), self.createIndex(oldrow, 2))
            return self.createIndex(oldrow, 0)
        else:
            # move the old row to the new place
            if self.beginMoveRows(QModelIndex(), oldrow, oldrow, QModelIndex(), i):
                del self._names[oldrow]
                if i > oldrow:
                    i -= 1
                self._names.insert(i, name)
                self.endMoveRows()
                self.dataChanged.emit(self.createIndex(i, 0), self.createIndex(i, 2))
                return self.createIndex(i, 0)
            raise RuntimeError("wrong row move offset")


def shortcut(name):
    """Returns a shortcut text for the named snippets, if any, else None."""
    s = shortcuts(name)
    if s:
        text = s[0].toString(QKeySequence.NativeText)
        if len(s) > 1:
            text += "..."
        return text


def shortcuts(name):
    """Returns a (maybe empty) list of QKeySequences for the named snippet."""
    ac = collection()
    return ac and ac.shortcuts(name) or []


def collection():
    """Returns an instance of the 'snippets' ShortcutCollection, if existing."""
    try:
        # HACK alert :-) access an instance of the ShortcutCollection named 'snippets'
        ref = actioncollection.ShortcutCollection.others['snippets'][0]
    except (KeyError, IndexError):
        return
    return ref()