Mercurial and Git clients can push and pull from this alias URL to interact with this repository. You can change to which repository an alias points by going to the Aliases link on the project page.
# annotate.py - File annotation widget## Copyright 2010 Steve Borho <steve@borho.org>## This software may be used and distributed according to the terms of the# GNU General Public License version 2, incorporated herein by reference.importosfrommercurialimportui,error,utilfromtortoisehg.hgqtimportvisdiff,qtlib,qscilib,thgrepo,lexersfromtortoisehg.utilimportpaths,hglib,colormap,thread2fromtortoisehg.hgqt.i18nimport_fromtortoisehg.hgqt.grepimportSearchWidgetfromPyQt4.QtCoreimport*fromPyQt4.QtGuiimport*fromPyQt4.QsciimportQsciScintilla,QsciStyle# Technical Debt# Pass search parameters to grep# forward/backward history buttons# menu options for viewing appropriate changesetsclassAnnotateView(qscilib.Scintilla):revisionHint=pyqtSignal(QString)searchRequested=pyqtSignal(QString)"""Emitted (pattern) when user request to search content"""editSelected=pyqtSignal(unicode,object,int)"""Emitted (path, rev, line) when user requests to open editor"""grepRequested=pyqtSignal(QString,dict)"""Emitted (pattern, **opts) when user request to search changelog"""sourceChanged=pyqtSignal(unicode,object)"""Emitted (path, rev) when the content source changed"""def__init__(self,repo,parent=None,**opts):super(AnnotateView,self).__init__(parent)self.setReadOnly(True)self.setMarginLineNumbers(1,True)self.setMarginType(2,QsciScintilla.TextMarginRightJustified)self.setMouseTracking(True)self.setFont(qtlib.getfont('fontdiff').font())self.setContextMenuPolicy(Qt.CustomContextMenu)self.customContextMenuRequested.connect(self.menuRequest)self.repo=repoself.repo.configChanged.connect(self.configChanged)self.configChanged()self._rev=Noneself.annfile=Noneself._annotation_enabled=bool(opts.get('annotationEnabled',False))self._links=[]# by lineself._revmarkers={}# by revself._lastrev=Noneself._thread=_AnnotateThread(self)self._thread.finished.connect(self.fillModel)defconfigChanged(self):self.setIndentationWidth(self.repo.tabwidth)self.setTabWidth(self.repo.tabwidth)defkeyPressEvent(self,event):ifevent.key()==Qt.Key_Escape:self._thread.abort()returnreturnsuper(AnnotateView,self).keyPressEvent(event)defmouseMoveEvent(self,event):self._emitRevisionHintAtLine(self.lineAt(event.pos()))super(AnnotateView,self).mouseMoveEvent(event)def_emitRevisionHintAtLine(self,line):ifline<0:returntry:fctx=self._links[line][0]iffctx.rev()!=self._lastrev:s=hglib.get_revision_desc(fctx,hglib.fromunicode(self.annfile))self.revisionHint.emit(s)self._lastrev=fctx.rev()exceptIndexError:pass@pyqtSlot(QPoint)defmenuRequest(self,point):menu=self.createStandardContextMenu()line=self.lineAt(point)point=self.mapToGlobal(point)ifline<0ornotself.isAnnotationEnabled():returnmenu.exec_(point)fctx,line=self._links[line]data=[hglib.tounicode(fctx.path()),fctx.rev(),line]ifself.hasSelectedText():selection=self.selectedText()defsreq(**opts):returnlambda:self.grepRequested.emit(selection,opts)defsann():self.searchRequested.emit(selection)menu.addSeparator()forname,funcin[(_('Search in original revision'),sreq(rev=fctx.rev())),(_('Search in working revision'),sreq(rev='.')),(_('Search in current annotation'),sann),(_('Search in history'),sreq(all=True))]:defadd(name,func):action=menu.addAction(name)action.triggered.connect(func)add(name,func)defannorig():self.setSource(*data)defeditorig():self.editSelected.emit(*data)menu.addSeparator()forname,funcin[(_('Annotate originating revision'),annorig),(_('View originating revision'),editorig)]:defadd(name,func):action=menu.addAction(name)action.triggered.connect(func)add(name,func)forpfctxinfctx.parents():pdata=[hglib.tounicode(pfctx.path()),pfctx.changectx().rev(),line]defannparent(data):self.setSource(*data)defeditparent(data):self.editSelected.emit(*data)forname,funcin[(_('Annotate parent revision %d')%pdata[1],annparent),(_('View parent revision %d')%pdata[1],editparent)]:defadd(name,func):action=menu.addAction(name)action.data=pdataaction.run=lambda:func(action.data)action.triggered.connect(action.run)add(name,func)menu.exec_(point)@propertydefrev(self):"""Returns the current revision number"""returnself._rev@pyqtSlot(unicode,object,int)defsetSource(self,wfile,rev,line=None):"""Change the content to the specified file at rev [unicode] line is counted from 1. """ifself.annfile==wfileandself.rev==rev:ifline:self.setCursorPosition(int(line)-1,0)returntry:ctx=self.repo[rev]fctx=ctx[hglib.fromunicode(wfile)]excepterror.LookupError: qtlib.ErrorMsgBox(_('Unable to annotate'),
_('%s is not found in revision %d') % (wfile, ctx.rev()))
return
- self._rev = ctx.rev()- self.clear()- self.annfile = wfile- if util.binary(fctx.data()):
- self.setText(_('File is binary.\n'))
++ if fctx._filelog.rawsize(fctx.filerev()) > ctx._repo.maxdiff:
+ self.setText(_('File or diffs not displayed: ') + \+ _('File is larger than the specified max size.\n'))
else:
- self.setText(hglib.tounicode(fctx.data()))
- if line:
- self.setCursorPosition(int(line) - 1, 0)
- self._updatelexer(fctx)
- self._updatemarginwidth()
- self.sourceChanged.emit(wfile, self._rev)
- self._updateannotation()
+ self._rev = ctx.rev()+ self.clear()+ self.annfile = wfile+ if util.binary(fctx.data()):+ self.setText(_('File is binary.\n'))+ else:+ self.setText(hglib.tounicode(fctx.data()))
+ if line:
+self.setCursorPosition(int(line) - 1, 0)
+self._updatelexer(fctx)
+self._updatemarginwidth()
+ self.sourceChanged.emit(wfile, self._rev)
+self._updateannotation()
def _updateannotation(self):
if not self.isAnnotationEnabled() or not self.annfile:
returnctx=self.repo[self._rev]fctx=ctx[hglib.fromunicode(self.annfile)]ifutil.binary(fctx.data()):returnself._thread.abort()self._thread.start(fctx)@pyqtSlot()deffillModel(self):self._thread.wait()ifself._thread.dataisNone:returnself._links=list(self._thread.data)self._updaterevmargin()self._updatemarkers()self._updatemarginwidth()defclear(self):super(AnnotateView,self).clear()self.clearMarginText()self.markerDeleteAll()self.annfile=None@pyqtSlot(bool)defsetAnnotationEnabled(self,enabled):"""Enable / disable annotation"""enabled=bool(enabled)ifenabled==self.isAnnotationEnabled():returnself._annotation_enabled=enabledself._updateannotation()self._updatemarginwidth()self.setMouseTracking(enabled)ifnotself.isAnnotationEnabled():self.annfile=Noneself.markerDeleteAll()defisAnnotationEnabled(self):"""True if annotation enabled and available"""ifself.revisNone:returnFalse# annotate working copy is not supportedreturnself._annotation_enableddef_updatelexer(self,fctx):"""Update the lexer according to the given file"""lex=lexers.get_lexer(fctx.path(),hglib.tounicode(fctx.data()),self)self.setLexer(lex)def_updaterevmargin(self):"""Update the content of margin area showing revisions"""s=self._margin_style# Workaround to set style of the current sci widget.# QsciStyle sends style data only to the first sci widget.# See qscintilla2/Qt4/qscistyle.cppself.SendScintilla(QsciScintilla.SCI_STYLESETBACK,s.style(),s.paper())self.SendScintilla(QsciScintilla.SCI_STYLESETFONT,s.style(),s.font().family().toAscii().data())self.SendScintilla(QsciScintilla.SCI_STYLESETSIZE,s.style(),s.font().pointSize())fori,(fctx,_origline)inenumerate(self._links):self.setMarginText(i,str(fctx.rev()),s)def_updatemarkers(self):"""Update markers which colorizes each line"""self._redefinemarkers()fori,(fctx,_origline)inenumerate(self._links):m=self._revmarkers.get(fctx.rev())ifmisnotNone:self.markerAdd(i,m)def_redefinemarkers(self):"""Redefine line markers according to the current revs"""curdate=self.repo[self._rev].date()[0]# make sure to colorize at least 1 yearmindate=curdate-365*24*60*60self._revmarkers.clear()filectxs=iter(fctxforfctx,_origlineinself._links)palette=colormap.makeannotatepalette(filectxs,curdate,maxcolors=32,maxhues=8,maxsaturations=16,mindate=mindate)fori,(color,fctxs)inenumerate(palette.iteritems()):self.markerDefine(QsciScintilla.Background,i)self.setMarkerBackgroundColor(QColor(color),i)forfctxinfctxs:self._revmarkers[fctx.rev()]=i@util.propertycachedef_margin_style(self):"""Style for margin area"""s=QsciStyle()s.setPaper(QApplication.palette().color(QPalette.Window))s.setFont(self.font())returns@pyqtSlot()def_updatemarginwidth(self):self.setMarginsFont(self.font())deflentext(s):return'M'*(len(str(s))+2)# 2 for marginself.setMarginWidth(1,lentext(self.lines()))ifself.isAnnotationEnabled()andself._links:maxrev=max(fctx.rev()forfctx,_origlineinself._links)self.setMarginWidth(2,lentext(maxrev))else:self.setMarginWidth(2,0)class_AnnotateThread(QThread):'Background thread for annotating a file at a revision'def__init__(self,parent=None):super(_AnnotateThread,self).__init__(parent)self._threadid=None@pyqtSlot(object)defstart(self,fctx):self._fctx=fctxsuper(_AnnotateThread,self).start()self.data=None@pyqtSlot()defabort(self):ifself._threadidisNone:returntry:thread2._async_raise(self._threadid,KeyboardInterrupt)self.wait()exceptValueError:passdefrun(self):assertself.currentThread()!=qApp.thread()self._threadid=self.currentThreadId()try:data=[]for(fctx,line),_textinself._fctx.annotate(True,True):data.append((fctx,line))self.data=dataexceptKeyboardInterrupt:passfinally:self._threadid=Nonedelself._fctxclassAnnotateDialog(QMainWindow):def__init__(self,*pats,**opts):super(AnnotateDialog,self).__init__(opts.get('parent'),Qt.Window)root=opts.get('root')orpaths.find_root()repo=thgrepo.repository(ui.ui(),path=root)# TODO: handle repo not foundav=AnnotateView(repo,self,annotationEnabled=True)self.setCentralWidget(av)self.av=avstatus=QStatusBar()self.setStatusBar(status)av.revisionHint.connect(status.showMessage)av.editSelected.connect(self.editSelected)av.grepRequested.connect(self._openSearchWidget)self._searchbar=qscilib.SearchToolBar()self.addToolBar(self._searchbar)self._searchbar.setPattern(hglib.tounicode(opts.get('pattern','')))self._searchbar.searchRequested.connect(self.av.find)self._searchbar.conditionChanged.connect(self.av.highlightText)av.searchRequested.connect(self._searchbar.search)QShortcut(QKeySequence.Find,self,lambda:self._searchbar.setFocus(Qt.OtherFocusReason))self.av.sourceChanged.connect(lambda*args:self.setWindowTitle(_('Annotate %s@%d')%args))self.searchwidget=opts.get('searchwidget')self.opts=optsline=opts.get('line')iflineandisinstance(line,str):line=int(line)self.repo=repoself.restoreSettings()# run heavy operation after the dialog visiblepath=hglib.tounicode(pats[0])rev=opts.get('rev')or'.'QTimer.singleShot(0,lambda:av.setSource(path,rev,line))defcloseEvent(self,event):self.storeSettings()super(AnnotateDialog,self).closeEvent(event)defeditSelected(self,wfile,rev,line):pattern=hglib.fromunicode(self._searchbar._le.text())orNonewfile=hglib.fromunicode(wfile)repo=self.repotry:ctx=repo[rev]fctx=ctx[wfile]exceptException,e:self.statusBar().showMessage(hglib.tounicode(str(e)))base,_=visdiff.snapshot(repo,[wfile],repo[rev])files=[os.path.join(base,wfile)]qtlib.editfiles(repo,files,line,pattern,self)@pyqtSlot(unicode,dict)def_openSearchWidget(self,pattern,opts):opts=dict((str(k),str(v))fork,vinopts.iteritems())ifself.searchwidgetisNone:self.searchwidget=SearchWidget([pattern],repo=self.repo,**opts)self.searchwidget.show()else:self.searchwidget.setSearch(pattern,**opts)self.searchwidget.show()self.searchwidget.raise_()defstoreSettings(self):s=QSettings()s.setValue('annotate/geom',self.saveGeometry())self.av.saveSettings(s,'annotate/av')defrestoreSettings(self):s=QSettings()self.restoreGeometry(s.value('annotate/geom').toByteArray())self.av.loadSettings(s,'annotate/av')defrun(ui,*pats,**opts):pats=hglib.canonpaths(pats)returnAnnotateDialog(*pats,**opts)
Attach a Trello Card
Add a tag
Your session has expired
You are no longer logged in. Please log in and try your request again.
Filter RSS Feed
This RSS feed URL allows you to see the contents of your current filter using any feed reader.
This link includes a special authentication token. If you share the URL with anyone else, they can see this RSS feed's activity. You can disable these tokens when needed.
Your current filter is unsaved; changing it won't affect this RSS feed.