~doxxx/qbzr/qconflicts-cmdline-splitting

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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
# -*- coding: utf-8 -*-
#
# QBzr - Qt frontend to Bazaar commands
# Copyright (C) 2007 Lukáš Lalinský <lalinsky@gmail.com>
#
# 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 Street, Fifth Floor, Boston, MA 02110-1301, USA.

import os
from PyQt4 import QtCore, QtGui

from bzrlib import errors, osutils
from bzrlib.branch import Branch

from bzrlib.plugins.qbzr.lib.i18n import gettext
from bzrlib.plugins.qbzr.lib.util import (
    BTN_CLOSE,
    QBzrWindow,
    ThrobberWidget,
    file_extension,
    get_set_encoding,
    runs_in_loading_queue,
    )
from bzrlib.plugins.qbzr.lib.uifactory import ui_current_widget
from bzrlib.plugins.qbzr.lib.trace import reports_exception
from bzrlib.plugins.qbzr.lib.encoding_selector import EncodingSelector
from bzrlib.plugins.qbzr.lib.syntaxhighlighter import highlight_document
from bzrlib.plugins.qbzr.lib.texteditannotate import LineNumberEditerFrame


def hexdump(data):
    content = []
    for i in range(0, len(data), 16):
        hexdata = []
        chardata = []
        for c in data[i:i+16]:
            j = ord(c)
            hexdata.append('%02x' % j)
            if j >= 32 and j < 128:
                chardata.append(c)
            else:
                chardata.append('.')
        for c in range(16 - len(hexdata)):
            hexdata.append('  ')
            chardata.append(' ')
        line = '%08x  ' % i + ' '.join(hexdata[:8]) + '  ' + ' '.join(hexdata[8:]) + '  |' + ''.join(chardata) + '|'
        content.append(line)
    return '\n'.join(content)


class QBzrCatWindow(QBzrWindow):
    """Show content of versioned file/symlink."""

    def __init__(self, filename=None, revision=None,
                 tree=None, file_id=None, encoding=None,
                 parent=None):
        """Create qcat window."""
        
        self.filename = filename
        self.revision = revision
        self.tree = tree
        if tree:
            self.branch = getattr(tree, 'branch', None)
            if self.branch is None:
                self.branch = FakeBranch()
        self.file_id = file_id
        self.encoding = encoding

        if (not self.filename) and self.tree and self.file_id:
            self.filename = self.tree.id2path(self.file_id)

        QBzrWindow.__init__(self, [gettext("View"), self.filename], parent)
        self.restoreSize("cat", (780, 580))

        self.throbber = ThrobberWidget(self)
        self.buttonbox = self.create_button_box(BTN_CLOSE)
        self.encoding_selector = self._create_encoding_selector()

        self.vbox = QtGui.QVBoxLayout(self.centralwidget)
        self.vbox.addWidget(self.throbber)
        self.vbox.addStretch()

        hbox = QtGui.QHBoxLayout()
        hbox.addWidget(self.encoding_selector)
        hbox.addWidget(self.buttonbox)
        self.vbox.addLayout(hbox)

    def _create_encoding_selector(self):
        encoding_selector = EncodingSelector(self.encoding,
            gettext("Encoding:"),
            self._on_encoding_changed)
        # disable encoding selector,
        # it will be enabled later only for text files
        encoding_selector.setDisabled(True)
        return encoding_selector

    def show(self):
        # we show the bare form as soon as possible.
        QBzrWindow.show(self)
        QtCore.QTimer.singleShot(0, self.load)
    
    @runs_in_loading_queue
    @ui_current_widget
    @reports_exception()
    def load(self):
        self.throbber.show()
        self.processEvents()
        try:
            if not self.tree:
                branch, relpath = Branch.open_containing(self.filename)
                self.branch = branch
                self.encoding = get_set_encoding(self.encoding, branch)
                self.encoding_selector.encoding = self.encoding

                if self.revision is None:
                    self.tree = branch.basis_tree()
                else:
                    revision_id = self.revision[0].in_branch(branch).rev_id
                    self.tree = branch.repository.revision_tree(revision_id)
                
                self.file_id = self.tree.path2id(relpath)
            
            if not self.file_id:
                self.file_id = self.tree.path2id(self.filename)
                
            if not self.file_id:
                raise errors.BzrCommandError(
                    "%r is not present in revision %s" % (
                        self.filename, self.tree.get_revision_id()))
            
            self.tree.lock_read()
            try:
                kind = self.tree.kind(self.file_id)
                if kind == 'file':
                    text = self.tree.get_file_text(self.file_id)
                elif kind == 'symlink':
                    text = self.tree.get_symlink_target(self.file_id)
                else:
                    text = ''
            finally:
                self.tree.unlock()
            self.processEvents()

            self.text = text
            self.kind = kind
            self._create_and_show_browser(self.filename, text, kind)
        finally:
            self.throbber.hide()

    def _create_and_show_browser(self, filename, text, kind):
        """Create browser object for given file and then attach it to GUI.

        @param  filename:   filename used for differentiate between images
                            and simply binary files.
        @param  text:       raw file content.
        @param  kind:       filesystem kind: file, symlink, directory
        """
        type_, fview = self.detect_content_type(filename, text, kind)
        # update title
        title = "View " + type_
        self.set_title([gettext(title), filename])
        # create and show browser
        self.browser = fview(filename, text)
        self.vbox.insertWidget(1, self.browser, 1)
        # set focus on content
        self.browser.setFocus()

    def detect_content_type(self, relpath, text, kind='file'):
        """Return (file_type, viewer_factory) based on kind, text and relpath.
        Supported file types: text, image, binary
        """
        if kind == 'file':
            if not '\0' in text:
                return 'text file', self._create_text_view
            else:
                ext = file_extension(relpath).lower()
                image_exts = ['.'+str(i)
                    for i in QtGui.QImageReader.supportedImageFormats()]
                if ext in image_exts:
                    return 'image file', self._create_image_view
                else:
                    return 'binary file', self._create_hexdump_view
        else:
            return kind, self._create_symlink_view

    def _set_text(self, edit_widget, relpath, text, encoding=None):
        """Set plain text to widget, as unicode.

        @param edit_widget: edit widget to view the text.
        @param relpath: filename (required for syntax highlighting to detect
            file type).
        @param text: plain non-unicode text (bytes).
        @param encoding: text encoding (default: utf-8).
        """
        text = text.decode(encoding or 'utf-8', 'replace')
        edit_widget.setPlainText(text)
        highlight_document(edit_widget, relpath)

    def _create_text_view(self, relpath, text):
        """Create widget to show text files.
        @return: created widget with loaded text.
        """
        browser = LineNumberEditerFrame(self)
        edit = browser.edit
        edit.setReadOnly(True)
        edit.document().setDefaultFont(
            QtGui.QFont("Courier New,courier", edit.font().pointSize()))
        self._set_text(edit, relpath, text, self.encoding)
        self.encoding_selector.setEnabled(True)
        return browser

    def _on_encoding_changed(self, encoding):
        """Event handler for EncodingSelector.
        It sets file text to browser again with new encoding.
        """
        self.encoding = encoding
        branch = self.branch
        if branch is None:
            branch = Branch.open_containing(self.filename)[0]
        if branch:
            get_set_encoding(encoding, branch)
        self._set_text(self.browser.edit, self.filename, self.text, self.encoding)

    def _create_simple_text_browser(self):
        """Create and return simple widget to show text-like content."""
        browser = QtGui.QPlainTextEdit(self)
        browser.setReadOnly(True)
        browser.document().setDefaultFont(
            QtGui.QFont("Courier New,courier", browser.font().pointSize()))
        return browser

    def _create_symlink_view(self, relpath, target):
        """Create widget to show symlink target.
        @return: created widget with loaded content.
        """
        browser = self._create_simple_text_browser()
        browser.setPlainText('-> ' + target.decode('utf-8', 'replace'))
        return browser

    def _create_hexdump_view(self, relpath, data):
        """Create widget to show content of binary files.
        @return: created widget with loaded content.
        """
        browser = self._create_simple_text_browser()
        browser.setPlainText(hexdump(data))
        return browser

    def _create_image_view(self, relpath, data):
        """Create widget to show image file.
        @return: created widget with loaded image.
        """
        self.pixmap = QtGui.QPixmap()
        self.pixmap.loadFromData(data)
        self.item = QtGui.QGraphicsPixmapItem(self.pixmap)
        self.scene = QtGui.QGraphicsScene(self.item.boundingRect())
        self.scene.addItem(self.item)
        return QtGui.QGraphicsView(self.scene)


class QBzrViewWindow(QBzrCatWindow):
    """Show content of file/symlink from the disk."""

    def __init__(self, filename=None, encoding=None, parent=None):
        """Construct GUI.

        @param  filename:   filesystem object to view.
        @param  encoding:   use this encoding to decode text file content
                            to unicode.
        @param  parent:     parent widget.
        """
        QBzrWindow.__init__(self, [gettext("View"), filename], parent)
        self.restoreSize("cat", (780, 580))

        self.filename = filename
        self.encoding = encoding

        self.buttonbox = self.create_button_box(BTN_CLOSE)
        self.encoding_selector = self._create_encoding_selector()
        self.branch = FakeBranch()

        self.vbox = QtGui.QVBoxLayout(self.centralwidget)
        self.vbox.addStretch()
        hbox = QtGui.QHBoxLayout()
        hbox.addWidget(self.encoding_selector)
        hbox.addWidget(self.buttonbox)
        self.vbox.addLayout(hbox)

    def load(self):
        kind = osutils.file_kind(self.filename)
        text = ''
        if kind == 'file':
            f = open(self.filename, 'rb')
            try:
                text = f.read()
            finally:
                f.close()
        elif kind == 'symlink':
            text = os.readlink(self.filename)
        self.text = text
        self._create_and_show_browser(self.filename, text, kind)


class FakeBranch(object):
    """Special branch object to disable save encodings to branch.conf"""

    def __init__(self):
        pass

    def __nonzero__(self):
        return False


def cat_to_native_app(tree, relpath):
    """Extract file content to temp directory and then launch
    native application to open it.

    @param  tree:   RevisionTree object.
    @param  relpath:    path to file relative to tree root.
    @raise  KindError:  if relpath entry has not file kind.
    @return:    True if native application was launched.
    """
    file_id = tree.path2id(relpath)
    kind = tree.kind(file_id)
    if kind != 'file':
        raise KindError('cat to native application is not supported '
            'for entry of kind %r' % kind)
    # make temp file
    import os
    import tempfile
    qdir = os.path.join(tempfile.gettempdir(), 'QBzr', 'qcat')
    if not os.path.isdir(qdir):
        os.makedirs(qdir)
    basename = os.path.basename(relpath)
    fname = os.path.join(qdir, basename)
    f = open(fname, 'wb')
    tree.lock_read()
    try:
        f.write(tree.get_file_text(file_id))
    finally:
        tree.unlock()
        f.close()
    # open it
    url = QtCore.QUrl(fname)
    result = QtGui.QDesktopServices.openUrl(url)
    # now application is about to start and user will work with file
    # so we can do cleanup in "background"
    import time
    limit = time.time() - 60    # files older than 1 minute
    files = os.listdir(qdir)
    for i in files[:20]:
        if i == basename:
            continue
        fname = os.path.join(qdir, i)
        st = os.lstat(fname)
        if st.st_mtime > limit:
            continue
        try:
            os.unlink(fname)
        except (OSError, IOError):
            pass
    #
    return result


class KindError(errors.BzrError):
    pass