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
34 class CommitError(Exception):
35 def __init__(self
, operation
, msg
):
36 self
.operation
= operation
42 class MyListItem(qt
.QCheckListItem
):
43 def __init__(self
, parent
, file, commitMsg
= False):
44 qt
.QCheckListItem
.__init
__(self
, parent
, file.text
, qt
.QCheckListItem
.CheckBox
)
46 self
.commitMsg
= commitMsg
48 def compare(self
, item
, col
, asc
):
60 return cmp(self
.file.srcName
, item
.file.srcName
)
62 def paintCell(self
, p
, cg
, col
, w
, a
):
64 qt
.QListViewItem
.paintCell(self
, p
, cg
, col
, w
, a
)
66 qt
.QCheckListItem
.paintCell(self
, p
, cg
, col
, w
, a
)
69 return self
.state() == qt
.QCheckListItem
.On
71 def setSelected(self
, s
):
73 self
.setState(qt
.QCheckListItem
.On
)
75 self
.setState(qt
.QCheckListItem
.Off
)
77 class MyListView(qt
.QListView
):
78 def __init__(self
, parent
=None, name
=None):
79 qt
.QListView
.__init
__(self
, parent
, name
)
82 return ListViewIterator(self
)
84 class ListViewIterator
:
85 def __init__(self
, listview
):
86 self
.it
= qt
.QListViewItemIterator(listview
)
89 cur
= self
.it
.current()
102 class MainWidget(qt
.QMainWindow
):
103 def __init__(self
, options
, parent
=None, name
=None):
104 qt
.QMainWindow
.__init
__(self
, parent
, name
)
105 self
.setCaption(applicationName
)
107 splitter
= qt
.QSplitter(Qt
.Vertical
, self
)
108 self
.setCentralWidget(splitter
)
109 self
.splitter
= splitter
111 # The file list and file filter widgets are part of this layout widget.
112 self
.filesLayout
= qt
.QVBox(splitter
)
115 fW
= MyListView(self
.filesLayout
)
118 fW
.setSelectionMode(qt
.QListView
.NoSelection
)
119 fW
.addColumn('Description')
120 fW
.setResizeMode(qt
.QListView
.AllColumns
)
123 self
.filterLayout
= qt
.QHBox(self
.filesLayout
)
124 self
.filterClear
= qt
.QPushButton("&Clear", self
.filterLayout
)
125 self
.filterLabel
= qt
.QLabel(" File filter: ", self
.filterLayout
)
126 qconnect(self
.filterClear
, qt
.SIGNAL("clicked()"), self
.clearFilter
)
127 self
.filter = qt
.QLineEdit(self
.filterLayout
)
128 self
.filterLabel
.setBuddy(self
.filter)
130 qconnect(self
.filter, qt
.SIGNAL("textChanged(const QString&)"), self
.updateFilter
)
132 self
.newCurLambda
= lambda i
: self
.currentChange(i
)
133 qconnect(fW
, qt
.SIGNAL("currentChanged(QListViewItem*)"), self
.newCurLambda
)
135 # The diff viewing widget
136 self
.text
= qt
.QWidgetStack(splitter
)
138 ops
= qt
.QPopupMenu(self
)
139 ops
.insertItem("Commit Selected Files", self
.commit
, Qt
.CTRL
+Qt
.Key_T
)
140 ops
.insertItem("Refresh", self
.refreshFiles
, Qt
.CTRL
+Qt
.Key_R
)
141 ops
.insertItem("Select All", self
.selectAll
, Qt
.CTRL
+Qt
.Key_A
)
142 ops
.insertItem("Unselect All", self
.unselectAll
, Qt
.CTRL
+Qt
.Key_U
)
143 ops
.insertItem("Preferences...", self
.showPrefs
, Qt
.CTRL
+Qt
.Key_P
)
146 m
.insertItem("&Operations", ops
)
148 h
= qt
.QPopupMenu(self
)
149 h
.insertItem("&About", self
.about
)
150 m
.insertItem("&Help", h
)
152 qconnect(fW
, qt
.SIGNAL("contextMenuRequested(QListViewItem*, const QPoint&, int)"),
153 self
.contextMenuRequestedSlot
)
154 self
.fileOps
= qt
.QPopupMenu(self
)
155 self
.fileOps
.insertItem("Toggle selection", self
.toggleFile
)
156 self
.fileOps
.insertItem("Edit", self
.editFile
, Qt
.CTRL
+Qt
.Key_E
)
157 self
.fileOps
.insertItem("Discard changes", self
.discardFile
)
158 self
.fileOps
.insertItem("Ignore file", self
.ignoreFile
)
160 # The following attribute is set by contextMenuRequestedSlot
161 # and currentChange and used by the fileOps
162 self
.currentContextItem
= None
164 self
.patchColors
= {'std': 'black', 'new': '#009600', 'remove': '#C80000', 'head': '#C800C8'}
169 f
.text
= "Commit message"
170 f
.textW
= self
.newTextEdit()
171 f
.textW
.setTextFormat(Qt
.PlainText
)
172 f
.textW
.setReadOnly(False)
173 f
.textW
.setText(settings().signoff
)
176 self
.createCmitItem()
177 self
.editorProcesses
= sets
.Set()
180 self
.options
= options
182 def loadSettings(self
):
183 self
.splitter
.setSizes(settings().splitter
)
185 def closeEvent(self
, e
):
187 settings().width
= s
.width()
188 settings().height
= s
.height()
189 settings().splitter
= self
.splitter
.sizes()
192 def createCmitItem(self
):
193 self
.cmitItem
= MyListItem(self
.filesW
, self
.cmitFile
, True)
194 self
.cmitItem
.setSelectable(False)
195 self
.filesW
.insertItem(self
.cmitItem
)
196 self
.cmitFile
.listViewItem
= self
.cmitItem
198 def about(self
, ignore
):
199 qt
.QMessageBox
.about(self
, "About " + applicationName
,
200 "<qt><center><h1>" + applicationName
+ " " + version
+ """</h1></center>\n
201 <center>Copyright © 2005 Fredrik Kuivinen <freku045@student.liu.se>
203 <center>Copyright © 2005 Mark Williamson <maw48@cl.cam.ac.uk>
204 </center>\n<p> This program is free software; you can redistribute it and/or
205 modify it under the terms of the GNU General Public License version 2 as
206 published by the Free Software Foundation.</p></qt>""")
208 def contextMenuRequestedSlot(self
, item
, pos
, col
):
209 if item
and not item
.commitMsg
:
210 self
.currentContextItem
= item
211 self
.fileOps
.exec_loop(qt
.QCursor
.pos())
213 self
.currentContextItem
= None
215 def toggleFile(self
, ignored
):
216 it
= self
.currentContextItem
221 it
.setSelected(False)
225 def editFile(self
, ignored
):
226 it
= self
.currentContextItem
232 qt
.QMessageBox
.warning(self
, 'No editor found',
233 '''No editor found. Gct looks for an editor to execute in the environment
234 variable GCT_EDITOR, if that variable is not set it will use the variable
238 # This piece of code is not entirely satisfactory. If the user
239 # has EDITOR set to 'vi', or some other non-X application, the
240 # editor will be started in the terminal which (h)gct was
241 # started in. A better approach would be to close stdin and
242 # stdout after the fork but before the exec, but this doesn't
243 # seem to be possible with QProcess.
245 p
.addArgument(it
.file.dstName
)
246 p
.setCommunication(0)
247 qconnect(p
, qt
.SIGNAL('processExited()'), self
.editorExited
)
248 if not p
.launch(qt
.QByteArray()):
249 qt
.QMessageBox
.warning(self
, 'Failed to launch editor',
250 shortName
+ ' failed to launch the ' + \
251 'editor. The command used was: ' + \
252 ed
+ ' ' + it
.file.dstName
)
254 self
.editorProcesses
.add(p
)
256 def editorExited(self
):
258 status
= p
.exitStatus()
259 file = str(p
.arguments()[1])
260 editor
= str(p
.arguments()[0]) + ' ' + file
261 if not p
.normalExit():
262 qt
.QMessageBox
.warning(self
, 'Editor failure',
263 'The editor, ' + editor
+ ', exited abnormally.')
265 qt
.QMessageBox
.warning(self
, 'Editor failure',
266 'The editor, ' + editor
+ ', exited with exit code ' + str(status
))
268 self
.editorProcesses
.remove(p
)
269 scm
.doUpdateCache(file)
272 def discardFile(self
, ignored
):
273 it
= self
.currentContextItem
277 scm
.discardFile(it
.file)
280 def ignoreFile(self
, ignored
):
281 it
= self
.currentContextItem
285 scm
.ignoreFile(it
.file)
288 def currentChange(self
, item
):
289 self
.text
.raiseWidget(item
.file.textW
)
291 self
.currentContextItem
= item
293 def commit(self
, id):
298 for item
in self
.filesW
:
299 debug("file: " + item
.file.text
)
300 if item
.isSelected():
301 selFileNames
.append(item
.file.text
)
302 commitFiles
.append(item
.file)
304 keepFiles
.append(item
.file)
306 commitMsg
= str(self
.cmitItem
.file.textW
.text())
309 qt
.QMessageBox
.information(self
, "Commit - " + applicationName
,
310 "No files selected for commit.", "&Ok")
313 commitMsg
= fixCommitMsgWhiteSpace(commitMsg
)
314 if scm
.commitIsMerge():
315 mergeMsg
= scm
.mergeMessage()
319 commitDialog
= CommitDialog(mergeMsg
, commitMsg
, selFileNames
)
320 if commitDialog
.exec_loop():
322 scm
.doCommit(keepFiles
, commitFiles
, commitMsg
)
323 except CommitError
, e
:
324 qt
.QMessageBox
.warning(self
, "Commit Failed - " + applicationName
,
325 "Commit failed during " + e
.operation
+ ": " + e
.msg
,
328 qt
.QMessageBox
.warning(self
, "Commit Failed - " + applicationName
,
329 "Commit failed: " + e
.strerror
,
332 if not self
.options
.oneshot
:
333 self
.cmitItem
.file.textW
.setText(settings().signoff
)
336 if self
.options
.oneshot
:
339 def getFileState(self
):
341 cur
= self
.filesW
.currentItem()
342 if cur
and cur
!= self
.cmitItem
:
343 ret
.current
= self
.filesW
.currentItem().file.dstName
346 ret
.selected
= sets
.Set()
348 for x
in self
.filesW
:
350 ret
.selected
.add(x
.file.dstName
)
354 def restoreFileState(self
, state
):
356 f
.listViewItem
.setSelected(f
.dstName
in state
.selected
)
358 for x
in self
.filesW
:
359 if x
.file.dstName
== state
.current
:
360 self
.filesW
.setCurrentItem(x
)
362 def newTextEdit(self
):
364 self
.text
.addWidget(ret
)
367 def setFiles(self
, files
):
368 state
= self
.getFileState()
370 self
.createCmitItem()
372 self
.text
.removeWidget(f
.textW
)
373 f
.listViewItem
= None
377 f
.textW
= self
.newTextEdit()
378 f
.textW
.setReadOnly(True)
379 f
.textW
.setTextFormat(Qt
.RichText
)
380 f
.textW
.setText(formatPatchRichText(f
.patch
, self
.patchColors
))
383 f
.listViewItem
= MyListItem(self
.filesW
, f
)
384 # Only display files that match the filter.
385 f
.listViewItem
.setVisible(self
.filterMatch(f
))
386 self
.filesW
.insertItem(f
.listViewItem
)
388 self
.filesW
.setCurrentItem(self
.cmitItem
)
390 # For some reason the currentChanged signal isn't emitted
391 # here. We call currentChange ourselves instead.
392 self
.currentChange(self
.cmitItem
)
394 self
.restoreFileState(state
)
396 def refreshFiles(self
, ignored
=None):
397 files
= scm
.getFiles()
398 if settings().quitOnNoChanges
and len(files
) == 0:
403 return len(files
) > 0
405 def filterMatch(self
, file):
406 return file.dstName
.find(str(self
.filter.text())) != -1
408 def updateFilter(self
, ignored
=None):
409 for w
in self
.filesW
:
410 w
.setVisible(self
.filterMatch(w
.file))
412 def clearFilter(self
):
413 self
.filter.setText("")
416 for x
in self
.filesW
:
420 def unselectAll(self
):
421 for x
in self
.filesW
:
426 if settings().showSettings():
429 commitMsgRE
= re
.compile('[ \t\r\f\v]*\n\\s*\n')
430 def fixCommitMsgWhiteSpace(msg
):
433 msg
= re
.sub(commitMsgRE
, '\n\n', msg
)
437 def formatPatchRichText(patch
, colors
):
438 ret
= ['<qt><pre><font color="', colors
['std'], '">']
440 for l
in patch
.split('\n'):
447 if c
== '+': style
= 'new'
448 elif c
== '-': style
= 'remove'
449 elif c
== '@': style
= 'head'
451 ret
.extend(['</font><font color="', colors
[style
], '">'])
453 line
= qt
.QStyleSheet
.escape(l
).ascii()
458 ret
.extend([line
, '\n'])
459 ret
.append('</pre></qt>')
463 if os
.environ
.has_key('GCT_EDITOR'):
464 return os
.environ
['GCT_EDITOR']
465 elif os
.environ
.has_key('EDITOR'):
466 return os
.environ
['EDITOR']
472 app
= qt
.QApplication(sys
.argv
)
474 optParser
= OptionParser(usage
="%prog [--gui] [--one-shot]", version
=applicationName
+ ' ' + version
)
475 optParser
.add_option('-g', '--gui', action
='store_true', dest
='gui',
476 help='Unconditionally start the GUI')
477 optParser
.add_option('-o', '--one-shot', action
='store_true', dest
='oneshot',
478 help="Do (at most) one commit, then exit.")
479 (options
, args
) = optParser
.parse_args(app
.argv()[1:])
481 mw
= MainWidget(options
)
483 if not mw
.refreshFiles() and settings().quitOnNoChanges
and not options
.gui
:
484 print 'No outstanding changes'
487 mw
.resize(settings().width
, settings().height
)
489 # The following code doesn't work correctly in some (at least
491 # managers. http://doc.trolltech.com/3.3/geometry.html contains some
492 # information about this issue.
493 # mw.move(settings.readNumEntry('x', 100)[0],
494 # settings.readNumEntry('y', 100)[0])
497 app
.setMainWidget(mw
)
500 # Handle CTRL-C appropriately
501 signal
.signal(signal
.SIGINT
, lambda s
, f
: app
.quit())
503 ret
= app
.exec_loop()
504 settings().writeSettings()