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
19 import sys
, math
, random
, qt
, os
, re
, signal
, sets
, settings
20 from optparse
import OptionParser
24 # Determine semantics according to executable name. Default to git.
25 if os
.path
.basename(sys
.argv
[0]) == 'hgct':
26 print "defaulting to import hg because arg = %s" % sys
.argv
[0]
31 qconnect
= qt
.QObject
.connect
35 class CommitError(Exception):
36 def __init__(self
, operation
, msg
):
37 self
.operation
= operation
43 class MyListItem(qt
.QCheckListItem
):
44 def __init__(self
, parent
, file, commitMsg
= False):
45 qt
.QCheckListItem
.__init
__(self
, parent
, file.text
, qt
.QCheckListItem
.CheckBox
)
47 self
.commitMsg
= commitMsg
49 def compare(self
, item
, col
, asc
):
61 return cmp(self
.key(col
, asc
), item
.key(col
, asc
))
63 def paintCell(self
, p
, cg
, col
, w
, a
):
65 qt
.QListViewItem
.paintCell(self
, p
, cg
, col
, w
, a
)
67 qt
.QCheckListItem
.paintCell(self
, p
, cg
, col
, w
, a
)
70 return self
.state() == qt
.QCheckListItem
.On
72 def setSelected(self
, s
):
74 self
.setState(qt
.QCheckListItem
.On
)
76 self
.setState(qt
.QCheckListItem
.Off
)
78 class MyListView(qt
.QListView
):
79 def __init__(self
, parent
=None, name
=None):
80 qt
.QListView
.__init
__(self
, parent
, name
)
83 return ListViewIterator(self
)
85 class ListViewIterator
:
86 def __init__(self
, listview
):
87 self
.it
= qt
.QListViewItemIterator(listview
)
90 cur
= self
.it
.current()
103 class MainWidget(qt
.QMainWindow
):
104 def __init__(self
, parent
=None, name
=None):
105 qt
.QMainWindow
.__init
__(self
, parent
, name
)
106 splitter
= qt
.QSplitter(Qt
.Vertical
, self
)
108 fW
= MyListView(splitter
)
110 fW
.setSelectionMode(qt
.QListView
.NoSelection
)
111 fW
.addColumn('Description')
112 fW
.setResizeMode(qt
.QListView
.AllColumns
)
114 text
= qt
.QWidgetStack(splitter
)
116 self
.setCentralWidget(splitter
)
117 self
.setCaption(applicationName
)
119 self
.newCurLambda
= lambda i
: self
.currentChange(i
)
120 qconnect(fW
, qt
.SIGNAL("currentChanged(QListViewItem*)"), self
.newCurLambda
)
122 ops
= qt
.QPopupMenu(self
)
123 ops
.insertItem("Commit Selected Files", self
.commit
, Qt
.CTRL
+Qt
.Key_T
)
124 ops
.insertItem("Refresh", self
.refreshFiles
, Qt
.CTRL
+Qt
.Key_R
)
125 ops
.insertItem("Select All", self
.selectAll
, Qt
.CTRL
+Qt
.Key_A
)
126 ops
.insertItem("Unselect All", self
.unselectAll
, Qt
.CTRL
+Qt
.Key_U
)
127 ops
.insertItem("Preferences...", self
.showPrefs
, Qt
.CTRL
+Qt
.Key_P
)
130 m
.insertItem("&Operations", ops
)
132 h
= qt
.QPopupMenu(self
)
133 h
.insertItem("&About", self
.about
)
134 m
.insertItem("&Help", h
)
136 qconnect(fW
, qt
.SIGNAL("contextMenuRequested(QListViewItem*, const QPoint&, int)"),
137 self
.contextMenuRequestedSlot
)
138 self
.fileOps
= qt
.QPopupMenu(self
)
139 self
.fileOps
.insertItem("Toggle selection", self
.toggleFile
)
140 self
.fileOps
.insertItem("Edit", self
.editFile
, Qt
.CTRL
+Qt
.Key_E
)
141 self
.fileOps
.insertItem("Discard changes", self
.discardFile
)
142 self
.fileOps
.insertItem("Ignore file", self
.ignoreFile
)
144 # The following attribute is set by contextMenuRequestedSlot
145 # and currentChange and used by the fileOps
146 self
.currentContextItem
= None
148 self
.patchColors
= {'std': 'black', 'new': '#009600', 'remove': '#C80000', 'head': '#C800C8'}
152 self
.splitter
= splitter
156 f
.text
= "Commit message"
157 f
.textW
= self
.newTextEdit()
158 f
.textW
.setTextFormat(Qt
.PlainText
)
159 f
.textW
.setReadOnly(False)
160 f
.textW
.setText(settings
.signoff
)
163 self
.createCmitItem()
164 self
.editorProcesses
= sets
.Set()
167 def loadSettings(self
):
168 self
.splitter
.setSizes(settings
.splitter
)
170 def closeEvent(self
, e
):
172 settings
.width
= s
.width()
173 settings
.height
= s
.height()
174 settings
.splitter
= self
.splitter
.sizes()
177 def createCmitItem(self
):
178 self
.cmitItem
= MyListItem(self
.filesW
, self
.cmitFile
, True)
179 self
.cmitItem
.setSelectable(False)
180 self
.filesW
.insertItem(self
.cmitItem
)
182 def about(self
, ignore
):
183 qt
.QMessageBox
.about(self
, "About " + applicationName
,
184 "<qt><center><h1>" + applicationName
+ " " + version
+ """</h1></center>\n
185 <center>Copyright © 2005 Fredrik Kuivinen <freku045@student.liu.se>
186 </center>\n<p>This program is free software; you can redistribute it and/or
187 modify it under the terms of the GNU General Public License version 2 as
188 published by the Free Software Foundation.</p></qt>""")
190 def contextMenuRequestedSlot(self
, item
, pos
, col
):
191 if item
and not item
.commitMsg
:
192 self
.currentContextItem
= item
193 self
.fileOps
.exec_loop(qt
.QCursor
.pos())
195 self
.currentContextItem
= None
197 def toggleFile(self
, ignored
):
198 it
= self
.currentContextItem
203 it
.setSelected(False)
207 def editFile(self
, ignored
):
208 it
= self
.currentContextItem
214 qt
.QMessageBox
.warning(self
, 'No editor found',
215 '''No editor found. Gct looks for an editor to execute in the environment
216 variable GCT_EDITOR, if that variable is not set it will use the variable
220 # This piece of code is not entirely satisfactory. If the user
221 # has EDITOR set to 'vi', or some other non-X application, the
222 # editor will be started in the terminal which (h)gct was
223 # started in. A better approach would be to close stdin and
224 # stdout after the fork but before the exec, but this doesn't
225 # seem to be possible with QProcess.
227 p
.addArgument(it
.file.dstName
)
228 p
.setCommunication(0)
229 qconnect(p
, qt
.SIGNAL('processExited()'), self
.editorExited
)
230 if not p
.launch(qt
.QByteArray()):
231 qt
.QMessageBox
.warning(self
, 'Failed to launch editor',
232 shortName
+ ' failed to launch the ' + \
233 'editor. The command used was: ' + \
234 ed
+ ' ' + it
.file.dstName
)
236 self
.editorProcesses
.add(p
)
238 def editorExited(self
):
240 status
= p
.exitStatus()
241 file = str(p
.arguments()[1])
242 editor
= str(p
.arguments()[0]) + ' ' + file
243 if not p
.normalExit():
244 qt
.QMessageBox
.warning(self
, 'Editor failure',
245 'The editor, ' + editor
+ ', exited abnormally.')
247 qt
.QMessageBox
.warning(self
, 'Editor failure',
248 'The editor, ' + editor
+ ', exited with exit code ' + str(status
))
250 self
.editorProcesses
.remove(p
)
251 scm
.doUpdateCache(file)
254 def discardFile(self
, ignored
):
255 it
= self
.currentContextItem
259 scm
.discardFile(it
.file)
262 def ignoreFile(self
, ignored
):
263 it
= self
.currentContextItem
267 scm
.ignoreFile(it
.file)
270 def currentChange(self
, item
):
271 self
.text
.raiseWidget(item
.file.textW
)
273 self
.currentContextItem
= item
275 def selectedItems(self
):
277 for item
in self
.filesW
:
278 if item
.isSelected():
282 def commit(self
, id):
287 for item
in self
.filesW
:
288 debug("file: " + item
.file.text
)
289 if item
.isSelected():
290 selFileNames
.append(item
.file.text
)
291 commitFiles
.append(item
.file.dstName
)
293 keepFiles
.append(item
.file)
295 commitMsg
= str(self
.cmitItem
.file.textW
.text())
298 qt
.QMessageBox
.information(self
, "Commit - " + applicationName
,
299 "No files selected for commit.", "&Ok")
302 commitMsg
= fixCommitMsgWhiteSpace(commitMsg
)
303 if scm
.commitIsMerge():
304 mergeMsg
= scm
.mergeMessage()
308 if(qt
.QMessageBox
.question(self
, "Confirm Commit - " + applicationName
,
309 '<qt><p>' + mergeMsg
+ '</p><p>Do you want to commit the following file(s):</p><blockquote>' +
310 '<br>'.join(selFileNames
) +
311 '''</blockquote><p>with the commit message:</p><blockquote><pre>''' +
312 str(qt
.QStyleSheet
.escape(commitMsg
)) + '</pre></blockquote></qt>',
317 scm
.doCommit(keepFiles
, commitFiles
, commitMsg
)
318 except CommitError
, e
:
319 qt
.QMessageBox
.warning(self
, "Commit Failed - " + applicationName
,
320 "Commit failed during " + e
.operation
+ ": " + e
.msg
,
323 qt
.QMessageBox
.warning(self
, "Commit Failed - " + applicationName
,
324 "Commit failed: " + e
.strerror
,
327 self
.cmitItem
.file.textW
.setText(settings
.signoff
)
330 def getFileState(self
):
332 cur
= self
.filesW
.currentItem()
333 if cur
and cur
!= self
.cmitItem
:
334 ret
.current
= self
.filesW
.currentItem().file.srcName
339 for x
in self
.filesW
:
341 ret
.selected
[x
.file.srcName
] = True
344 def restoreFileState(self
, state
):
345 for x
in self
.filesW
:
346 if state
.selected
.has_key(x
.file.srcName
):
348 if x
.file.srcName
== state
.current
:
349 self
.filesW
.setCurrentItem(x
)
351 def newTextEdit(self
):
353 self
.text
.addWidget(ret
)
356 def setFiles(self
, files
):
357 state
= self
.getFileState()
359 self
.createCmitItem()
361 self
.text
.removeWidget(f
.textW
)
365 f
.textW
= self
.newTextEdit()
366 f
.textW
.setReadOnly(True)
367 f
.textW
.setTextFormat(Qt
.RichText
)
368 f
.textW
.setText(formatPatchRichText(f
.patch
, self
.patchColors
))
370 self
.filesW
.insertItem(MyListItem(self
.filesW
, f
))
372 self
.filesW
.setCurrentItem(self
.cmitItem
)
374 # For some reason the currentChanged signal isn't emitted
375 # here. We call currentChange ourselves instead.
376 self
.currentChange(self
.cmitItem
)
378 self
.restoreFileState(state
)
380 def refreshFiles(self
, ignored
=None):
381 files
= scm
.getFiles()
382 if settings
.quitOnNoChanges
and len(files
) == 0:
387 return len(files
) > 0
390 for x
in self
.filesW
:
393 def unselectAll(self
):
394 for x
in self
.filesW
:
398 settings
.showSettings()
400 commitMsgRE
= re
.compile('[ \t\r\f\v]*\n\\s*\n')
401 def fixCommitMsgWhiteSpace(msg
):
404 msg
= re
.sub(commitMsgRE
, '\n\n', msg
)
408 def formatPatchRichText(patch
, colors
):
409 ret
= ['<qt><pre><font color="', colors
['std'], '">']
411 for l
in patch
.split('\n'):
418 if c
== '+': style
= 'new'
419 elif c
== '-': style
= 'remove'
420 elif c
== '@': style
= 'head'
422 ret
.extend(['</font><font color="', colors
[style
], '">'])
424 line
= qt
.QStyleSheet
.escape(l
).ascii()
429 ret
.extend([line
, '\n'])
430 ret
.append('</pre></qt>')
434 if os
.environ
.has_key('GCT_EDITOR'):
435 return os
.environ
['GCT_EDITOR']
436 elif os
.environ
.has_key('EDITOR'):
437 return os
.environ
['EDITOR']
443 app
= qt
.QApplication(sys
.argv
)
445 optParser
= OptionParser(usage
="%prog [--gui]", version
=applicationName
+ ' ' + version
)
446 optParser
.add_option('-g', '--gui', action
='store_true', dest
='gui',
447 help='Unconditionally start the GUI')
448 (options
, args
) = optParser
.parse_args(app
.argv()[1:])
450 settings
= settings
.Settings()
453 if not mw
.refreshFiles() and settings
.quitOnNoChanges
and not options
.gui
:
454 print 'No outstanding changes'
457 mw
.resize(settings
.width
, settings
.height
)
459 # The following code doesn't work correctly in some (at least
461 # managers. http://doc.trolltech.com/3.3/geometry.html contains some
462 # information about this issue.
463 # mw.move(settings.readNumEntry('x', 100)[0],
464 # settings.readNumEntry('y', 100)[0])
467 app
.setMainWidget(mw
)
470 # Handle CTRL-C appropriately
471 signal
.signal(signal
.SIGINT
, lambda s
, f
: app
.quit())
473 ret
= app
.exec_loop()
474 settings
.writeSettings()