Source

thg / tortoisehg / hgqt / filedialogs.py

  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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
# Copyright (c) 2003-2010 LOGILAB S.A. (Paris, FRANCE).
# http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# 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.
"""
Qt4 dialogs to display hg revisions of a file
"""

import os
import difflib

from tortoisehg.util import hglib
from tortoisehg.hgqt.i18n import _
from tortoisehg.hgqt import qtlib, visdiff, filerevmodel, blockmatcher, lexers
from tortoisehg.hgqt import fileview, repoview, revpanel, revert
from tortoisehg.hgqt.qscilib import Scintilla

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.Qsci import QsciScintilla

sides = ('left', 'right')
otherside = {'left': 'right', 'right': 'left'}

class _AbstractFileDialog(QMainWindow):
    finished = pyqtSignal(int)

    def __init__(self, repo, filename, repoviewer=None):
        QMainWindow.__init__(self)
        self.repo = repo

        self.setupUi(self)
        self.setRepoViewer(repoviewer)
        self._show_rev = None

        if isinstance(filename, (unicode, QString)):
            filename = hglib.fromunicode(filename)
        self.filename = filename

        self.createActions()
        self.setupToolbars()

        self.setupViews()
        self.setupModels()

    def closeEvent(self, event):
        super(_AbstractFileDialog, self).closeEvent(event)
        self.finished.emit(0)  # mimic QDialog exit

    def setRepoViewer(self, repoviewer=None):
        self.repoviewer = repoviewer
        if repoviewer:
            repoviewer.finished.connect(lambda x: self.setRepoViewer(None))

    def reload(self):
        'Reload toolbar action handler'
        self.repo.thginvalidate()
        self.setupModels()

    def onRevisionActivated(self, rev):
        """
        Callback called when a revision is double-clicked in the revisions table
        """
        if self.repoviewer is None:
            # prevent recursive import
            from workbench import Workbench
            self.repoviewer = Workbench()
        self.repoviewer.show()
        self.repoviewer.activateWindow()
        self.repoviewer.raise_()
        self.repoviewer.showRepo(hglib.tounicode(self.repo.root))
        self.repoviewer.goto(self.repo.root, rev)

class FileLogDialog(_AbstractFileDialog):
    """
    A dialog showing a revision graph for a file.
    """
    def __init__(self, repo, filename, repoviewer=None):
        super(FileLogDialog, self).__init__(repo, filename, repoviewer)
        self._readSettings()
        self.menu = None
        self.dualmenu = None

    def closeEvent(self, event):
        self._writeSettings()
        super(FileLogDialog, self).closeEvent(event)

    def _readSettings(self):
        s = QSettings()
        s.beginGroup('filelog')
        try:
            self.textView.loadSettings(s, 'fileview')
            self.restoreGeometry(s.value('geom').toByteArray())
            self.splitter.restoreState(s.value('splitter').toByteArray())
            self.revpanel.set_expanded(s.value('revpanel.expanded').toBool())
        finally:
            s.endGroup()

    def _writeSettings(self):
        s = QSettings()
        s.beginGroup('filelog')
        try:
            self.textView.saveSettings(s, 'fileview')
            s.setValue('revpanel.expanded', self.revpanel.is_expanded())
            s.setValue('geom', self.saveGeometry())
            s.setValue('splitter', self.splitter.saveState())
        finally:
            s.endGroup()

    def setupUi(self, o):
        self.editToolbar = QToolBar(self)
        self.editToolbar.setContextMenuPolicy(Qt.PreventContextMenu)
        self.addToolBar(Qt.ToolBarArea(Qt.TopToolBarArea), self.editToolbar)
        self.actionClose = QAction(self)
        self.actionClose.setShortcuts(QKeySequence.Close)
        self.actionReload = QAction(self)
        self.actionReload.setShortcuts(QKeySequence.Refresh)
        self.editToolbar.addAction(self.actionReload)
        self.addAction(self.actionClose)

        self.splitter = QSplitter(Qt.Vertical)
        self.setCentralWidget(self.splitter)
        cs = ('fileLogDialog', _('File History Log Columns'))
        self.repoview = repoview.HgRepoView(self.repo, cs[0], cs, self.splitter)

        # It does not make sense to select more than two revisions at a time.
        # Rather than enforcing a max selection size we simply let the user
        # know when it has selected too many revisions by using the status bar
        def checkValidSelection(selected, deselected):
            selection = self.repoview.selectedRevisions()
            if len(selection) > 2:
                msg = _('Too many rows selected for menu')
            else:
                msg = ''
            self.textView.showMessage.emit(msg)
        self.repoview.revisionSelectionChanged.connect(checkValidSelection)

        self.contentframe = QFrame(self.splitter)

        vbox = QVBoxLayout()
        vbox.setSpacing(0)
        vbox.setMargin(0)
        self.contentframe.setLayout(vbox)

        self.revpanel = revpanel.RevPanelWidget(self.repo)
        self.revpanel.linkActivated.connect(self.onLinkActivated)
        vbox.addWidget(self.revpanel, 0)

        self.textView = fileview.HgFileView(self.repo, self)
        self.textView.revisionSelected.connect(self.goto)
        vbox.addWidget(self.textView, 1)

    def setupViews(self):
        self.textView.showMessage.connect(self.statusBar().showMessage)

    def setupToolbars(self):
        self.editToolbar.addSeparator()
        self.editToolbar.addAction(self.actionBack)
        self.editToolbar.addAction(self.actionForward)

    def setupModels(self):
        self.filerevmodel = filerevmodel.FileRevModel(self.repo,
                                         self.repoview.colselect[0],
                                         parent=self)
        self.repoview.setModel(self.filerevmodel)
        self.repoview.revisionSelected.connect(self.onRevisionSelected)
        self.repoview.revisionActivated.connect(self.onRevisionActivated)
        self.repoview.menuRequested.connect(self.viewMenuRequest)
        self.filerevmodel.showMessage.connect(self.statusBar().showMessage)
        self.filerevmodel.filled.connect(self.modelFilled)
        self.filerevmodel.setFilename(self.filename)

    def createActions(self):
        self.actionClose.triggered.connect(self.close)
        self.actionReload.triggered.connect(self.reload)
        self.actionReload.setIcon(qtlib.geticon('view-refresh'))

        self.actionBack = QAction(_('Back'), self, enabled=False,
                                  icon=qtlib.geticon('go-previous'))
        self.actionForward = QAction(_('Forward'), self, enabled=False,
                                     icon=qtlib.geticon('go-next'))
        self.repoview.revisionSelected.connect(self._updateHistoryActions)
        self.actionBack.triggered.connect(self.repoview.back)
        self.actionForward.triggered.connect(self.repoview.forward)

    @pyqtSlot()
    def _updateHistoryActions(self):
        self.actionBack.setEnabled(self.repoview.canGoBack())
        self.actionForward.setEnabled(self.repoview.canGoForward())

    def modelFilled(self):
        self.repoview.resizeColumns()
        if self._show_rev is not None:
            index = self.filerevmodel.indexFromRev(self._show_rev)
            self._show_rev = None
        else:
            index = self.filerevmodel.index(0,0)
        if index is not None:
            self.repoview.setCurrentIndex(index)

    @pyqtSlot(QPoint, object)
    def viewMenuRequest(self, point, selection):
        'User requested a context menu in repo view widget'
        if not selection or len(selection) > 2:
            return
        if len(selection) == 2:
            if self.dualmenu is None:
                self.dualmenu = menu = QMenu(self)
                a = menu.addAction(_('&Diff Selected Changesets'))
                a.triggered.connect(self.onVisualDiffRevs)
                a = menu.addAction(_('Diff Selected &File Revisions'))
                a.setIcon(qtlib.getmenuicon('visualdiff'))
                a.triggered.connect(self.onVisualDiffFileRevs)
            else:
                menu = self.dualmenu
        elif self.menu is None:
            self.menu = menu = QMenu(self)
            a = menu.addAction(_('&Diff Changeset to Parent'))
            a.setIcon(qtlib.getmenuicon('visualdiff'))
            a.triggered.connect(self.onVisualDiff)
            a = menu.addAction(_('Diff Changeset to &Local'))
            a.setIcon(qtlib.getmenuicon('ldiff'))
            a.triggered.connect(self.onVisualDiffToLocal)
            menu.addSeparator()
            a = menu.addAction(_('Diff &File to Parent'))
            a.setIcon(qtlib.getmenuicon('visualdiff'))
            a.triggered.connect(self.onVisualDiffFile)
            a = menu.addAction(_('Diff File to Lo&cal'))
            a.setIcon(qtlib.getmenuicon('ldiff'))
            a.triggered.connect(self.onVisualDiffFileToLocal)
            menu.addSeparator()
            a = menu.addAction(_('&View at Revision'))
            a.setIcon(qtlib.getmenuicon('view-at-revision'))
            a.triggered.connect(self.onViewFileAtRevision)
            a = menu.addAction(_('&Save at Revision...'))
            a.triggered.connect(self.onSaveFileAtRevision)
            a = menu.addAction(_('&Edit Local'))
            a.setIcon(qtlib.getmenuicon('edit-file'))
            a.triggered.connect(self.onEditLocal)
            a = menu.addAction(_('&Revert to Revision...'))
            a.setIcon(qtlib.getmenuicon('hg-revert'))
            a.triggered.connect(self.onRevertFileToRevision)
        else:
            menu = self.menu
        self.selection = selection
        menu.exec_(point)

    def onVisualDiff(self):
        opts = dict(change=self.selection[0])
        dlg = visdiff.visualdiff(self.repo.ui, self.repo, [], opts)
        if dlg:
            dlg.exec_()
            dlg.deleteLater()

    def onVisualDiffToLocal(self):
        opts = dict(rev=['rev(%d)' % self.selection[0]])
        dlg = visdiff.visualdiff(self.repo.ui, self.repo, [], opts)
        if dlg:
            dlg.exec_()
            dlg.deleteLater()

    def onVisualDiffRevs(self):
        revs = self.selection
        if len(revs) != 2:
            self.textView.showMessage.emit(_('You must select two revisions to diff'))
            return
        opts = dict(rev=revs)
        dlg = visdiff.visualdiff(self.repo.ui, self.repo, [], opts)
        if dlg:
            dlg.exec_()
            dlg.deleteLater()

    def onVisualDiffFile(self):
        rev = self.selection[0]
        paths = [self.filerevmodel.graph.filename(rev)]
        opts = dict(change=self.selection[0])
        dlg = visdiff.visualdiff(self.repo.ui, self.repo, paths, opts)
        if dlg:
            dlg.exec_()
            dlg.deleteLater()

    def onVisualDiffFileToLocal(self):
        rev = self.selection[0]
        paths = [self.filerevmodel.graph.filename(rev)]
        opts = dict(rev=['rev(%d)' % rev])
        dlg = visdiff.visualdiff(self.repo.ui, self.repo, paths, opts)
        if dlg:
            dlg.exec_()
            dlg.deleteLater()

    def onVisualDiffFileRevs(self):
        revs = self.selection
        if len(revs) != 2:
            self.textView.showMessage.emit(_('You must select two revisions to diff'))
            return
        paths = [self.filerevmodel.graph.filename(revs[0])]
        opts = dict(rev=['rev(%d)' % rev for rev in revs])
        dlg = visdiff.visualdiff(self.repo.ui, self.repo, paths, opts)
        if dlg:
            dlg.exec_()
            dlg.deleteLater()

    def onEditLocal(self):
        filenames = [self.filename]
        if not filenames:
            return
        qtlib.editfiles(self.repo, filenames, parent=self)

    def onRevertFileToRevision(self):
        rev = self.selection[0]
        if rev is None:
            rev = self.repo['.'].rev()
        fileSelection = [self.filerevmodel.graph.filename(rev)]
        if len(fileSelection) == 0:
            return
        dlg = revert.RevertDialog(self.repo, fileSelection, rev, self)
        if dlg:
            dlg.exec_()
            dlg.deleteLater()

    def onViewFileAtRevision(self):
        rev = self.selection[0]
        filenames = [self.filerevmodel.graph.filename(rev)]
        if not filenames:
            return
        if rev is None:
            qtlib.editfiles(self.repo, filenames, parent=self)
        else:
            base, _ = visdiff.snapshot(self.repo, filenames, self.repo[rev])
            files = [os.path.join(base, filename)
                     for filename in filenames]
            qtlib.editfiles(self.repo, files, parent=self)

    def onSaveFileAtRevision(self, rev):
        rev = self.selection[0]
        files = [self.filerevmodel.graph.filename(rev)]
        if not files or rev is None:
            return
        else:
            qtlib.savefiles(self.repo, files, rev, parent=self)

    @pyqtSlot(QString)
    def onLinkActivated(self, link):
        link = unicode(link)
        if ':' in link:
            scheme, param = link.split(':', 1)
            if scheme == 'cset':
                rev = self.repo[hglib.fromunicode(param)].rev()
                return self.goto(rev)
        QDesktopServices.openUrl(QUrl(link))

    def onRevisionSelected(self, rev):
        pos = self.textView.verticalScrollBar().value()
        ctx = self.filerevmodel.repo.changectx(rev)
        self.textView.setContext(ctx)
        self.textView.displayFile(self.filerevmodel.graph.filename(rev), None)
        self.textView.verticalScrollBar().setValue(pos)
        self.revpanel.set_revision(rev)
        self.revpanel.update(repo = self.repo)

    def goto(self, rev):
        index = self.filerevmodel.indexFromRev(rev)
        if index is not None:
            self.repoview.setCurrentIndex(index)
        else:
            self._show_rev = rev

    def reload(self):
        self.repoview.saveSettings()
        super(FileLogDialog, self).reload()

class FileDiffDialog(_AbstractFileDialog):
    """
    Qt4 dialog to display diffs between different mercurial revisions of a file.
    """
    def __init__(self, repo, filename, repoviewer=None):
        super(FileDiffDialog, self).__init__(repo, filename, repoviewer)
        self._readSettings()
        self.menu = None

    def closeEvent(self, event):
        self._writeSettings()
        super(FileDiffDialog, self).closeEvent(event)

    def _readSettings(self):
        s = QSettings()
        s.beginGroup('filediff')
        try:
            self.restoreGeometry(s.value('geom').toByteArray())
            self.splitter.restoreState(s.value('splitter').toByteArray())
        finally:
            s.endGroup()

    def _writeSettings(self):
        s = QSettings()
        s.beginGroup('filediff')
        try:
            s.setValue('geom', self.saveGeometry())
            s.setValue('splitter', self.splitter.saveState())
        finally:
            s.endGroup()

    def setupUi(self, o):
        self.editToolbar = QToolBar(self)
        self.editToolbar.setContextMenuPolicy(Qt.PreventContextMenu)
        self.addToolBar(Qt.ToolBarArea(Qt.TopToolBarArea), self.editToolbar)
        self.actionClose = QAction(self)
        self.actionClose.setShortcuts(QKeySequence.Close)
        self.actionReload = QAction(self)
        self.actionReload.setShortcuts(QKeySequence.Refresh)
        self.editToolbar.addAction(self.actionReload)
        self.addAction(self.actionClose)

        def layouttowidget(layout):
            w = QWidget()
            w.setLayout(layout)
            return w

        self.splitter = QSplitter(Qt.Vertical)
        self.setCentralWidget(self.splitter)
        self.horizontalLayout = QHBoxLayout()
        cs = ('fileDiffDialogLeft', _('File Differences Log Columns'))
        self.tableView_revisions_left = repoview.HgRepoView(self.repo, cs[0],
                                                            cs, self)
        self.tableView_revisions_right = repoview.HgRepoView(self.repo,
                                                             'fileDiffDialogRight',
                                                             cs, self)
        self.horizontalLayout.addWidget(self.tableView_revisions_left)
        self.horizontalLayout.addWidget(self.tableView_revisions_right)
        self.tableView_revisions_right.setSelectionMode(QAbstractItemView.SingleSelection)
        self.tableView_revisions_left.setSelectionMode(QAbstractItemView.SingleSelection)
        self.frame = QFrame()
        self.splitter.addWidget(layouttowidget(self.horizontalLayout))
        self.splitter.addWidget(self.frame)

    #@pyqtSlot(QPoint)
    def fileViewMenuRequest(self, point):
        sci = self.sender()
        menu = sci.createStandardContextMenu()
        point = sci.viewport().mapToGlobal(point)
        menu.exec_(point)

    def setupViews(self):
        self.tableViews = {'left': self.tableView_revisions_left,
                           'right': self.tableView_revisions_right}
        # viewers are Scintilla editors
        self.viewers = {}
        # block are diff-block displayers
        self.block = {}
        self.diffblock = blockmatcher.BlockMatch(self.frame)
        lay = QHBoxLayout(self.frame)
        lay.setSpacing(0)
        lay.setContentsMargins(0, 0, 0, 0)

        try:
            contents = open(self.repo.wjoin(self.filename), "rb").read(1024)
            lexer = lexers.get_lexer(self.filename, contents, self)
        except Exception:
            lexer = None

        for side, idx  in (('left', 0), ('right', 3)):
            sci = Scintilla(self.frame)
            sci.verticalScrollBar().setFocusPolicy(Qt.StrongFocus)
            sci.setFocusProxy(sci.verticalScrollBar())
            sci.verticalScrollBar().installEventFilter(self)

            sci.setContextMenuPolicy(Qt.CustomContextMenu)
            sci.customContextMenuRequested.connect(self.fileViewMenuRequest)

            sci.setFrameShape(QFrame.NoFrame)
            sci.setMarginLineNumbers(1, True)
            sci.SendScintilla(sci.SCI_SETSELEOLFILLED, True)

            sci.setLexer(lexer)
            if lexer is None:
                sci.setFont(qtlib.getfont('fontdiff').font())

            sci.setReadOnly(True)
            sci.setUtf8(True)
            lay.addWidget(sci)

            # hide margin 0 (markers)
            sci.SendScintilla(sci.SCI_SETMARGINTYPEN, 0, 0)
            sci.SendScintilla(sci.SCI_SETMARGINWIDTHN, 0, 0)
            # setup margin 1 for line numbers only
            sci.SendScintilla(sci.SCI_SETMARGINTYPEN, 1, 1)
            sci.SendScintilla(sci.SCI_SETMARGINWIDTHN, 1, 20)
            sci.SendScintilla(sci.SCI_SETMARGINMASKN, 1, 0)

            # define markers for colorize zones of diff
            self.markerplus = sci.markerDefine(QsciScintilla.Background)
            sci.SendScintilla(sci.SCI_MARKERSETBACK, self.markerplus, 0xB0FFA0)
            self.markerminus = sci.markerDefine(QsciScintilla.Background)
            sci.SendScintilla(sci.SCI_MARKERSETBACK, self.markerminus, 0xA0A0FF)
            self.markertriangle = sci.markerDefine(QsciScintilla.Background)
            sci.SendScintilla(sci.SCI_MARKERSETBACK, self.markertriangle, 0xFFA0A0)

            self.viewers[side] = sci
            blk = blockmatcher.BlockList(self.frame)
            blk.linkScrollBar(sci.verticalScrollBar())
            self.diffblock.linkScrollBar(sci.verticalScrollBar(), side)
            lay.insertWidget(idx, blk)
            self.block[side] = blk
        lay.insertWidget(2, self.diffblock)

        for side in sides:
            table = getattr(self, 'tableView_revisions_%s' % side)
            table.setTabKeyNavigation(False)
            #table.installEventFilter(self)
            table.revisionSelected.connect(self.onRevisionSelected)
            table.revisionActivated.connect(self.onRevisionActivated)

            self.viewers[side].verticalScrollBar().valueChanged.connect(
                    lambda value, side=side: self.sbar_changed(value, side, 'vertical'))
            self.viewers[side].horizontalScrollBar().valueChanged.connect(
                    lambda value, side=side: self.sbar_changed(value, side, 'horizontal'))

        self.setTabOrder(table, self.viewers['left'])
        self.setTabOrder(self.viewers['left'], self.viewers['right'])

        # timer used to fill viewers with diff block markers during GUI idle time
        self.timer = QTimer()
        self.timer.setSingleShot(False)
        self.timer.timeout.connect(self.idle_fill_files)

    def setupModels(self):
        self.filedata = {'left': None, 'right': None}
        self._invbarchanged = False
        self.filerevmodel = filerevmodel.FileRevModel(self.repo,
                                         self.tableView_revisions_left.colselect[0],
                                         self.filename, parent=self)
        self.filerevmodel.filled.connect(self.modelFilled)
        self.tableView_revisions_left.setModel(self.filerevmodel)
        self.tableView_revisions_right.setModel(self.filerevmodel)
        self.tableView_revisions_left.menuRequested.connect(self.viewMenuRequest)
        self.tableView_revisions_right.menuRequested.connect(self.viewMenuRequest)

    def createActions(self):
        self.actionClose.triggered.connect(self.close)
        self.actionReload.triggered.connect(self.reload)
        self.actionReload.setIcon(qtlib.geticon('view-refresh'))

        self.actionNextDiff = QAction(qtlib.geticon('go-down'),
                                      _('Next diff'), self)
        self.actionNextDiff.setShortcut('Alt+Down')
        self.actionNextDiff.triggered.connect(self.nextDiff)

        self.actionPrevDiff = QAction(qtlib.geticon('go-up'),
                                      _('Previous diff'), self)
        self.actionPrevDiff.setShortcut('Alt+Up')
        self.actionPrevDiff.triggered.connect(self.prevDiff)

        self.actionNextDiff.setEnabled(False)
        self.actionPrevDiff.setEnabled(False)

    def setupToolbars(self):
        self.editToolbar.addSeparator()
        self.editToolbar.addAction(self.actionNextDiff)
        self.editToolbar.addAction(self.actionPrevDiff)

    def modelFilled(self):
        self.tableView_revisions_left.resizeColumns()
        self.tableView_revisions_right.resizeColumns()
        if self._show_rev is not None:
            self.goto(self._show_rev)
            self._show_rev = None
        elif len(self.filerevmodel.graph):
            self.goto(self.filerevmodel.graph[0].rev)

    def onRevisionSelected(self, rev):
        if rev is None or rev not in self.filerevmodel.graph.nodesdict:
            return
        if self.sender() is self.tableView_revisions_right:
            side = 'right'
        else:
            side = 'left'
        path = self.filerevmodel.graph.nodesdict[rev].extra[0]
        fc = self.repo.changectx(rev).filectx(path)
        data = hglib.tounicode(fc.data())
        self.filedata[side] = data.splitlines()
        self.update_diff(keeppos=otherside[side])

    def goto(self, rev):
        index = self.filerevmodel.indexFromRev(rev)
        if index is not None:
            if index.row() == 0:
                index = self.filerevmodel.index(1, 0)
            self.tableView_revisions_left.setCurrentIndex(index)
            index = self.filerevmodel.index(0, 0)
            self.tableView_revisions_right.setCurrentIndex(index)
        else:
            self._show_rev = rev

    def setDiffNavActions(self, pos=0):
        hasdiff = (self.diffblock.nDiffs() > 0)
        self.actionNextDiff.setEnabled(hasdiff and pos != 1)
        self.actionPrevDiff.setEnabled(hasdiff and pos != -1)

    def nextDiff(self):
        self.setDiffNavActions(self.diffblock.nextDiff())

    def prevDiff(self):
        self.setDiffNavActions(self.diffblock.prevDiff())

    def update_page_steps(self, keeppos=None):
        for side in sides:
            self.block[side].syncPageStep()
        self.diffblock.syncPageStep()
        if keeppos:
            side, pos = keeppos
            self.viewers[side].verticalScrollBar().setValue(pos)

    def idle_fill_files(self):
        # we make a burst of diff-lines computed at once, but we
        # disable GUI updates for efficiency reasons, then only
        # refresh GUI at the end of the burst
        for side in sides:
            self.viewers[side].setUpdatesEnabled(False)
            self.block[side].setUpdatesEnabled(False)
        self.diffblock.setUpdatesEnabled(False)

        for n in range(30): # burst pool
            if self._diff is None or not self._diff.get_opcodes():
                self._diff = None
                self.timer.stop()
                self.setDiffNavActions(-1)
                break

            tag, alo, ahi, blo, bhi = self._diff.get_opcodes().pop(0)

            w = self.viewers['left']
            cposl = w.SendScintilla(w.SCI_GETENDSTYLED)
            w = self.viewers['right']
            cposr = w.SendScintilla(w.SCI_GETENDSTYLED)
            if tag == 'replace':
                self.block['left'].addBlock('x', alo, ahi)
                self.block['right'].addBlock('x', blo, bhi)
                self.diffblock.addBlock('x', alo, ahi, blo, bhi)

                w = self.viewers['left']
                for i in range(alo, ahi):
                    w.markerAdd(i, self.markertriangle)

                w = self.viewers['right']
                for i in range(blo, bhi):
                    w.markerAdd(i, self.markertriangle)

            elif tag == 'delete':
                self.block['left'].addBlock('-', alo, ahi)
                self.diffblock.addBlock('-', alo, ahi, blo, bhi)

                w = self.viewers['left']
                for i in range(alo, ahi):
                    w.markerAdd(i, self.markerminus)

            elif tag == 'insert':
                self.block['right'].addBlock('+', blo, bhi)
                self.diffblock.addBlock('+', alo, ahi, blo, bhi)

                w = self.viewers['right']
                for i in range(blo, bhi):
                    w.markerAdd(i, self.markerplus)

            elif tag == 'equal':
                pass

            else:
                raise ValueError, 'unknown tag %r' % (tag,)

        # ok, let's enable GUI refresh for code viewers and diff-block displayers
        for side in sides:
            self.viewers[side].setUpdatesEnabled(True)
            self.block[side].setUpdatesEnabled(True)
        self.diffblock.setUpdatesEnabled(True)

    def update_diff(self, keeppos=None):
        """
        Recompute the diff, display files and starts the timer
        responsible for filling diff markers
        """
        if keeppos:
            pos = self.viewers[keeppos].verticalScrollBar().value()
            keeppos = (keeppos, pos)

        for side in sides:
            self.viewers[side].clear()
            self.block[side].clear()
        self.diffblock.clear()

        if None not in self.filedata.values():
            if self.timer.isActive():
                self.timer.stop()
            for side in sides:
                self.viewers[side].setMarginWidth(1, "00%s" % len(self.filedata[side]))

            self._diff = difflib.SequenceMatcher(None, self.filedata['left'],
                                                 self.filedata['right'])
            blocks = self._diff.get_opcodes()[:]

            self._diffmatch = {'left': [x[1:3] for x in blocks],
                               'right': [x[3:5] for x in blocks]}
            for side in sides:
                self.viewers[side].setText(u'\n'.join(self.filedata[side]))
            self.update_page_steps(keeppos)
            self.timer.start()

    def sbar_changed(self, value, side, bartype='vertical'):
        """
        Callback called when a scrollbar of a file viewer
        is changed, so we can update the position of the other file
        viewer.
        """
        if self._invbarchanged or not hasattr(self, '_diffmatch'):
            # prevent loops in changes (left -> right -> left ...)
            return
        self._invbarchanged = True
        oside = otherside[side]

        for i, (lo, hi) in enumerate(self._diffmatch[side]):
            if lo <= value < hi:
                break
        dv = value - lo

        blo, bhi = self._diffmatch[oside][i]
        if bartype == 'vertical':
            vbar = self.viewers[oside].verticalScrollBar()
        else:
            vbar = self.viewers[oside].horizontalScrollBar()
        if (dv) < (bhi - blo):
            bvalue = blo + dv
        else:
            bvalue = bhi
        vbar.setValue(bvalue)
        self._invbarchanged = False

    def reload(self):
        self.tableView_revisions_left.saveSettings()
        self.tableView_revisions_right.saveSettings()
        super(FileDiffDialog, self).reload()

    @pyqtSlot(QPoint, object)
    def viewMenuRequest(self, point, selection):
        'User requested a context menu in repo view widget'
        if not selection:
            return
        if self.menu is None:
            self.menu = menu = QMenu(self)
            a = menu.addAction(_('&Diff to Parent'))
            a.setIcon(qtlib.getmenuicon('visualdiff'))
            a.triggered.connect(self.onVisualDiff)
            a = menu.addAction(_('Diff to &Local'))
            a.setIcon(qtlib.getmenuicon('ldiff'))
            a.triggered.connect(self.onVisualDiffToLocal)
            menu.addSeparator()
            a = menu.addAction(_('Diff &File to Parent'))
            a.setIcon(qtlib.getmenuicon('visualdiff'))
            a.triggered.connect(self.onVisualDiffFile)
            a = menu.addAction(_('Diff File to Lo&cal'))
            a.setIcon(qtlib.getmenuicon('ldiff'))
            a.triggered.connect(self.onVisualDiffFileToLocal)
            menu.addSeparator()
            a = menu.addAction(_('&View at Revision'))
            a.setIcon(qtlib.getmenuicon('view-at-revision'))
            a.triggered.connect(self.onViewFileAtRevision)
            a = menu.addAction(_('&Save at Revision...'))
            a.triggered.connect(self.onSaveFileAtRevision)
            a = menu.addAction(_('&Edit Local'))
            a.setIcon(qtlib.getmenuicon('edit-file'))
            a.triggered.connect(self.onEditLocal)
            a = menu.addAction(_('&Revert to Revision...'))
            a.setIcon(qtlib.getmenuicon('hg-revert'))
            a.triggered.connect(self.onRevertFileToRevision)
        self.selection = selection
        self.menu.exec_(point)

    def onVisualDiff(self):
        opts = dict(change=self.selection[0])
        dlg = visdiff.visualdiff(self.repo.ui, self.repo, [], opts)
        if dlg:
            dlg.exec_()
            dlg.deleteLater()

    def onVisualDiffToLocal(self):
        opts = dict(rev=['rev(%d)' % self.selection[0]])
        dlg = visdiff.visualdiff(self.repo.ui, self.repo, [], opts)
        if dlg:
            dlg.exec_()
            dlg.deleteLater()

    def onVisualDiffFile(self):
        rev = self.selection[0]
        paths = [self.filerevmodel.graph.filename(rev)]
        opts = dict(change=self.selection[0])
        dlg = visdiff.visualdiff(self.repo.ui, self.repo, paths, opts)
        if dlg:
            dlg.exec_()
            dlg.deleteLater()

    def onVisualDiffFileToLocal(self):
        rev = self.selection[0]
        paths = [self.filerevmodel.graph.filename(rev)]
        opts = dict(rev=['rev(%d)' % rev])
        dlg = visdiff.visualdiff(self.repo.ui, self.repo, paths, opts)
        if dlg:
            dlg.exec_()
            dlg.deleteLater()

    def onEditLocal(self):
        filenames = [self.filename]
        if not filenames:
            return
        qtlib.editfiles(self.repo, filenames, parent=self)

    def onRevertFileToRevision(self):
        rev = self.selection[0]
        if rev is None:
            rev = self.repo['.'].rev()
        fileSelection = [self.filerevmodel.graph.filename(rev)]
        if len(fileSelection) == 0:
            return
        dlg = revert.RevertDialog(self.repo, fileSelection, rev, self)
        if dlg:
            dlg.exec_()
            dlg.deleteLater()

    def onViewFileAtRevision(self):
        rev = self.selection[0]
        filenames = [self.filerevmodel.graph.filename(rev)]
        if not filenames:
            return
        if rev is None:
            qtlib.editfiles(self.repo, filenames, parent=self)
        else:
            base, _ = visdiff.snapshot(self.repo, filenames, self.repo[rev])
            files = [os.path.join(base, filename)
                     for filename in filenames]
            qtlib.editfiles(self.repo, files, parent=self)

    def onSaveFileAtRevision(self, rev):
        rev = self.selection[0]
        files = [self.filerevmodel.graph.filename(rev)]
        if not files or rev is None:
            return
        else:
            qtlib.savefiles(self.repo, files, rev, parent=self)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.