3 # Copyright (c) 2005 Fredrik Kuivinen <freku045@student.liu.se>
4 # Copyright (c) 2005 Mark Williamson <mark.williamson@cl.cam.ac.uk>
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License version 2 as
8 # published by the Free Software Foundation.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 import sys
, math
, random
, qt
, os
, re
, signal
, sets
21 from optparse
import OptionParser
22 from commit
import CommitDialog
24 # Determine semantics according to executable name. Default to git.
25 if os
.path
.basename(sys
.argv
[0]) == 'hgct':
30 qconnect
= qt
.QObject
.connect
37 class MyListItem(qt
.QCheckListItem
):
38 def __init__(self
, parent
, file, commitMsg
= False):
39 qt
.QCheckListItem
.__init
__(self
, parent
, file.text
, qt
.QCheckListItem
.CheckBox
)
41 self
.commitMsg
= commitMsg
43 def compare(self
, item
, col
, asc
):
55 return cmp(self
.file.srcName
, item
.file.srcName
)
57 def paintCell(self
, p
, cg
, col
, w
, a
):
59 qt
.QListViewItem
.paintCell(self
, p
, cg
, col
, w
, a
)
61 qt
.QCheckListItem
.paintCell(self
, p
, cg
, col
, w
, a
)
64 return self
.state() == qt
.QCheckListItem
.On
66 def setSelected(self
, s
):
68 self
.setState(qt
.QCheckListItem
.On
)
70 self
.setState(qt
.QCheckListItem
.Off
)
72 class MyListView(qt
.QListView
):
73 def __init__(self
, parent
=None, name
=None):
74 qt
.QListView
.__init
__(self
, parent
, name
)
77 return ListViewIterator(self
)
79 class ListViewIterator
:
80 def __init__(self
, listview
):
81 self
.it
= qt
.QListViewItemIterator(listview
)
84 cur
= self
.it
.current()
97 class MainWidget(qt
.QMainWindow
):
98 def __init__(self
, options
, parent
=None, name
=None):
99 qt
.QMainWindow
.__init
__(self
, parent
, name
)
100 self
.setCaption(applicationName
)
103 splitter
= qt
.QSplitter(Qt
.Vertical
, self
)
104 self
.setCentralWidget(splitter
)
105 self
.splitter
= splitter
107 # The file list and file filter widgets are part of this layout widget.
108 self
.filesLayout
= qt
.QVBox(splitter
)
111 fW
= MyListView(self
.filesLayout
)
114 fW
.setSelectionMode(qt
.QListView
.NoSelection
)
115 fW
.addColumn('Description')
116 fW
.setResizeMode(qt
.QListView
.AllColumns
)
119 self
.filterLayout
= qt
.QHBox(self
.filesLayout
)
120 self
.filterClear
= qt
.QPushButton("&Clear", self
.filterLayout
)
121 self
.filterLabel
= qt
.QLabel(" File filter: ", self
.filterLayout
)
122 qconnect(self
.filterClear
, qt
.SIGNAL("clicked()"), self
.clearFilter
)
123 self
.filter = qt
.QLineEdit(self
.filterLayout
)
124 self
.filterLabel
.setBuddy(self
.filter)
126 qconnect(self
.filter, qt
.SIGNAL("textChanged(const QString&)"), self
.updateFilter
)
128 self
.newCurLambda
= lambda i
: self
.currentChange(i
)
129 qconnect(fW
, qt
.SIGNAL("currentChanged(QListViewItem*)"), self
.newCurLambda
)
131 # The diff viewing widget
132 self
.text
= qt
.QWidgetStack(splitter
)
134 ops
= qt
.QPopupMenu(self
)
135 ops
.setCheckable(True)
136 ops
.insertItem("Commit Selected Files", self
.commit
, Qt
.CTRL
+Qt
.Key_T
)
137 ops
.insertItem("Refresh", self
.refreshFiles
, Qt
.CTRL
+Qt
.Key_R
)
138 ops
.insertItem("(Un)select All", self
.toggleSelectAll
, Qt
.CTRL
+Qt
.Key_S
)
139 self
.showUnknownItem
= ops
.insertItem("Show Unkown Files",
140 self
.toggleShowUnknown
,
142 ops
.insertItem("Preferences...", self
.showPrefs
, Qt
.CTRL
+Qt
.Key_P
)
143 ops
.setItemChecked(self
.showUnknownItem
, settings().showUnknown
)
144 self
.operations
= ops
147 m
.insertItem("&Operations", ops
)
149 h
= qt
.QPopupMenu(self
)
150 h
.insertItem("&About", self
.about
)
151 m
.insertItem("&Help", h
)
153 qconnect(fW
, qt
.SIGNAL("contextMenuRequested(QListViewItem*, const QPoint&, int)"),
154 self
.contextMenuRequestedSlot
)
155 self
.fileOps
= qt
.QPopupMenu(self
)
156 self
.fileOps
.insertItem("Toggle selection", self
.toggleFile
)
157 self
.fileOps
.insertItem("Edit", self
.editFile
, Qt
.CTRL
+Qt
.Key_E
)
158 self
.fileOps
.insertItem("Discard changes", self
.discardFile
)
159 self
.fileOps
.insertItem("Ignore file", self
.ignoreFile
)
161 # The following attribute is set by contextMenuRequestedSlot
162 # and currentChange and used by the fileOps
163 self
.currentContextItem
= None
165 self
.patchColors
= {'std': 'black', 'new': '#009600', 'remove': '#C80000', 'head': '#C800C8'}
167 self
.files
= scm
.fileSetFactory(lambda f
: self
.addFile(f
),
168 lambda f
: self
.removeFile(f
))
170 f
.text
= "Commit message"
171 f
.textW
= self
.newTextEdit()
172 f
.textW
.setTextFormat(Qt
.PlainText
)
173 f
.textW
.setReadOnly(False)
174 f
.textW
.setText(settings().signoff
)
175 qconnect(f
.textW
, qt
.SIGNAL('cursorPositionChanged(int, int)'),
176 self
.updateCommitCursor
)
178 self
.createCmitItem()
179 self
.editorProcesses
= sets
.Set()
182 self
.options
= options
184 def updateStatusBar(self
):
185 if not self
.cmitFile
.textW
.isVisible():
186 self
.statusBar().clear()
188 def updateCommitCursor(self
, *dummy
):
189 [line
, col
] = self
.cmitFile
.textW
.getCursorPosition()
190 self
.statusBar().message('Column: ' + str(col
))
192 def loadSettings(self
):
193 self
.splitter
.setSizes(settings().splitter
)
195 def closeEvent(self
, e
):
197 settings().width
= s
.width()
198 settings().height
= s
.height()
199 settings().splitter
= self
.splitter
.sizes()
202 def createCmitItem(self
):
203 self
.cmitItem
= MyListItem(self
.filesW
, self
.cmitFile
, True)
204 self
.cmitItem
.setSelectable(False)
205 self
.filesW
.insertItem(self
.cmitItem
)
206 self
.cmitFile
.listViewItem
= self
.cmitItem
208 def about(self
, ignore
):
209 qt
.QMessageBox
.about(self
, "About " + applicationName
,
210 "<qt><center><h1>" + applicationName
+ " " + version
+ """</h1></center>\n
211 <center>Copyright © 2005 Fredrik Kuivinen <freku045@student.liu.se>
213 <center>Copyright © 2005 Mark Williamson <maw48@cl.cam.ac.uk>
214 </center>\n<p> This program is free software; you can redistribute it and/or
215 modify it under the terms of the GNU General Public License version 2 as
216 published by the Free Software Foundation.</p></qt>""")
218 def contextMenuRequestedSlot(self
, item
, pos
, col
):
219 if item
and not item
.commitMsg
:
220 self
.currentContextItem
= item
221 self
.fileOps
.exec_loop(qt
.QCursor
.pos())
223 self
.currentContextItem
= None
225 def toggleFile(self
, ignored
):
226 it
= self
.currentContextItem
231 it
.setSelected(False)
235 def editFile(self
, ignored
):
236 it
= self
.currentContextItem
242 qt
.QMessageBox
.warning(self
, 'No editor found',
243 '''No editor found. Gct looks for an editor to execute in the environment
244 variable GCT_EDITOR, if that variable is not set it will use the variable
248 # This piece of code is not entirely satisfactory. If the user
249 # has EDITOR set to 'vi', or some other non-X application, the
250 # editor will be started in the terminal which (h)gct was
251 # started in. A better approach would be to close stdin and
252 # stdout after the fork but before the exec, but this doesn't
253 # seem to be possible with QProcess.
255 p
.addArgument(it
.file.dstName
)
256 p
.setCommunication(0)
257 qconnect(p
, qt
.SIGNAL('processExited()'), self
.editorExited
)
258 if not p
.launch(qt
.QByteArray()):
259 qt
.QMessageBox
.warning(self
, 'Failed to launch editor',
260 shortName
+ ' failed to launch the ' + \
261 'editor. The command used was: ' + \
262 ed
+ ' ' + it
.file.dstName
)
264 self
.editorProcesses
.add(p
)
266 def editorExited(self
):
268 status
= p
.exitStatus()
269 file = unicode(p
.arguments()[1])
270 editor
= unicode(p
.arguments()[0]) + ' ' + file
271 if not p
.normalExit():
272 qt
.QMessageBox
.warning(self
, 'Editor failure',
273 'The editor, ' + editor
+ ', exited abnormally.')
275 qt
.QMessageBox
.warning(self
, 'Editor failure',
276 'The editor, ' + editor
+ ', exited with exit code ' + str(status
))
278 self
.editorProcesses
.remove(p
)
279 scm
.doUpdateCache(file)
282 def discardFile(self
, ignored
):
283 it
= self
.currentContextItem
287 scm
.discardFile(it
.file)
290 def ignoreFile(self
, ignored
):
291 it
= self
.currentContextItem
295 scm
.ignoreFile(it
.file)
298 def currentChange(self
, item
):
301 f
.textW
= self
.newTextEdit()
302 f
.textW
.setReadOnly(True)
303 f
.textW
.setTextFormat(Qt
.RichText
)
304 f
.textW
.setText(formatPatchRichText(f
.getPatch(), self
.patchColors
))
306 self
.text
.raiseWidget(f
.textW
)
307 self
.currentContextItem
= item
309 self
.updateCommitCursor()
311 def commit(self
, id):
316 for item
in self
.filesW
:
317 debug("file: " + item
.file.text
)
318 if item
.isSelected():
319 selFileNames
.append(item
.file.text
)
320 commitFiles
.append(item
.file)
322 keepFiles
.append(item
.file)
324 commitMsg
= unicode(self
.cmitItem
.file.textW
.text())
327 qt
.QMessageBox
.information(self
, "Commit - " + applicationName
,
328 "No files selected for commit.", "&Ok")
331 commitMsg
= fixCommitMsgWhiteSpace(commitMsg
)
332 if scm
.commitIsMerge():
333 mergeMsg
= scm
.mergeMessage()
337 commitDialog
= CommitDialog(mergeMsg
, commitMsg
, selFileNames
)
338 if commitDialog
.exec_loop():
340 scm
.doCommit(keepFiles
, commitFiles
, commitMsg
)
341 except ProgramError
, e
:
342 qt
.QMessageBox
.warning(self
, "Commit Failed - " + applicationName
,
343 "Commit failed: " + str(e
),
346 if not self
.options
.oneshot
:
347 self
.cmitItem
.file.textW
.setText(settings().signoff
)
349 self
.statusBar().message('Commit done')
351 if self
.options
.oneshot
:
354 def getFileState(self
):
356 cur
= self
.filesW
.currentItem()
357 if cur
and cur
!= self
.cmitItem
:
358 ret
.current
= self
.filesW
.currentItem().file.text
361 ret
.selected
= sets
.Set()
363 for x
in self
.filesW
:
365 ret
.selected
.add(x
.file.text
)
369 def restoreFileState(self
, state
):
371 f
.listViewItem
.setSelected(f
.text
in state
.selected
)
373 for x
in self
.filesW
:
374 if x
.file.text
== state
.current
:
375 self
.filesW
.setCurrentItem(x
)
377 def newTextEdit(self
):
379 self
.text
.addWidget(ret
)
382 def addFile(self
, file):
384 f
.listViewItem
= MyListItem(self
.filesW
, f
)
386 # The patch for this file is generated lazily in currentChange
388 # Only display files that match the filter.
389 f
.listViewItem
.setVisible(self
.filterMatch(f
))
391 self
.filesW
.insertItem(f
.listViewItem
)
394 def removeFile(self
, file):
396 self
.text
.removeWidget(f
.textW
)
397 self
.filesW
.takeItem(f
.listViewItem
)
398 f
.listViewItem
= None
400 def refreshFiles(self
):
401 state
= self
.getFileState()
403 self
.setUpdatesEnabled(False)
404 scm
.updateFiles(self
.files
)
405 self
.filesW
.setCurrentItem(self
.cmitItem
)
407 # For some reason the currentChanged signal isn't emitted
408 # here. We call currentChange ourselves instead.
409 self
.currentChange(self
.cmitItem
)
410 self
.restoreFileState(state
)
411 self
.setUpdatesEnabled(True)
414 if settings().quitOnNoChanges
and len(self
.files
) == 0:
416 return len(self
.files
) > 0
418 def filterMatch(self
, file):
419 return file.dstName
.find(unicode(self
.filter.text())) != -1
421 def updateFilter(self
, ignored
=None):
422 for w
in self
.filesW
:
423 w
.setVisible(self
.filterMatch(w
.file))
425 def clearFilter(self
):
426 self
.filter.setText("")
428 def toggleSelectAll(self
):
430 for x
in self
.filesW
:
432 if not x
.isSelected():
437 for x
in self
.filesW
:
441 def toggleShowUnknown(self
):
442 if settings().showUnknown
:
443 settings().showUnknown
= False
445 settings().showUnknown
= True
447 self
.operations
.setItemChecked(self
.showUnknownItem
, settings().showUnknown
)
451 if settings().showSettings():
454 commitMsgRE
= re
.compile('[ \t\r\f\v]*\n\\s*\n')
455 def fixCommitMsgWhiteSpace(msg
):
458 msg
= re
.sub(commitMsgRE
, '\n\n', msg
)
462 def formatPatchRichText(patch
, colors
):
463 ret
= ['<qt><pre><font color="', colors
['std'], '">']
465 for l
in patch
.split('\n'):
472 if c
== '+': style
= 'new'
473 elif c
== '-': style
= 'remove'
474 elif c
== '@': style
= 'head'
476 ret
.extend(['</font><font color="', colors
[style
], '">'])
478 line
= unicode(qt
.QStyleSheet
.escape(l
))
479 ret
.extend([line
, '\n'])
480 ret
.append('</pre></qt>')
484 if os
.environ
.has_key('GCT_EDITOR'):
485 return os
.environ
['GCT_EDITOR']
486 elif os
.environ
.has_key('EDITOR'):
487 return os
.environ
['EDITOR']
491 class EventFilter(qt
.QObject
):
492 def __init__(self
, parent
, mainWidget
):
493 qt
.QObject
.__init
__(self
, parent
)
496 def eventFilter(self
, watched
, e
):
497 if (e
.type() == qt
.QEvent
.KeyRelease
or \
498 e
.type() == qt
.QEvent
.MouseButtonRelease
):
499 self
.mw
.updateStatusBar()
506 app
= qt
.QApplication(sys
.argv
)
508 optParser
= OptionParser(usage
="%prog [--gui] [--one-shot]", version
=applicationName
+ ' ' + version
)
509 optParser
.add_option('-g', '--gui', action
='store_true', dest
='gui',
510 help='Unconditionally start the GUI')
511 optParser
.add_option('-o', '--one-shot', action
='store_true', dest
='oneshot',
512 help="Do (at most) one commit, then exit.")
513 (options
, args
) = optParser
.parse_args(app
.argv()[1:])
515 mw
= MainWidget(options
)
516 ef
= EventFilter(None, mw
)
517 app
.installEventFilter(ef
)
519 if not mw
.refreshFiles() and settings().quitOnNoChanges
and not options
.gui
:
520 print 'No outstanding changes'
523 mw
.resize(settings().width
, settings().height
)
526 app
.setMainWidget(mw
)
528 # Handle CTRL-C appropriately
529 signal
.signal(signal
.SIGINT
, lambda s
, f
: app
.quit())
531 ret
= app
.exec_loop()
532 settings().writeSettings()