Debian Codegraph @

lib/cat.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 #
3 # QBrz - Qt frontend to Breezy commands
4 # Copyright (C) 2007 Lukáš Lalinský <[email protected]om>
5 #
6 # This program is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU General Public License
8 # as published by the Free Software Foundation; either version 2
9 # of the License, or (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19
20 import os
21 from PyQt5 import QtCore, QtGui, QtWidgets
22
23 from breezy import errors, osutils
24 from breezy.branch import Branch
25
26 from breezy.plugins.qbrz.lib.i18n import gettext
27 from breezy.plugins.qbrz.lib.util import (
28 BTN_CLOSE,
29 QBzrWindow,
30 ThrobberWidget,
31 file_extension,
32 get_monospace_font,
33 get_set_encoding,
34 get_tab_width_pixels,
35 runs_in_loading_queue,
36 )
37 from breezy.plugins.qbrz.lib.encoding_selector import EncodingSelector
38 from breezy.plugins.qbrz.lib.fake_branch import FakeBranch
39 from breezy.plugins.qbrz.lib.syntaxhighlighter import highlight_document
40 from breezy.plugins.qbrz.lib.texteditannotate import LineNumberEditerFrame
41 from breezy.plugins.qbrz.lib.trace import reports_exception
42 from breezy.plugins.qbrz.lib.uifactory import ui_current_widget
43
44
45 def hexdump(data):
46 content = []
47 for i in range(0, len(data), 16):
48 hexdata = []
49 chardata = []
50 for c in data[i:i+16]:
51 j = ord(c)
52 hexdata.append('%02x' % j)
53 if j >= 32 and j < 128:
54 chardata.append(c)
55 else:
56 chardata.append('.')
57 for c in range(16 - len(hexdata)):
58 hexdata.append(' ')
59 chardata.append(' ')
60 line = '%08x ' % i + ' '.join(hexdata[:8]) + ' ' + ' '.join(hexdata[8:]) + ' |' + ''.join(chardata) + '|'
61 content.append(line)
62 return '\n'.join(content)
63
64
65 class QBzrCatWindow(QBzrWindow):
66 """Show content of versioned file/symlink."""
67
68 def __init__(self, filename=None, revision=None,
69 tree=None, file_id=None, encoding=None,
70 parent=None):
71 """Create qcat window."""
72
73 self.filename = filename
74 self.revision = revision
75 self.tree = tree
76 if tree:
77 self.branch = getattr(tree, 'branch', None)
78 if self.branch is None:
79 self.branch = FakeBranch()
80 self.file_id = file_id
81 self.encoding = encoding
82
83 if (not self.filename) and self.tree and self.file_id:
84 self.filename = self.tree.id2path(self.file_id)
85
86 QBzrWindow.__init__(self, [gettext("View"), self.filename], parent)
87 self.restoreSize("cat", (780, 580))
88
89 self.throbber = ThrobberWidget(self)
90 self.buttonbox = self.create_button_box(BTN_CLOSE)
91 self.encoding_selector = self._create_encoding_selector()
92
93 self.vbox = QtWidgets.QVBoxLayout(self.centralwidget)
94 self.vbox.addWidget(self.throbber)
95 self.vbox.addStretch()
96
97 hbox = QtWidgets.QHBoxLayout()
98 hbox.addWidget(self.encoding_selector)
99 hbox.addWidget(self.buttonbox)
100 self.vbox.addLayout(hbox)
101
102 def _create_encoding_selector(self):
103 encoding_selector = EncodingSelector(self.encoding,
104 gettext("Encoding:"),
105 self._on_encoding_changed)
106 # disable encoding selector,
107 # it will be enabled later only for text files
108 encoding_selector.setDisabled(True)
109 return encoding_selector
110
111 def show(self):
112 # we show the bare form as soon as possible.
113 # RJL, 2023 - this used to call QtCore.QTimer.singleShot(0, self.load)
114 # however, that failed to call self.load() rapidly enough
115 # (probably things run a lot faster in 2023 than 2007!), so
116 # just call it directly
117 QBzrWindow.show(self)
118 self.load()
119
120 @runs_in_loading_queue
121 @ui_current_widget
122 @reports_exception()
123 def load(self):
124 self.throbber.show()
125 self.processEvents()
126 try:
127 if not self.tree:
128 branch, relpath = Branch.open_containing(self.filename)
129 self.branch = branch
130 self.encoding = get_set_encoding(self.encoding, branch)
131 self.encoding_selector.encoding = self.encoding
132
133 if self.revision is None:
134 self.tree = branch.basis_tree()
135 else:
136 revision_id = self.revision[0].in_branch(branch).rev_id
137 self.tree = branch.repository.revision_tree(revision_id)
138
139 self.file_id = self.tree.path2id(relpath)
140
141 if not self.file_id:
142 self.file_id = self.tree.path2id(self.filename)
143
144 if not self.file_id:
145 raise errors.BzrCommandError(
146 "%r is not present in revision %s" % (
147 self.filename, self.tree.get_revision_id()))
148 with self.tree.lock_read():
149 kind = self.tree.kind(self.filename)
150 if kind == 'file':
151 text = self.tree.get_file_text(self.filename)
152 elif kind == 'symlink':
153 text = self.tree.get_symlink_target(self.filename)
154 else:
155 text = ''
156 self.processEvents()
157
158 self.text = text
159 self.kind = kind
160 self._create_and_show_browser(self.filename, text, kind)
161 finally:
162 self.throbber.hide()
163
164 def _create_and_show_browser(self, filename, text, kind):
165 """Create browser object for given file and then attach it to GUI.
166
167 @param filename: filename used for differentiate between images
168 and simply binary files.
169 @param text: raw file content.
170 @param kind: filesystem kind: file, symlink, directory
171 """
172 type_, fview = self.detect_content_type(filename, text, kind)
173 # update title
174 title = "View " + type_
175 self.set_title([gettext(title), filename])
176 # create and show browser
177 self.browser = fview(filename, text)
178 self.vbox.insertWidget(1, self.browser, 1)
179 # set focus on content
180 self.browser.setFocus()
181
182 def detect_content_type(self, relpath, text, kind='file'):
183 """Return (file_type, viewer_factory) based on kind, text and relpath.
184 Supported file types: text, image, binary
185 """
186 if kind == 'file':
187 if not b'\0' in text:
188 return 'text file', self._create_text_view
189 else:
190 ext = file_extension(relpath).lower()
191 image_exts = ['.'+str(i)
192 for i in QtGui.QImageReader.supportedImageFormats()]
193 if ext in image_exts:
194 return 'image file', self._create_image_view
195 else:
196 return 'binary file', self._create_hexdump_view
197 else:
198 return kind, self._create_symlink_view
199
200 def _set_text(self, edit_widget, relpath, text, encoding=None):
201 """Set plain text to widget, as unicode.
202
203 @param edit_widget: edit widget to view the text.
204 @param relpath: filename (required for syntax highlighting to detect
205 file type).
206 @param text: plain non-unicode text (bytes).
207 @param encoding: text encoding (default: utf-8).
208 """
209 text = text.decode(encoding or 'utf-8', 'replace')
210 edit_widget.setPlainText(text)
211 highlight_document(edit_widget, relpath)
212
213 def _create_text_view(self, relpath, text):
214 """Create widget to show text files.
215 @return: created widget with loaded text.
216 """
217 browser = LineNumberEditerFrame(self)
218 edit = browser.edit
219 edit.setReadOnly(True)
220 edit.document().setDefaultFont(get_monospace_font())
221
222 edit.setTabStopWidth(get_tab_width_pixels(self.branch))
223
224 self._set_text(edit, relpath, text, self.encoding)
225 self.encoding_selector.setEnabled(True)
226 return browser
227
228 def _on_encoding_changed(self, encoding):
229 """Event handler for EncodingSelector.
230 It sets file text to browser again with new encoding.
231 """
232 self.encoding = encoding
233 branch = self.branch
234 if branch is None:
235 branch = Branch.open_containing(self.filename)[0]
236 if branch:
237 get_set_encoding(encoding, branch)
238 self._set_text(self.browser.edit, self.filename, self.text, self.encoding)
239
240 def _create_simple_text_browser(self):
241 """Create and return simple widget to show text-like content."""
242 browser = QtWidgets.QPlainTextEdit(self)
243 browser.setReadOnly(True)
244 browser.document().setDefaultFont(get_monospace_font())
245 return browser
246
247 def _create_symlink_view(self, relpath, target):
248 """Create widget to show symlink target.
249 @return: created widget with loaded content.
250 """
251 browser = self._create_simple_text_browser()
252 browser.setPlainText('-> ' + target.decode('utf-8', 'replace'))
253 return browser
254
255 def _create_hexdump_view(self, relpath, data):
256 """Create widget to show content of binary files.
257 @return: created widget with loaded content.
258 """
259 browser = self._create_simple_text_browser()
260 browser.setPlainText(hexdump(data))
261 return browser
262
263 def _create_image_view(self, relpath, data):
264 """Create widget to show image file.
265 @return: created widget with loaded image.
266 """
267 self.pixmap = QtGui.QPixmap()
268 self.pixmap.loadFromData(data)
269 self.item = QtWidgets.QGraphicsPixmapItem(self.pixmap)
270 self.scene = QtWidgets.QGraphicsScene(self.item.boundingRect())
271 self.scene.addItem(self.item)
272 return QtWidgets.QGraphicsView(self.scene)
273
274
275 class QBzrViewWindow(QBzrCatWindow):
276 """Show content of file/symlink from the disk."""
277
278 def __init__(self, filename=None, encoding=None, parent=None):
279 """Construct GUI.
280
281 @param filename: filesystem object to view.
282 @param encoding: use this encoding to decode text file content
283 to unicode.
284 @param parent: parent widget.
285 """
286 QBzrWindow.__init__(self, [gettext("View"), filename], parent)
287 self.restoreSize("cat", (780, 580))
288
289 self.filename = filename
290 self.encoding = encoding
291
292 self.buttonbox = self.create_button_box(BTN_CLOSE)
293 self.encoding_selector = self._create_encoding_selector()
294 self.branch = FakeBranch()
295
296 self.vbox = QtWidgets.QVBoxLayout(self.centralwidget)
297 self.vbox.addStretch()
298 hbox = QtWidgets.QHBoxLayout()
299 hbox.addWidget(self.encoding_selector)
300 hbox.addWidget(self.buttonbox)
301 self.vbox.addLayout(hbox)
302
303 def load(self):
304 kind = osutils.file_kind(self.filename)
305 text = ''
306 if kind == 'file':
307 with open(self.filename, 'rb') as f:
308 text = f.read()
309 elif kind == 'symlink':
310 text = os.readlink(self.filename)
311 self.text = text
312 self._create_and_show_browser(self.filename, text, kind)
313
314
315 def cat_to_native_app(tree, relpath):
316 """Extract file content to temp directory and then launch
317 native application to open it.
318
319 @param tree: RevisionTree object.
320 @param relpath: path to file relative to tree root.
321 @raise KindError: if relpath entry has not file kind.
322 @return: True if native application was launched.
323 """
324 kind = tree.kind(relpath)
325 if kind != 'file':
326 raise KindError('cat to native application is not supported '
327 'for entry of kind %r' % kind)
328 # make temp file
329 import os
330 import tempfile
331 # RJLRJL Check this QBzr reference
332 # qdir = os.path.join(tempfile.gettempdir(), 'QBzr', 'qcat')
333 qdir = os.path.join(tempfile.gettempdir(), 'qbrz', 'qcat')
334 if not os.path.isdir(qdir):
335 os.makedirs(qdir)
336 basename = os.path.basename(relpath)
337 fname = os.path.join(qdir, basename)
338 with open(fname, 'wb') as f, tree.lock_read():
339 f.write(tree.get_file_text(relpath))
340 # open it
341 url = QtCore.QUrl.fromLocalFile(fname)
342 result = QtGui.QDesktopServices.openUrl(url)
343 # now application is about to start and user will work with file
344 # so we can do cleanup in "background"
345 import time
346 limit = time.time() - 60 # files older than 1 minute
347 files = os.listdir(qdir)
348 for i in files[:20]:
349 if i == basename:
350 continue
351 fname = os.path.join(qdir, i)
352 st = os.lstat(fname)
353 if st.st_mtime > limit:
354 continue
355 try:
356 os.unlink(fname)
357 except (OSError, IOError):
358 pass
359 #
360 return result
361
362
363 class KindError(errors.BzrError):
364 pass