Be more careful in what files are considered to be the same file.
[hgct.git] / main.py
blob5563bd144b755f5b5510e0bde8e4c92031a2fbc4
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 FileState:
35 pass
37 class MyListItem(qt.QCheckListItem):
38 def __init__(self, parent, file, commitMsg = False):
39 qt.QCheckListItem.__init__(self, parent, file.text, qt.QCheckListItem.CheckBox)
40 self.file = file
41 self.commitMsg = commitMsg
43 def compare(self, item, col, asc):
44 if self.commitMsg:
45 if asc:
46 return -1
47 else:
48 return 1
49 elif item.commitMsg:
50 if asc:
51 return 1
52 else:
53 return -1
54 else:
55 return cmp(self.file.srcName, item.file.srcName)
57 def paintCell(self, p, cg, col, w, a):
58 if self.commitMsg:
59 qt.QListViewItem.paintCell(self, p, cg, col, w, a)
60 else:
61 qt.QCheckListItem.paintCell(self, p, cg, col, w, a)
63 def isSelected(self):
64 return self.state() == qt.QCheckListItem.On
66 def setSelected(self, s):
67 if s:
68 self.setState(qt.QCheckListItem.On)
69 else:
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)
76 def __iter__(self):
77 return ListViewIterator(self)
79 class ListViewIterator:
80 def __init__(self, listview):
81 self.it = qt.QListViewItemIterator(listview)
83 def next(self):
84 cur = self.it.current()
85 if cur:
86 self.it += 1
87 if cur.commitMsg:
88 return self.next()
89 else:
90 return cur
91 else:
92 raise StopIteration()
94 def __iter__(self):
95 return self
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)
101 self.statusBar()
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)
110 # The file list
111 fW = MyListView(self.filesLayout)
112 self.filesW = fW
113 fW.setFocus()
114 fW.setSelectionMode(qt.QListView.NoSelection)
115 fW.addColumn('Description')
116 fW.setResizeMode(qt.QListView.AllColumns)
118 # The file filter
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,
141 Qt.CTRL+Qt.Key_U)
142 ops.insertItem("Preferences...", self.showPrefs, Qt.CTRL+Qt.Key_P)
143 ops.setItemChecked(self.showUnknownItem, settings().showUnknown)
144 self.operations = ops
146 m = self.menuBar()
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))
169 f = File()
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)
177 self.cmitFile = f
178 self.createCmitItem()
179 self.editorProcesses = sets.Set()
180 self.loadSettings()
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):
196 s = self.size()
197 settings().width = s.width()
198 settings().height = s.height()
199 settings().splitter = self.splitter.sizes()
200 e.accept()
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 &copy; 2005 Fredrik Kuivinen &lt;freku045@student.liu.se&gt;
212 </center>\n<p>
213 <center>Copyright &copy; 2005 Mark Williamson &lt;maw48@cl.cam.ac.uk&gt;
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())
222 else:
223 self.currentContextItem = None
225 def toggleFile(self, ignored):
226 it = self.currentContextItem
227 if not it:
228 return
230 if it.isSelected():
231 it.setSelected(False)
232 else:
233 it.setSelected(True)
235 def editFile(self, ignored):
236 it = self.currentContextItem
237 if not it:
238 return
240 ed = getEditor()
241 if not ed:
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
245 EDITOR.''')
246 return
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.
254 p = qt.QProcess(ed)
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)
263 else:
264 self.editorProcesses.add(p)
266 def editorExited(self):
267 p = self.sender()
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.')
274 elif status != 0:
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)
280 self.refreshFiles()
282 def discardFile(self, ignored):
283 it = self.currentContextItem
284 if not it:
285 return
287 scm.discardFile(it.file)
288 self.refreshFiles()
290 def ignoreFile(self, ignored):
291 it = self.currentContextItem
292 if not it:
293 return
295 scm.ignoreFile(it.file)
296 self.refreshFiles()
298 def currentChange(self, item):
299 f = item.file
300 if not f.textW:
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
308 if item.commitMsg:
309 self.updateCommitCursor()
311 def commit(self, id):
312 selFileNames = []
313 keepFiles = []
314 commitFiles = []
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)
321 else:
322 keepFiles.append(item.file)
324 commitMsg = unicode(self.cmitItem.file.textW.text())
326 if not selFileNames:
327 qt.QMessageBox.information(self, "Commit - " + applicationName,
328 "No files selected for commit.", "&Ok")
329 return
331 commitMsg = fixCommitMsgWhiteSpace(commitMsg)
332 if scm.commitIsMerge():
333 mergeMsg = scm.mergeMessage()
334 else:
335 mergeMsg = ''
337 commitDialog = CommitDialog(mergeMsg, commitMsg, selFileNames)
338 if commitDialog.exec_loop():
339 try:
340 scm.doCommit(keepFiles, commitFiles, commitMsg)
341 except ProgramError, e:
342 qt.QMessageBox.warning(self, "Commit Failed - " + applicationName,
343 "Commit failed: " + str(e),
344 '&Ok')
345 else:
346 if not self.options.oneshot:
347 self.cmitItem.file.textW.setText(settings().signoff)
348 self.refreshFiles()
349 self.statusBar().message('Commit done')
351 if self.options.oneshot:
352 self.close()
354 def getFileState(self):
355 ret = FileState()
356 cur = self.filesW.currentItem()
357 if cur and cur != self.cmitItem:
358 ret.current = self.filesW.currentItem().file.text
359 else:
360 ret.current = None
361 ret.selected = sets.Set()
363 for x in self.filesW:
364 if x.isSelected():
365 ret.selected.add(x.file.text)
367 return ret
369 def restoreFileState(self, state):
370 for f in self.files:
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):
378 ret = qt.QTextEdit()
379 self.text.addWidget(ret)
380 return ret
382 def addFile(self, file):
383 f = 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):
395 f = 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)
412 self.update()
414 if settings().quitOnNoChanges and len(self.files) == 0:
415 self.close()
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):
429 all = False
430 for x in self.filesW:
431 if x.isVisible():
432 if not x.isSelected():
433 x.setSelected(True)
434 all = True
436 if not all:
437 for x in self.filesW:
438 if x.isVisible():
439 x.setSelected(False)
441 def toggleShowUnknown(self):
442 if settings().showUnknown:
443 settings().showUnknown = False
444 else:
445 settings().showUnknown = True
447 self.operations.setItemChecked(self.showUnknownItem, settings().showUnknown)
448 self.refreshFiles()
450 def showPrefs(self):
451 if settings().showSettings():
452 self.refreshFiles()
454 commitMsgRE = re.compile('[ \t\r\f\v]*\n\\s*\n')
455 def fixCommitMsgWhiteSpace(msg):
456 msg = msg.lstrip()
457 msg = msg.rstrip()
458 msg = re.sub(commitMsgRE, '\n\n', msg)
459 msg += '\n'
460 return msg
462 def formatPatchRichText(patch, colors):
463 ret = ['<qt><pre><font color="', colors['std'], '">']
464 prev = ' '
465 for l in patch.split('\n'):
466 if len(l) > 0:
467 c = l[0]
468 else:
469 c = ' '
471 if c != prev:
472 if c == '+': style = 'new'
473 elif c == '-': style = 'remove'
474 elif c == '@': style = 'head'
475 else: style = 'std'
476 ret.extend(['</font><font color="', colors[style], '">'])
477 prev = c
478 line = unicode(qt.QStyleSheet.escape(l))
479 ret.extend([line, '\n'])
480 ret.append('</pre></qt>')
481 return u''.join(ret)
483 def getEditor():
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']
488 else:
489 return None
491 class EventFilter(qt.QObject):
492 def __init__(self, parent, mainWidget):
493 qt.QObject.__init__(self, parent)
494 self.mw = mainWidget
496 def eventFilter(self, watched, e):
497 if (e.type() == qt.QEvent.KeyRelease or \
498 e.type() == qt.QEvent.MouseButtonRelease):
499 self.mw.updateStatusBar()
501 return False
503 def main():
504 scm.initialize()
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'
521 sys.exit(0)
523 mw.resize(settings().width, settings().height)
525 mw.show()
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()
533 sys.exit(ret)
535 if executeMain:
536 main()