Remove old comment. Saving the window position is just a bad idea.
[hgct.git] / main.py
blob69c91e723782d807040a7487098824f773a60265
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
22 from commit import CommitDialog
24 # Determine semantics according to executable name. Default to git.
25 if os.path.basename(sys.argv[0]) == 'hgct':
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 commitDialog = CommitDialog(mergeMsg, commitMsg, selFileNames)
320 if commitDialog.exec_loop():
321 try:
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,
326 '&Ok')
327 except OSError, e:
328 qt.QMessageBox.warning(self, "Commit Failed - " + applicationName,
329 "Commit failed: " + e.strerror,
330 '&Ok')
331 else:
332 if not self.options.oneshot:
333 self.cmitItem.file.textW.setText(settings().signoff)
334 self.refreshFiles()
336 if self.options.oneshot:
337 self.close()
339 def getFileState(self):
340 ret = FileState()
341 cur = self.filesW.currentItem()
342 if cur and cur != self.cmitItem:
343 ret.current = self.filesW.currentItem().file.dstName
344 else:
345 ret.current = None
346 ret.selected = sets.Set()
348 for x in self.filesW:
349 if x.isSelected():
350 ret.selected.add(x.file.dstName)
352 return ret
354 def restoreFileState(self, state):
355 for f in self.files:
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):
363 ret = qt.QTextEdit()
364 self.text.addWidget(ret)
365 return ret
367 def setFiles(self, files):
368 state = self.getFileState()
369 self.filesW.clear()
370 self.createCmitItem()
371 for f in self.files:
372 self.text.removeWidget(f.textW)
373 f.listViewItem = None
375 self.files = []
376 for f in files:
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))
381 self.files.append(f)
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:
399 self.close()
400 else:
401 self.setFiles(files)
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("")
415 def selectAll(self):
416 for x in self.filesW:
417 if x.isVisible():
418 x.setSelected(True)
420 def unselectAll(self):
421 for x in self.filesW:
422 if x.isVisible():
423 x.setSelected(False)
425 def showPrefs(self):
426 if settings().showSettings():
427 self.refreshFiles()
429 commitMsgRE = re.compile('[ \t\r\f\v]*\n\\s*\n')
430 def fixCommitMsgWhiteSpace(msg):
431 msg = msg.lstrip()
432 msg = msg.rstrip()
433 msg = re.sub(commitMsgRE, '\n\n', msg)
434 msg += '\n'
435 return msg
437 def formatPatchRichText(patch, colors):
438 ret = ['<qt><pre><font color="', colors['std'], '">']
439 prev = ' '
440 for l in patch.split('\n'):
441 if len(l) > 0:
442 c = l[0]
443 else:
444 c = ' '
446 if c != prev:
447 if c == '+': style = 'new'
448 elif c == '-': style = 'remove'
449 elif c == '@': style = 'head'
450 else: style = 'std'
451 ret.extend(['</font><font color="', colors[style], '">'])
452 prev = c
453 line = qt.QStyleSheet.escape(l).ascii()
454 if not line:
455 line = ''
456 else:
457 line = str(line)
458 ret.extend([line, '\n'])
459 ret.append('</pre></qt>')
460 return ''.join(ret)
462 def getEditor():
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']
467 else:
468 return None
470 scm.initialize()
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'
485 sys.exit(0)
487 mw.resize(settings().width, settings().height)
489 mw.show()
490 app.setMainWidget(mw)
493 # Handle CTRL-C appropriately
494 signal.signal(signal.SIGINT, lambda s, f: app.quit())
496 ret = app.exec_loop()
497 settings().writeSettings()
498 sys.exit(ret)