File: document.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 (220 lines) | stat: -rw-r--r-- 7,289 bytes parent folder | download
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
# 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.

"""
A Frescobaldi (LilyPond) document.
"""


import os

from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QTextCursor, QTextDocument
from PyQt5.QtWidgets import QPlainTextDocumentLayout

import app
import util
import variables
import signals


class Document(QTextDocument):
    
    urlChanged = signals.Signal() # new url, old url
    closed = signals.Signal()
    loaded = signals.Signal()
    saving = signals.SignalContext()
    saved = signals.Signal()
    
    @classmethod
    def load_data(cls, url, encoding=None):
        """Class method to load document contents from an url.
        
        This is intended to open a document without instantiating one
        if loading the contents fails.
        
        This method returns the text contents of the url as decoded text,
        thus a unicode string.
        
        The line separator is always '\\n'.
        
        """
        filename = url.toLocalFile()
        
        # currently, we do not support non-local files
        if not filename:
            raise IOError("not a local file")
        with open(filename, 'rb') as f:
            data = f.read()
        text = util.decode(data, encoding)
        return util.universal_newlines(text)
    
    @classmethod
    def new_from_url(cls, url, encoding=None):
        """Create and return a new document, loaded from url.
        
        This is intended to open a new Document without instantiating one
        if loading the contents fails.
        
        """
        if not url.isEmpty():
            text = cls.load_data(url, encoding)
        d = cls(url, encoding)
        if not url.isEmpty():
            d.setPlainText(text)
            d.setModified(False)
            d.loaded()
            app.documentLoaded(d)
        return d
        
    def __init__(self, url=None, encoding=None):
        """Create a new Document with url and encoding.
        
        Does not load the contents, you should use load() for that, or
        use the new_from_url() constructor to instantiate a new Document
        with the contents loaded.
        
        """
        if url is None:
            url = QUrl()
        super(Document, self).__init__()
        self.setDocumentLayout(QPlainTextDocumentLayout(self))
        self._encoding = encoding
        self._url = url # avoid urlChanged on init
        self.setUrl(url)
        self.modificationChanged.connect(self.slotModificationChanged)
        app.documents.append(self)
        app.documentCreated(self)
        
    def slotModificationChanged(self):
        app.documentModificationChanged(self)

    def close(self):
        self.closed()
        app.documentClosed(self)
        app.documents.remove(self)

    def load(self, url=None, encoding=None, keepUndo=False):
        """Load the specified or current url (if None was specified).
        
        Currently only local files are supported. An IOError is raised
        when trying to load a nonlocal URL.
        
        If loading succeeds and an url was specified, the url is make the
        current url (by calling setUrl() internally).
        
        If keepUndo is True, the loading can be undone (with Ctrl-Z).
        
        """
        if url is None:
            url = QUrl()
        u = url if not url.isEmpty() else self.url()
        text = self.load_data(u, encoding or self._encoding)
        if keepUndo:
            c = QTextCursor(self)
            c.select(QTextCursor.Document)
            c.insertText(text)
        else:
            self.setPlainText(text)
        self.setModified(False)
        if not url.isEmpty():
            self.setUrl(url)
        self.loaded()
        app.documentLoaded(self)
            
    def save(self, url=None, encoding=None):
        """Saves the document to the specified or current url.
        
        Currently only local files are supported. An IOError is raised
        when trying to save a nonlocal URL.
        
        If saving succeeds and an url was specified, the url is made the
        current url (by calling setUrl() internally).
        
        """
        if url is None:
            url = QUrl()
        u = url if not url.isEmpty() else self.url()
        filename = u.toLocalFile()
        # currently, we do not support non-local files
        if not filename:
            raise IOError("not a local file")
        # keep the url if specified when we didn't have one, even if saving
        # would fail
        if self.url().isEmpty() and not url.isEmpty():
            self.setUrl(url)
        with self.saving(), app.documentSaving(self):
            with open(filename, "wb") as f:
                f.write(self.encodedText())
                f.flush()
                os.fsync(f.fileno())
            self.setModified(False)
            if not url.isEmpty():
                self.setUrl(url)
        self.saved()
        app.documentSaved(self)

    def url(self):
        return self._url
        
    def setUrl(self, url):
        """ Change the url for this document. """
        if url is None:
            url = QUrl()
        old, self._url = self._url, url
        changed = old != url
        # number for nameless documents
        if self._url.isEmpty():
            nums = [0]
            nums.extend(doc._num for doc in app.documents if doc is not self)
            self._num = max(nums) + 1
        else:
            self._num = 0
        if changed:
            self.urlChanged(url, old)
            app.documentUrlChanged(self, url, old)
    
    def encoding(self):
        return variables.get(self, "coding") or self._encoding
        
    def setEncoding(self, encoding):
        self._encoding = encoding
    
    def encodedText(self):
        """Returns the text of the document encoded in the correct encoding.
        
        The line separator is '\\n' on Unix/Linux/Mac OS X, '\\r\\n' on Windows.
        
        Useful to save to a file.
        
        """
        text = util.platform_newlines(self.toPlainText())
        return util.encode(text, self.encoding())
        
    def documentName(self):
        """ Returns a suitable name for this document. """
        if self._url.isEmpty():
            if self._num == 1:
                return _("Untitled")
            else:
                return _("Untitled ({num})").format(num=self._num)
        else:
            return os.path.basename(self._url.path())