Pass options to main widget - use this to support the new --one-shot option.
[hgct.git] / main.py
bloba6252b70e9906872d4ee6b58d2af6bd755837d6c
1 #!/usr/bin/env python
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.
9 #
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 from ctcore import *
20 import sys, math, random, qt, os, re, signal, sets
21 from optparse import OptionParser
23 # Determine semantics according to executable name. Default to git.
24 if os.path.basename(sys.argv[0]) == 'hgct':
25 print "defaulting to import hg because arg = %s" % sys.argv[0]
26 import hg as scm
27 else:
28 import git as scm
30 qconnect = qt.QObject.connect
31 Qt = qt.Qt
32 #DEBUG = 1
34 class CommitError(Exception):
35 def __init__(self, operation, msg):
36 self.operation = operation
37 self.msg = msg
39 class FileState:
40 pass
42 class MyListItem(qt.QCheckListItem):
43 def __init__(self, parent, file, commitMsg = False):
44 qt.QCheckListItem.__init__(self, parent, file.text, qt.QCheckListItem.CheckBox)
45 self.file = file
46 self.commitMsg = commitMsg
48 def compare(self, item, col, asc):
49 if self.commitMsg:
50 if asc:
51 return -1
52 else:
53 return 1
54 elif item.commitMsg:
55 if asc:
56 return 1
57 else:
58 return -1
59 else:
60 return cmp(self.file.srcName, item.file.srcName)
62 def paintCell(self, p, cg, col, w, a):
63 if self.commitMsg:
64 qt.QListViewItem.paintCell(self, p, cg, col, w, a)
65 else:
66 qt.QCheckListItem.paintCell(self, p, cg, col, w, a)
68 def isSelected(self):
69 return self.state() == qt.QCheckListItem.On
71 def setSelected(self, s):
72 if s:
73 self.setState(qt.QCheckListItem.On)
74 else:
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)
81 def __iter__(self):
82 return ListViewIterator(self)
84 class ListViewIterator:
85 def __init__(self, listview):
86 self.it = qt.QListViewItemIterator(listview)
88 def next(self):
89 cur = self.it.current()
90 if cur:
91 self.it += 1
92 if cur.commitMsg:
93 return self.next()
94 else:
95 return cur
96 else:
97 raise StopIteration()
99 def __iter__(self):
100 return self
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)
114 # The file list
115 fW = MyListView(self.filesLayout)
116 self.filesW = fW
117 fW.setFocus()
118 fW.setSelectionMode(qt.QListView.NoSelection)
119 fW.addColumn('Description')
120 fW.setResizeMode(qt.QListView.AllColumns)
122 # The file filter
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)
145 m = self.menuBar()
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'}
166 self.files = []
168 f = File()
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)
175 self.cmitFile = f
176 self.createCmitItem()
177 self.editorProcesses = sets.Set()
178 self.loadSettings()
180 self.options = options
182 def loadSettings(self):
183 self.splitter.setSizes(settings().splitter)
185 def closeEvent(self, e):
186 s = self.size()
187 settings().width = s.width()
188 settings().height = s.height()
189 settings().splitter = self.splitter.sizes()
190 e.accept()
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 &copy; 2005 Fredrik Kuivinen &lt;freku045@student.liu.se&gt;
202 </center>\n<p>
203 <center>Copyright &copy; 2005 Mark Williamson &lt;maw48@cl.cam.ac.uk&gt;
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())
212 else:
213 self.currentContextItem = None
215 def toggleFile(self, ignored):
216 it = self.currentContextItem
217 if not it:
218 return
220 if it.isSelected():
221 it.setSelected(False)
222 else:
223 it.setSelected(True)
225 def editFile(self, ignored):
226 it = self.currentContextItem
227 if not it:
228 return
230 ed = getEditor()
231 if not ed:
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
235 EDITOR.''')
236 return
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.
244 p = qt.QProcess(ed)
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)
253 else:
254 self.editorProcesses.add(p)
256 def editorExited(self):
257 p = self.sender()
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.')
264 elif status != 0:
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)
270 self.refreshFiles()
272 def discardFile(self, ignored):
273 it = self.currentContextItem
274 if not it:
275 return
277 scm.discardFile(it.file)
278 self.refreshFiles()
280 def ignoreFile(self, ignored):
281 it = self.currentContextItem
282 if not it:
283 return
285 scm.ignoreFile(it.file)
286 self.refreshFiles()
288 def currentChange(self, item):
289 self.text.raiseWidget(item.file.textW)
290 self.text.update()
291 self.currentContextItem = item
293 def commit(self, id):
294 selFileNames = []
295 keepFiles = []
296 commitFiles = []
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)
303 else:
304 keepFiles.append(item.file)
306 commitMsg = str(self.cmitItem.file.textW.text())
308 if not selFileNames:
309 qt.QMessageBox.information(self, "Commit - " + applicationName,
310 "No files selected for commit.", "&Ok")
311 return
313 commitMsg = fixCommitMsgWhiteSpace(commitMsg)
314 if scm.commitIsMerge():
315 mergeMsg = scm.mergeMessage()
316 else:
317 mergeMsg = ''
319 if(qt.QMessageBox.question(self, "Confirm Commit - " + applicationName,
320 '<qt><p>' + mergeMsg + '</p><p>Do you want to commit the following file(s):</p><blockquote>' +
321 '<br>'.join(selFileNames) +
322 '''</blockquote><p>with the commit message:</p><blockquote><pre>''' +
323 str(qt.QStyleSheet.escape(commitMsg)) + '</pre></blockquote></qt>',
324 '&Yes', '&No')):
325 return
326 else:
327 try:
328 scm.doCommit(keepFiles, commitFiles, commitMsg)
329 except CommitError, e:
330 qt.QMessageBox.warning(self, "Commit Failed - " + applicationName,
331 "Commit failed during " + e.operation + ": " + e.msg,
332 '&Ok')
333 except OSError, e:
334 qt.QMessageBox.warning(self, "Commit Failed - " + applicationName,
335 "Commit failed: " + e.strerror,
336 '&Ok')
337 else:
338 if not self.options.oneshot:
339 self.cmitItem.file.textW.setText(settings().signoff)
340 self.refreshFiles()
342 if self.options.oneshot:
343 self.close()
346 def getFileState(self):
347 ret = FileState()
348 cur = self.filesW.currentItem()
349 if cur and cur != self.cmitItem:
350 ret.current = self.filesW.currentItem().file.dstName
351 else:
352 ret.current = None
353 ret.selected = sets.Set()
355 for x in self.filesW:
356 if x.isSelected():
357 ret.selected.add(x.file.dstName)
359 return ret
361 def restoreFileState(self, state):
362 for f in self.files:
363 f.listViewItem.setSelected(f.dstName in state.selected)
365 for x in self.filesW:
366 if x.file.dstName == state.current:
367 self.filesW.setCurrentItem(x)
369 def newTextEdit(self):
370 ret = qt.QTextEdit()
371 self.text.addWidget(ret)
372 return ret
374 def setFiles(self, files):
375 state = self.getFileState()
376 self.filesW.clear()
377 self.createCmitItem()
378 for f in self.files:
379 self.text.removeWidget(f.textW)
380 f.listViewItem = None
382 self.files = []
383 for f in files:
384 f.textW = self.newTextEdit()
385 f.textW.setReadOnly(True)
386 f.textW.setTextFormat(Qt.RichText)
387 f.textW.setText(formatPatchRichText(f.patch, self.patchColors))
388 self.files.append(f)
390 f.listViewItem = MyListItem(self.filesW, f)
391 # Only display files that match the filter.
392 f.listViewItem.setVisible(self.filterMatch(f))
393 self.filesW.insertItem(f.listViewItem)
395 self.filesW.setCurrentItem(self.cmitItem)
397 # For some reason the currentChanged signal isn't emitted
398 # here. We call currentChange ourselves instead.
399 self.currentChange(self.cmitItem)
401 self.restoreFileState(state)
403 def refreshFiles(self, ignored=None):
404 files = scm.getFiles()
405 if settings().quitOnNoChanges and len(files) == 0:
406 self.close()
407 else:
408 self.setFiles(files)
410 return len(files) > 0
412 def filterMatch(self, file):
413 return file.dstName.find(str(self.filter.text())) != -1
415 def updateFilter(self, ignored=None):
416 for w in self.filesW:
417 w.setVisible(self.filterMatch(w.file))
419 def clearFilter(self):
420 self.filter.setText("")
422 def selectAll(self):
423 for x in self.filesW:
424 if x.isVisible():
425 x.setSelected(True)
427 def unselectAll(self):
428 for x in self.filesW:
429 if x.isVisible():
430 x.setSelected(False)
432 def showPrefs(self):
433 settings().showSettings()
435 commitMsgRE = re.compile('[ \t\r\f\v]*\n\\s*\n')
436 def fixCommitMsgWhiteSpace(msg):
437 msg = msg.lstrip()
438 msg = msg.rstrip()
439 msg = re.sub(commitMsgRE, '\n\n', msg)
440 msg += '\n'
441 return msg
443 def formatPatchRichText(patch, colors):
444 ret = ['<qt><pre><font color="', colors['std'], '">']
445 prev = ' '
446 for l in patch.split('\n'):
447 if len(l) > 0:
448 c = l[0]
449 else:
450 c = ' '
452 if c != prev:
453 if c == '+': style = 'new'
454 elif c == '-': style = 'remove'
455 elif c == '@': style = 'head'
456 else: style = 'std'
457 ret.extend(['</font><font color="', colors[style], '">'])
458 prev = c
459 line = qt.QStyleSheet.escape(l).ascii()
460 if not line:
461 line = ''
462 else:
463 line = str(line)
464 ret.extend([line, '\n'])
465 ret.append('</pre></qt>')
466 return ''.join(ret)
468 def getEditor():
469 if os.environ.has_key('GCT_EDITOR'):
470 return os.environ['GCT_EDITOR']
471 elif os.environ.has_key('EDITOR'):
472 return os.environ['EDITOR']
473 else:
474 return None
476 scm.repoValid()
478 app = qt.QApplication(sys.argv)
480 optParser = OptionParser(usage="%prog [--gui] [--one-shot]", version=applicationName + ' ' + version)
481 optParser.add_option('-g', '--gui', action='store_true', dest='gui',
482 help='Unconditionally start the GUI')
483 optParser.add_option('-o', '--one-shot', action='store_true', dest='oneshot',
484 help="Do (at most) one commit, then exit.")
485 (options, args) = optParser.parse_args(app.argv()[1:])
487 mw = MainWidget(options)
489 if not mw.refreshFiles() and settings().quitOnNoChanges and not options.gui:
490 print 'No outstanding changes'
491 sys.exit(0)
493 mw.resize(settings().width, settings().height)
495 # The following code doesn't work correctly in some (at least
496 # Metacity) window
497 # managers. http://doc.trolltech.com/3.3/geometry.html contains some
498 # information about this issue.
499 # mw.move(settings.readNumEntry('x', 100)[0],
500 # settings.readNumEntry('y', 100)[0])
502 mw.show()
503 app.setMainWidget(mw)
506 # Handle CTRL-C appropriately
507 signal.signal(signal.SIGINT, lambda s, f: app.quit())
509 ret = app.exec_loop()
510 settings().writeSettings()
511 sys.exit(ret)