pydev-cvs Mailing List for PyDev for Eclipse (Page 303)
Brought to you by:
fabioz
You can subscribe to this list here.
2004 |
Jan
|
Feb
(4) |
Mar
(48) |
Apr
(56) |
May
(64) |
Jun
(27) |
Jul
(66) |
Aug
(81) |
Sep
(148) |
Oct
(194) |
Nov
(78) |
Dec
(46) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2005 |
Jan
(125) |
Feb
(126) |
Mar
(163) |
Apr
(133) |
May
(115) |
Jun
(307) |
Jul
(387) |
Aug
(417) |
Sep
(283) |
Oct
(148) |
Nov
(45) |
Dec
(53) |
2006 |
Jan
(240) |
Feb
(200) |
Mar
(267) |
Apr
(231) |
May
(245) |
Jun
(361) |
Jul
(142) |
Aug
(12) |
Sep
(210) |
Oct
(99) |
Nov
(7) |
Dec
(30) |
2007 |
Jan
(161) |
Feb
(511) |
Mar
(265) |
Apr
(74) |
May
(147) |
Jun
(151) |
Jul
(94) |
Aug
(68) |
Sep
(98) |
Oct
(144) |
Nov
(26) |
Dec
(36) |
2008 |
Jan
(98) |
Feb
(107) |
Mar
(199) |
Apr
(113) |
May
(119) |
Jun
(112) |
Jul
(92) |
Aug
(71) |
Sep
(101) |
Oct
(16) |
Nov
|
Dec
|
From: Fabio Z. <fa...@us...> - 2004-09-16 15:33:44
|
Update of /cvsroot/pydev/org.python.pydev In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv26116 Modified Files: plugin.xml Log Message: Making refactoring. Index: plugin.xml =================================================================== RCS file: /cvsroot/pydev/org.python.pydev/plugin.xml,v retrieving revision 1.36 retrieving revision 1.37 diff -C2 -d -r1.36 -r1.37 *** plugin.xml 15 Sep 2004 17:36:09 -0000 1.36 --- plugin.xml 16 Sep 2004 15:33:34 -0000 1.37 *************** *** 4,8 **** id="org.python.pydev" name="Pydev - Python Development Environment" ! version="0.5.9.5a" provider-name="AleksTotic" class="org.python.pydev.plugin.PydevPlugin"> --- 4,8 ---- id="org.python.pydev" name="Pydev - Python Development Environment" ! version="0.5.9.5b" provider-name="AleksTotic" class="org.python.pydev.plugin.PydevPlugin"> |
From: Fabio Z. <fa...@us...> - 2004-09-16 15:32:55
|
Update of /cvsroot/pydev/org.python.pydev/PySrc/ThirdParty/brm/bike/query In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv25869/PySrc/ThirdParty/brm/bike/query Modified Files: common.py Log Message: Making refactoring. Index: common.py =================================================================== RCS file: /cvsroot/pydev/org.python.pydev/PySrc/ThirdParty/brm/bike/query/common.py,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** common.py 14 Sep 2004 17:42:08 -0000 1.1 --- common.py 16 Sep 2004 15:32:44 -0000 1.2 *************** *** 55,59 **** if line.find(targetname) != -1: doctoredline = makeLineParseable(line) ! ast = compiler.parse(doctoredline) scope = getScopeForLine(sourcenode, lineno) matchFinder.reset(line) --- 55,63 ---- if line.find(targetname) != -1: doctoredline = makeLineParseable(line) ! try: ! ast = compiler.parse(doctoredline) ! except : ! print >> log.warning , 'Error parsing: %s' % doctoredline ! raise scope = getScopeForLine(sourcenode, lineno) matchFinder.reset(line) *************** *** 197,201 **** if word == "*": return # won't be able to find this ! posInWords = self.words.index(word) idx = self.positions[posInWords] self.words = self.words[posInWords+1:] --- 201,215 ---- if word == "*": return # won't be able to find this ! try: ! posInWords = self.words.index(word) ! except ValueError: ! print >> log.warning , 'ValueError raised (communicate to bicycle repair man plugin).' ! print >> log.warning , 'code that raised error (commom.py): posInWords = self.words.index(word)' ! try: ! print >> log.warning , 'WORD: %s'%word ! except TypeError: ! print >> log.warning , 'Unable to get word.' ! print >> log.warning , 'SELF.WORDS: %s'%self.words ! return idx = self.positions[posInWords] self.words = self.words[posInWords+1:] |
From: Fabio Z. <fa...@us...> - 2004-09-16 15:28:51
|
Update of /cvsroot/pydev/org.python.pydev/PySrc/aRefactoring In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv24791/PySrc/aRefactoring Added Files: Refactoring.py MatchesForm.ui MatchesForm.py MatchesDialog.py __init__.py Log Message: changed package name (this package is just for reference). --- NEW FILE: MatchesForm.py --- # -*- coding: utf-8 -*- # Form implementation generated from reading ui file '/home/detlev/Development/Python/Eric/eric3/Refactoring/MatchesForm.ui' # # Created: Mit Aug 13 21:23:54 2003 # by: The PyQt User Interface Compiler (pyuic) 3.7 # # WARNING! All changes made in this file will be lost! import sys from qt import * class MatchesForm(QDialog): def __init__(self,parent = None,name = None,modal = 0,fl = 0): QDialog.__init__(self,parent,name,modal,fl) if not name: self.setName("MatchesForm") self.setSizeGripEnabled(1) MatchesFormLayout = QVBoxLayout(self,6,6,"MatchesFormLayout") self.matchesList = QListView(self,"matchesList") self.matchesList.addColumn(self.__tr("Filename")) self.matchesList.addColumn(self.__tr("Line")) self.matchesList.addColumn(self.__tr("Confidence [%]")) self.matchesList.setAllColumnsShowFocus(1) self.matchesList.setShowSortIndicator(1) MatchesFormLayout.addWidget(self.matchesList) layout1 = QHBoxLayout(None,0,6,"layout1") spacer = QSpacerItem(40,20,QSizePolicy.Expanding,QSizePolicy.Minimum) layout1.addItem(spacer) self.closeButton = QPushButton(self,"closeButton") layout1.addWidget(self.closeButton) spacer_2 = QSpacerItem(40,20,QSizePolicy.Expanding,QSizePolicy.Minimum) layout1.addItem(spacer_2) MatchesFormLayout.addLayout(layout1) self.languageChange() self.resize(QSize(649,480).expandedTo(self.minimumSizeHint())) self.clearWState(Qt.WState_Polished) self.connect(self.closeButton,SIGNAL("clicked()"),self,SLOT("close()")) self.connect(self.matchesList,SIGNAL("doubleClicked(QListViewItem*)"),self.handleDoubleClicked) def languageChange(self): self.setCaption(self.__tr("Refactoring Matches")) self.matchesList.header().setLabel(0,self.__tr("Filename")) self.matchesList.header().setLabel(1,self.__tr("Line")) self.matchesList.header().setLabel(2,self.__tr("Confidence [%]")) self.closeButton.setText(self.__tr("&Close")) def handleDoubleClicked(self,a0): print "MatchesForm.handleDoubleClicked(QListViewItem*): Not implemented yet" def __tr(self,s,c = None): return qApp.translate("MatchesForm",s,c) if __name__ == "__main__": a = QApplication(sys.argv) QObject.connect(a,SIGNAL("lastWindowClosed()"),a,SLOT("quit()")) w = MatchesForm() a.setMainWidget(w) w.show() a.exec_loop() --- NEW FILE: MatchesDialog.py --- # -*- coding: utf-8 -*- # Copyright (c) 2003 Detlev Offenbach <de...@di...> # from qt import * from MatchesForm import MatchesForm """ Module implementing a dialog to show matching references/definitions. """ class MatchesDialog(MatchesForm): """ Class implementing a dialog to show matching references/definitions. """ def __init__(self,ui,parent = None,name = None,modal = 0,fl = 0): """ Constructor @param ui reference to the UI object @param parent parent of this dialog (QWidget) @param name name of this dialog (string or QString) @param modal flag indicating a modal window (boolean) @param fl window flags """ MatchesForm.__init__(self,parent,name,modal,fl) self.ui = ui self.matchesList.setSorting(0) self.matchesList.setColumnAlignment(1, Qt.AlignRight) self.matchesList.setColumnAlignment(2, Qt.AlignRight) dummy = self.trUtf8("Dummy") def handleDoubleClicked(self, itm): """ Private slot to handle the DoubleClicked signal of the list. """ lineno = int(str(itm.text(1))) fn = str(itm.text(0)) self.ui.getViewManager().displayPythonFile(fn, lineno) def addEntry(self, ref): """ Public slot to add a reference to the listview. """ itm = QListViewItem(self.matchesList, ref.filename, " %5d" % ref.lineno, " %5d" % ref.confidence) --- NEW FILE: MatchesForm.ui --- <!DOCTYPE UI><UI version="3.1" stdsetdef="1"> <class>MatchesForm</class> <widget class="QDialog"> <property name="name"> <cstring>MatchesForm</cstring> </property> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>649</width> <height>480</height> </rect> </property> <property name="caption"> <string>Refactoring Matches</string> </property> <property name="sizeGripEnabled"> <bool>true</bool> </property> <vbox> <property name="name"> <cstring>unnamed</cstring> </property> <widget class="QListView"> <column> <property name="text"> <string>Filename</string> </property> <property name="clickable"> <bool>true</bool> </property> <property name="resizable"> <bool>true</bool> </property> </column> <column> <property name="text"> <string>Line</string> </property> <property name="clickable"> <bool>true</bool> </property> <property name="resizable"> <bool>true</bool> </property> </column> <column> <property name="text"> <string>Confidence [%]</string> </property> <property name="clickable"> <bool>true</bool> </property> <property name="resizable"> <bool>true</bool> </property> </column> <property name="name"> <cstring>matchesList</cstring> </property> <property name="allColumnsShowFocus"> <bool>true</bool> </property> <property name="showSortIndicator"> <bool>true</bool> </property> </widget> <widget class="QLayoutWidget"> <property name="name"> <cstring>layout1</cstring> </property> <hbox> <property name="name"> <cstring>unnamed</cstring> </property> <spacer> <property name="name"> <cstring>spacer1</cstring> </property> <property name="orientation"> <enum>Horizontal</enum> </property> <property name="sizeType"> <enum>Expanding</enum> </property> <property name="sizeHint"> <size> <width>40</width> <height>20</height> </size> </property> </spacer> <widget class="QPushButton"> <property name="name"> <cstring>closeButton</cstring> </property> <property name="text"> <string>&Close</string> </property> </widget> <spacer> <property name="name"> <cstring>spacer2</cstring> </property> <property name="orientation"> <enum>Horizontal</enum> </property> <property name="sizeType"> <enum>Expanding</enum> </property> <property name="sizeHint"> <size> <width>40</width> <height>20</height> </size> </property> </spacer> </hbox> </widget> </vbox> </widget> <connections> <connection> <sender>closeButton</sender> <signal>clicked()</signal> <receiver>MatchesForm</receiver> <slot>close()</slot> </connection> <connection> <sender>matchesList</sender> <signal>doubleClicked(QListViewItem*)</signal> <receiver>MatchesForm</receiver> <slot>handleDoubleClicked(QListViewItem*)</slot> </connection> </connections> <slots> <slot>handleDoubleClicked(QListViewItem*)</slot> </slots> <layoutdefaults spacing="6" margin="6"/> </UI> --- NEW FILE: __init__.py --- # -*- coding: utf-8 -*- # Copyright (c) 2003 Detlev Offenbach <de...@di...> # """ Package implementing the refactoring interface module of eric3. This package implements just the interface for the eric3 IDE. The refactoring is done using the Bicyle Repair Man (brm) software (<a href="http://bicyclerepair.sourceforge.net">http://bicyclerepair.sourceforge.net</a>). """ --- NEW FILE: Refactoring.py --- # -*- coding: utf-8 -*- # Copyright (c) 2003 Detlev Offenbach <de...@di...> # """ Module implementing the refactoring interface to brm. """ import os import sys sys.path.insert(1, os.path.join(os.path.dirname(sys.argv[0]), "ThirdParty", "brm")) import ThirdParty.brm.bike as bike from qt import * from MatchesDialog import MatchesDialog import Utilities import Preferences BRM_VERSION_STR = '0.9 cvs20040211' class SilentLogger: """ Class implementing a logger that doesn't log anything. """ def write(*args): """ Public method to write the arguments. """ pass class Refactoring(QObject): """ Class implementing the refactoring interface to brm. """ def __init__(self, parent = None, *args): """ Constructor @param parent parent (QObject) @param *args arguments passed on to QObject """ QObject.__init__(*(self, parent) + args) self.ui = parent self.projectpath = '' self.projectopen = 0 self.refreshing = 0 self.matchesDialog = None self.init() def initActions(self): """ Public method to define the refactoring actions. """ self.resetBRMAct = QAction(self.trUtf8('Reset'), self.trUtf8('Re&set'),0, self) self.resetBRMAct.setStatusTip(self.trUtf8('Reset the refactoring machine')) self.resetBRMAct.setWhatsThis(self.trUtf8( """<b>Reset</b>""" """<p>Reset the refactoring machine.</p>""" )) self.connect(self.resetBRMAct,SIGNAL('activated()'),self.handleReset) self.queryReferencesAct = QAction(self.trUtf8('Find references'), self.trUtf8('Find &References'),0, self) self.queryReferencesAct.setStatusTip(self.trUtf8('Find references of the highlighted item')) self.queryReferencesAct.setWhatsThis(self.trUtf8( """<b>Find references</b>""" """<p>Find references to the highlighted class, method, function or variable.</p>""" )) self.connect(self.queryReferencesAct,SIGNAL('activated()'),self.handleQueryReferences) self.queryDefinitionAct = QAction(self.trUtf8('Find definition'), self.trUtf8('Find &Definition'),0, self) self.queryDefinitionAct.setStatusTip(self.trUtf8('Find definition of the highlighted item')) self.queryDefinitionAct.setWhatsThis(self.trUtf8( """<b>Find definition</b>""" """<p>Find the definition to the highlighted class, method, function or variable.</p>""" )) self.connect(self.queryDefinitionAct,SIGNAL('activated()'),self.handleQueryDefinition) self.refactoringRenameAct = QAction(self.trUtf8('Rename'), self.trUtf8('&Rename'),0, self) self.refactoringRenameAct.setStatusTip(self.trUtf8('Rename the highlighted item')) self.refactoringRenameAct.setWhatsThis(self.trUtf8( """<b>Rename</b>""" """<p>Rename the highlighted class, method, function or variable.</p>""" )) self.connect(self.refactoringRenameAct,SIGNAL('activated()'),self.handleRename) self.refactoringExtractMethodAct = QAction(self.trUtf8('Extract method'), self.trUtf8('Extract &Method'),0, self) self.refactoringExtractMethodAct.setStatusTip(self.trUtf8('Extract the highlighted area as a method')) self.refactoringExtractMethodAct.setWhatsThis(self.trUtf8( """<b>Extract method</b>""" """<p>Extract the highlighted area as a method or function.</p>""" )) self.connect(self.refactoringExtractMethodAct,SIGNAL('activated()'),self.handleExtractMethod) self.refactoringInlineLocalVariableAct = QAction(self.trUtf8('Inline local variable'), self.trUtf8('&Inline Local Variable'),0, self) self.refactoringInlineLocalVariableAct.setStatusTip(self.trUtf8('Inlines the selected local variable')) self.refactoringInlineLocalVariableAct.setWhatsThis(self.trUtf8( """<b>Inline local variable</b>""" """<p>Inlines the selected local variable.</p>""" )) self.connect(self.refactoringInlineLocalVariableAct,SIGNAL('activated()'),self.handleInlineLocalVariable) self.refactoringExtractLocalVariableAct = QAction(self.trUtf8('Extract local variable'), self.trUtf8('Extract Local &Variable'),0, self) self.refactoringExtractLocalVariableAct.setStatusTip(self.trUtf8('Extract the highlighted area as a local variable')) self.refactoringExtractLocalVariableAct.setWhatsThis(self.trUtf8( """<b>Extract local variable</b>""" """<p>Extract the highlighted area as a local variable.</p>""" )) self.connect(self.refactoringExtractLocalVariableAct,SIGNAL('activated()'),self.handleExtractLocalVariable) self.refactoringUndoAct = QAction(self.trUtf8('Undo'), self.trUtf8('&Undo'),0, self) self.refactoringUndoAct.setStatusTip(self.trUtf8('Undo refactorings')) self.refactoringUndoAct.setWhatsThis(self.trUtf8( """<b>Undo</b>""" """<p>Undo the performed refactorings.</p>""" )) self.connect(self.refactoringUndoAct,SIGNAL('activated()'),self.handleUndo) self.refactoringMoveClassAct = QAction(self.trUtf8('Move Class'), self.trUtf8('Move &Class'),0, self) self.refactoringMoveClassAct.setStatusTip(self.trUtf8('Move class to new module')) self.refactoringMoveClassAct.setWhatsThis(self.trUtf8( """<b>Move class</b>""" """<p>Moves the class pointed to by the cursor to a new module.</p>""" )) self.connect(self.refactoringMoveClassAct,SIGNAL('activated()'),self.handleMoveClass) self.refactoringMoveFunctionAct = QAction(self.trUtf8('Move Function'), self.trUtf8('Move &Function'),0, self) self.refactoringMoveFunctionAct.setStatusTip(self.trUtf8('Move function to new module')) self.refactoringMoveFunctionAct.setWhatsThis(self.trUtf8( """<b>Move function</b>""" """<p>Moves the function pointed to by the cursor to a new module.</p>""" )) self.connect(self.refactoringMoveFunctionAct,SIGNAL('activated()'),self.handleMoveFunction) # disable some action until the code behind them works reliably self.refactoringMoveClassAct.setEnabled(0) self.refactoringMoveFunctionAct.setEnabled(0) def initMenu(self): """ Public slot to initialize the refactoring menu. @return the menu generated (QPopupMenu) """ self.menuitems = [] menu = QPopupMenu(self.ui) lbl = QLabel('Bicycle Repair Man', menu) lbl.setFrameStyle( QFrame.Panel | QFrame.Sunken ) lbl.setAlignment(Qt.AlignHCenter) font = lbl.font() font.setBold(1) lbl.setFont(font) menu.insertItem(lbl) menu.insertTearOffHandle() smenu = QPopupMenu(self.ui) self.queryReferencesAct.addTo(smenu) self.queryDefinitionAct.addTo(smenu) self.menuitems.append(menu.insertItem(self.trUtf8("&Query"), smenu)) smenu = QPopupMenu(self.ui) self.refactoringRenameAct.addTo(smenu) smenu.insertSeparator() self.refactoringExtractMethodAct.addTo(smenu) smenu.insertSeparator() self.refactoringInlineLocalVariableAct.addTo(smenu) self.refactoringExtractLocalVariableAct.addTo(smenu) smenu.insertSeparator() self.refactoringMoveClassAct.addTo(smenu) self.refactoringMoveFunctionAct.addTo(smenu) smenu.insertSeparator() self.refactoringUndoAct.addTo(smenu) self.menuitems.append(menu.insertItem(self.trUtf8("&Refactoring"), smenu)) menu.insertSeparator() self.resetBRMAct.addTo(menu) self.menu = menu return menu def init(self): """ Private slot to handle the Reset action. """ self.brmctx = bike.init() self.logging = Preferences.getRefactoring("Logging") if self.logging: self.brmctx.setProgressLogger(self.ui.stdout) else: self.brmctx.setProgressLogger(SilentLogger()) self.brmctx.setWarningLogger(self.ui.stderr) def handleReset(self): """ Private slot to handle the Reset action. """ self.init() ################################################################## ## methods below are handling the various Query actions ################################################################## def handleQueryReferences(self): """ Private slot to handle the Query References action. """ self.showOutput() aw = self.ui.getViewManager().activeWindow() if aw is None: return if not aw.hasSelectedText(): # no selection available QMessageBox.warning(self.ui, self.trUtf8("Query References"), self.trUtf8("Highlight the name of a Function, Class or Method and try again."), self.trUtf8("&OK")) return if not self.confirmAllBuffersSaved(): return filename = aw.getFileName() line, column, dummy1, dummy2 = aw.getSelection() qApp.setOverrideCursor(Qt.waitCursor) qApp.processEvents() self.matchesDialog = None if self.projectopen: sys.path.insert(0, self.projectpath) try: try: for ref in self.brmctx.findReferencesByCoordinates(filename, line + 1, column): if self.matchesDialog is None: self.matchesDialog = MatchesDialog(self.ui) self.matchesDialog.show() self.matchesDialog.addEntry(ref) except AssertionError: pass except Exception, e: self.__unhandledException(e) finally: if self.projectopen: del sys.path[0] qApp.restoreOverrideCursor() if self.matchesDialog is None: QMessageBox.information(self.ui, self.trUtf8("Query References"), self.trUtf8("No matches were found."), self.trUtf8("&OK")) def handleQueryDefinition(self): """ Private slot to handle the Query Definition action """ self.showOutput() aw = self.ui.getViewManager().activeWindow() if aw is None: return if not self.confirmAllBuffersSaved(): return filename = aw.getFileName() if aw.hasSelectedText(): line, column, dummy1, dummy2 = aw.getSelection() else: line, column = aw.getCursorPosition() qApp.setOverrideCursor(Qt.waitCursor) qApp.processEvents() if self.projectopen: sys.path.insert(0, self.projectpath) try: try: defns = self.brmctx.findDefinitionByCoordinates(filename, line + 1, column) try: firstref = defns.next() self.ui.getViewManager().displayPythonFile(firstref.filename, firstref.lineno) except StopIteration: QMessageBox.information(self.ui, self.trUtf8("Query Definition"), self.trUtf8("Definition wasn't found."), self.trUtf8("&OK")) else: self.matchesDialog = None for ref in defns: if self.matchesDialog is None: self.matchesDialog = MatchesDialog(self.ui) self.matchesDialog.show() self.matchesDialog.addEntry(firstref) self.matchesDialog.addEntry(ref) except AssertionError: pass except Exception, e: self.__unhandledException(e) finally: if self.projectopen: del sys.path[0] qApp.restoreOverrideCursor() ################################################################## ## methods below are handling the various Refactoring actions ################################################################## def renameMethodPromptCallback(self, filename, line, start, stop): """ Private slot called by the refactoring machine to ask the user for confirmation. @param filename the name of the file (string) @param line the line of the object (int) @param start beginning column of the object (int) @param stop end column of the object (int) @return flag indicating renaming wanted (boolean) """ vm = self.ui.getViewManager() # display the file and select the method call vm.displayPythonFile(filename) aw = vm.activeWindow() cline, cindex = aw.getCursorPosition() aw.ensureLineVisible(line-1) aw.gotoLine(line-1) aw.setSelection(line-1, start, line-1, stop) ans = QMessageBox.information(self.ui, self.trUtf8("Rename"), self.trUtf8("Cannot deduce the type of the highlighted object reference.<br>" "Rename this declaration?"), self.trUtf8("&Yes"), self.trUtf8("&No")) aw.setCursorPosition(cline, cindex) aw.ensureCursorVisible() return ans == 0 def refreshEditors(self, savedfiles, filename, line): """ Private method to refresh modified editors. @param savedfiles list of filenames of modified files (list of strings) @param filename filename of the active editor (string) @param line line to place cursor at (int) """ vm = self.ui.getViewManager() openFiles = vm.getOpenFilenames() self.refreshing = 1 for file in savedfiles: normfile = Utilities.normcasepath(file) if normfile in openFiles: dummy, editor = vm.getEditor(normfile) editor.refresh() if filename is not None: vm.displayPythonFile(filename, line) self.refreshing = 0 def handleRename(self): """ Private slot to handle the Rename action. """ self.showOutput() aw = self.ui.getViewManager().activeWindow() if aw is None: return if not aw.hasSelectedText(): # no selection available QMessageBox.warning(self.ui, self.trUtf8("Rename"), self.trUtf8("Highlight the declaration you want to rename and try again."), self.trUtf8("&OK")) return if not self.confirmAllBuffersSaved(): return filename = aw.getFileName() line, column, dummy1, dummy2 = aw.getSelection() if self.projectopen: sys.path.insert(0, self.projectpath) try: try: self.brmctx.setRenameMethodPromptCallback(self.renameMethodPromptCallback) newname, ok = QInputDialog.getText(self.trUtf8("Rename"), self.trUtf8("Rename to:")) if not ok or newname.isEmpty(): return # user pressed cancel or didn't enter anything self.brmctx.renameByCoordinates(filename, line+1, column, str(newname)) savedfiles = self.brmctx.save() self.refreshEditors(savedfiles, filename, line+1) except AssertionError: pass except Exception, e: self.__unhandledException(e) finally: if self.projectopen: del sys.path[0] def handleExtractMethod(self): """ Private slot to handle the Extract Method action. """ self.showOutput() aw = self.ui.getViewManager().activeWindow() if aw is None: return if not aw.hasSelectedText(): # no selection available QMessageBox.warning(self.ui, self.trUtf8("Extract Method"), self.trUtf8("Highlight the region of code you want to extract and try again."), self.trUtf8("&OK")) return if not self.confirmAllBuffersSaved(): return filename = aw.getFileName() startline, startcolumn, endline, endcolumn = aw.getSelection() newname, ok = QInputDialog.getText(self.trUtf8("Extract Method"), self.trUtf8("New Name:")) if not ok or newname.isEmpty(): return # user pressed cancel or didn't enter anything if self.projectopen: sys.path.insert(0, self.projectpath) try: try: self.brmctx.extractMethod(filename, startline+1, startcolumn, endline+1, endcolumn, str(newname)) savedfiles = self.brmctx.save() self.refreshEditors(savedfiles, filename, startline+1) except AssertionError: pass except Exception, e: self.__unhandledException(e) finally: if self.projectopen: del sys.path[0] def handleInlineLocalVariable(self): """ Private slot to handle the Inline Local Variable action. """ self.showOutput() aw = self.ui.getViewManager().activeWindow() if aw is None: return if not self.confirmAllBuffersSaved(): return filename = aw.getFileName() if aw.hasSelectedText(): line, column, dummy1, dummy2 = aw.getSelection() else: line, column = aw.getCursorPosition() if self.projectopen: sys.path.insert(0, self.projectpath) try: try: self.brmctx.inlineLocalVariable(filename, line+1, column) savedfiles = self.brmctx.save() self.refreshEditors(savedfiles, filename, line+1) except AssertionError: pass except Exception, e: self.__unhandledException(e) finally: if self.projectopen: del sys.path[0] def handleExtractLocalVariable(self): """ Private slot to handle the Extract Local Variable action. """ self.showOutput() aw = self.ui.getViewManager().activeWindow() if aw is None: return if not aw.hasSelectedText(): # no selection available QMessageBox.warning(self.ui, self.trUtf8("Extract Local Variable"), self.trUtf8("Highlight the region of code you want to extract and try again."), self.trUtf8("&OK")) return if not self.confirmAllBuffersSaved(): return filename = aw.getFileName() startline, startcolumn, endline, endcolumn = aw.getSelection() newname, ok = QInputDialog.getText(self.trUtf8("Extract Local Variable"), self.trUtf8("New Name:")) if not ok or newname.isEmpty(): return # user pressed cancel or didn't enter anything if self.projectopen: sys.path.insert(0, self.projectpath) try: try: self.brmctx.extractLocalVariable(filename, startline+1, startcolumn, endline+1, endcolumn, str(newname)) savedfiles = self.brmctx.save() self.refreshEditors(savedfiles, filename, startline+1) except AssertionError: pass except Exception, e: self.__unhandledException(e) finally: if self.projectopen: del sys.path[0] def handleMoveClass(self): """ Private slot to handle the Move Class action. """ self.showOutput() aw = self.ui.getViewManager().activeWindow() if aw is None: return if not self.confirmAllBuffersSaved(): return filename = aw.getFileName() line, column = aw.getCursorPosition() newname = QFileDialog.getSaveFileName(\ None, self.trUtf8("Python Files (*.py)"), None, None, self.trUtf8("New Module"), None, 1) if newname.isEmpty(): return # user pressed cancel or didn't enter anything newname = str(newname) if not newname.endswith('.py'): newname = "%s.py" % newname if not os.path.exists(newname): try: f = open(newname, "w") f.close() except Exception, e: self.__unhandledException(e) return if self.projectopen: sys.path.insert(0, self.projectpath) try: try: self.brmctx.moveClassToNewModule(filename, line+1, str(newname)) savedfiles = self.brmctx.save() self.refreshEditors(savedfiles, filename, line+1) except AssertionError: pass except Exception, e: self.__unhandledException(e) finally: if self.projectopen: del sys.path[0] def handleMoveFunction(self): """ Private slot to handle the Move Function action. """ self.showOutput() aw = self.ui.getViewManager().activeWindow() if aw is None: return if not self.confirmAllBuffersSaved(): return filename = aw.getFileName() line, column = aw.getCursorPosition() newname = QFileDialog.getSaveFileName(\ None, self.trUtf8("Python Files (*.py)"), None, None, self.trUtf8("New Module"), None, 1) if newname.isEmpty(): return # user pressed cancel or didn't enter anything newname = str(newname) if not newname.endswith('.py'): newname = "%s.py" % newname if not os.path.exists(newname): try: f = open(newname, "w") f.close() except Exception, e: self.__unhandledException(e) return if self.projectopen: sys.path.insert(0, self.projectpath) try: try: self.brmctx.moveFunctionToNewModule(filename, line+1, str(newname)) savedfiles = self.brmctx.save() self.refreshEditors(savedfiles, filename, line+1) except AssertionError: pass except Exception, e: self.__unhandledException(e) finally: if self.projectopen: del sys.path[0] def handleUndo(self): """ Private slot to handle the Undo action. """ self.showOutput() aw = self.ui.getViewManager().activeWindow() if aw is not None: filename = aw.getFileName() line, column = aw.getCursorPosition() else: filename = None line = 0 try: try: self.brmctx.undo() except bike.UndoStackEmptyException: QMessageBox.information(self.ui, self.trUtf8("Undo"), self.trUtf8("The Undo stack is empty."), self.trUtf8("&OK")) savedfiles = self.brmctx.save() self.refreshEditors(savedfiles, filename, line+1) except AssertionError: pass except Exception, e: self.__unhandledException(e) ################################################################## ## methods below are private utility methods ################################################################## def confirmBufferIsSaved(self, editor): """ Private method to check, if an editor has unsaved changes. @param editor Reference to the editor to be checked. """ return editor.checkDirty() def confirmAllBuffersSaved(self): """ Private method to check, if any editor has unsaved changes. """ return self.ui.getViewManager().checkAllDirty() def setMenuItemsEnabled(self, enabled): """ Private method to enable/disable menu items. @param enabled Flag indicating enabled or disabled status. (boolean) """ for itm in self.menuitems: self.menu.setItemEnabled(itm, enabled) def __unhandledException(self, msg): """ Private method handling not specifically handled exceptions. @param msg message describing the exception (string) """ if not str(msg): msg = str(sys.exc_info()[0]) QMessageBox.critical(None, self.trUtf8("Refactoring"), self.trUtf8("""Caught exception <b>%1</b>""") .arg(str(msg)), self.trUtf8("&OK"), None, None, 0, -1) def showOutput(self): """ Private method to switch to the relevant output tab. """ if self.logging: qApp.mainWidget().showLogTab("stdout") else: qApp.mainWidget().showLogTab("stderr") ################################################################## ## slots below are public utility methods ################################################################## def handlePreferencesChanged(self): """ Public slot called when the preferences have been changed. """ self.logging = Preferences.getRefactoring("Logging") if self.logging: self.brmctx.setProgressLogger(self.ui.stdout) else: self.brmctx.setProgressLogger(SilentLogger()) def getActions(self): """ Public method to get a list of all actions. @return list of all actions (list of QAction) """ actionList = [] for act in self.queryList("QAction"): if not isinstance(act, QActionGroup): actionList.append(act) return actionList def handleProjectOpened(self): """ Public slot to handle the projectOpened signal. """ self.projectopen = 1 self.projectpath = self.ui.getProject().ppath def handleProjectClosed(self): """ Public slot to handle the projectClosed signal. """ self.projectopen = 0 self.projectpath = '' |
From: Fabio Z. <fa...@us...> - 2004-09-16 15:28:47
|
Update of /cvsroot/pydev/org.python.pydev/PySrc/aRefactoring In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv24770/PySrc/aRefactoring Log Message: Directory /cvsroot/pydev/org.python.pydev/PySrc/aRefactoring added to the repository |
From: Fabio Z. <fa...@us...> - 2004-09-16 15:28:17
|
Update of /cvsroot/pydev/org.python.pydev/PySrc In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv24666/PySrc Added Files: .cvsignore Log Message: changed package name. --- NEW FILE: .cvsignore --- temporary_file.py |
From: Fabio Z. <fa...@us...> - 2004-09-16 15:27:45
|
Update of /cvsroot/pydev/org.python.pydev/PySrc In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv24305/PySrc Modified Files: test_pyserver.py test_refactoring.py pycompletionserver.py refactoring.py Log Message: Making refactoring. Index: pycompletionserver.py =================================================================== RCS file: /cvsroot/pydev/org.python.pydev/PySrc/pycompletionserver.py,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** pycompletionserver.py 15 Sep 2004 17:36:08 -0000 1.7 --- pycompletionserver.py 16 Sep 2004 15:27:25 -0000 1.8 *************** *** 10,25 **** HOST = '127.0.0.1' # Symbolic name meaning the local host ! MSG_KILL_SERVER = '@@KILL_SERVER_END@@' ! MSG_COMPLETIONS = '@@COMPLETIONS' ! MSG_END = 'END@@' ! MSG_GLOBALS = '@@GLOBALS:' ! MSG_TOKEN_GLOBALS = '@@TOKEN_GLOBALS(' ! MSG_CLASS_GLOBALS = '@@CLASS_GLOBALS(' ! MSG_INVALID_REQUEST = '@@INVALID_REQUEST' ! MSG_RELOAD_MODULES = '@@RELOAD_MODULES_END@@' ! MSG_CHANGE_DIR = '@@CHANGE_DIR:' ! MSG_OK = '@@MSG_OK_END@@' ! MSG_REFACTOR = '@@REFACTOR' ! MSG_PROCESSING = '@@PROCESSING_END@@' BUFFER_SIZE = 1024 --- 10,26 ---- HOST = '127.0.0.1' # Symbolic name meaning the local host ! MSG_KILL_SERVER = '@@KILL_SERVER_END@@' ! MSG_COMPLETIONS = '@@COMPLETIONS' ! MSG_END = 'END@@' ! MSG_GLOBALS = '@@GLOBALS:' ! MSG_TOKEN_GLOBALS = '@@TOKEN_GLOBALS(' ! MSG_CLASS_GLOBALS = '@@CLASS_GLOBALS(' ! MSG_INVALID_REQUEST = '@@INVALID_REQUEST' ! MSG_RELOAD_MODULES = '@@RELOAD_MODULES_END@@' ! MSG_CHANGE_DIR = '@@CHANGE_DIR:' ! MSG_OK = '@@MSG_OK_END@@' ! MSG_REFACTOR = '@@REFACTOR' ! MSG_PROCESSING = '@@PROCESSING_END@@' ! MSG_PROCESSING_PROGRESS = '@@PROCESSING:%sEND@@' BUFFER_SIZE = 1024 *************** *** 29,32 **** --- 30,34 ---- threading.Thread.__init__(self) self.socket = socket + self.processMsgFunc = None self.lastMsg = None *************** *** 34,41 **** time.sleep(0.1) while self.lastMsg == None: ! print 'sending', MSG_PROCESSING ! self.socket.send(MSG_PROCESSING) time.sleep(0.1) ! print 'sending', self.lastMsg self.socket.send(self.lastMsg) --- 36,48 ---- time.sleep(0.1) while self.lastMsg == None: ! ! if self.processMsgFunc != None: ! s = MSG_PROCESSING_PROGRESS % self.processMsgFunc() ! self.socket.send(s) ! else: ! self.socket.send(MSG_PROCESSING) time.sleep(0.1) ! ! #print 'sending', self.lastMsg self.socket.send(self.lastMsg) *************** *** 134,138 **** else: ! data = data[:data.find(MSG_END)] if data.startswith(MSG_GLOBALS): --- 141,145 ---- else: ! data = data[:data.rfind(MSG_END)] if data.startswith(MSG_GLOBALS): *************** *** 160,164 **** elif data.startswith(MSG_REFACTOR): data = data.replace(MSG_REFACTOR, '') ! returnMsg = refactoring.HandleRefactorMessage(data) else: --- 167,171 ---- elif data.startswith(MSG_REFACTOR): data = data.replace(MSG_REFACTOR, '') ! returnMsg = refactoring.HandleRefactorMessage(data, keepAliveThread) else: Index: test_refactoring.py =================================================================== RCS file: /cvsroot/pydev/org.python.pydev/PySrc/test_refactoring.py,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** test_refactoring.py 15 Sep 2004 17:36:08 -0000 1.1 --- test_refactoring.py 16 Sep 2004 15:27:25 -0000 1.2 *************** *** 29,37 **** FILE = 'temporary_file.py' - - class Test(unittest.TestCase): ! def getInitialFile(self): ! s = \ ''' class C: --- 29,35 ---- FILE = 'temporary_file.py' ! def getInitialFile(): ! s = \ ''' class C: *************** *** 41,46 **** c = a+b #this should be refactored. return c ''' ! return s def getRefactoredFile(self): --- 39,62 ---- c = a+b #this should be refactored. return c + c = C() ''' ! return s ! ! ! def getRenameRefactored(): ! s = \ ! ''' ! class G: ! def a(self): ! a = 2 ! b = 3 ! c = a+b #this should be refactored. ! return c ! c = G() ! ''' ! return s ! ! class Test(unittest.TestCase): ! def getRefactoredFile(self): *************** *** 51,60 **** a = 2 b = 3 ! c = self.plusMet(a, b) return c def plusMet(self, a, b): ! c = a+b #this should be refactored. ! return c ''' return s --- 67,76 ---- a = 2 b = 3 ! c = self.plusMet(a, b) #this should be refactored. return c def plusMet(self, a, b): ! return a+b ! c = C() ''' return s *************** *** 62,66 **** def setUp(self): unittest.TestCase.setUp(self) ! createFile(FILE, self.getInitialFile()) def tearDown(self): --- 78,82 ---- def setUp(self): unittest.TestCase.setUp(self) ! createFile(FILE, getInitialFile()) def tearDown(self): *************** *** 68,74 **** delete(FILE) ! def testIt(self): r = refactoring.Refactoring() ! s = r.extractMethod(FILE, 5+1, 0, 5+1, 44, 'plusMet') f = file(FILE, 'r') --- 84,90 ---- delete(FILE) ! def testExtractMethod(self): r = refactoring.Refactoring() ! s = r.extractMethod(FILE, 5+1, 12, 5+1, 12+3, 'plusMet') f = file(FILE, 'r') *************** *** 76,81 **** f.close() ! self.assertEquals(contents, self.getRefactoredFile()) ! if __name__ == '__main__': --- 92,107 ---- f.close() ! self.assertEquals(self.getRefactoredFile(), contents) ! ! def testRename(self): ! r = refactoring.Refactoring() ! s = r.renameByCoordinates(FILE, 1+1, 6, 'G') ! ! f = file(FILE, 'r') ! contents = f.read() ! f.close() ! ! self.assertEquals(getRenameRefactored(), contents) ! if __name__ == '__main__': Index: test_pyserver.py =================================================================== RCS file: /cvsroot/pydev/org.python.pydev/PySrc/test_pyserver.py,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** test_pyserver.py 15 Sep 2004 17:36:08 -0000 1.5 --- test_pyserver.py 16 Sep 2004 15:27:25 -0000 1.6 *************** *** 34,50 **** self.assertEquals('@@COMPLETIONS((Def,description),(Def1,description1),(Def2,description2))END@@', msg) ! def createConnections(self): ''' Creates the connections needed for testing. ''' ! t = pycompletionserver.T(50002,50003) t.start() sToWrite = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ! sToWrite.connect((pycompletionserver.HOST, 50002)) sToRead = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ! sToRead.bind((pycompletionserver.HOST, 50003)) sToRead.listen(1) #socket to receive messages. --- 34,50 ---- self.assertEquals('@@COMPLETIONS((Def,description),(Def1,description1),(Def2,description2))END@@', msg) ! def createConnections(self, p1 = 50002,p2 = 50003): ''' Creates the connections needed for testing. ''' ! t = pycompletionserver.T(p1,p2) t.start() sToWrite = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ! sToWrite.connect((pycompletionserver.HOST, p1)) sToRead = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ! sToRead.bind((pycompletionserver.HOST, p2)) sToRead.listen(1) #socket to receive messages. *************** *** 53,68 **** return t, sToWrite, sToRead, connToRead, addr - # def testRefactoring(self): - # t, sToWrite, sToRead, connToRead, addr = self.createConnections() - # self. def readMsg(self): msg = '@@PROCESSING_END@@' ! while msg == '@@PROCESSING_END@@': msg = self.connToRead.recv(1024*4) return msg ! def testSocketsAndMessages(self): t, sToWrite, sToRead, self.connToRead, addr = self.createConnections() --- 53,67 ---- return t, sToWrite, sToRead, connToRead, addr def readMsg(self): msg = '@@PROCESSING_END@@' ! while msg.startswith('@@PROCESSING'): msg = self.connToRead.recv(1024*4) + if msg.startswith('@@PROCESSING:'): + print 'Status msg:', msg return msg ! def testCompletionSocketsAndMessages(self): t, sToWrite, sToRead, self.connToRead, addr = self.createConnections() *************** *** 143,146 **** --- 142,146 ---- sToRead.close() sToWrite.close() + self.connToRead.close() def sendKillMsg(self, socket): *************** *** 148,151 **** --- 148,174 ---- + def testRefactoringSocketsAndMessages(self): + t, sToWrite, sToRead, self.connToRead, addr = self.createConnections(50002+2,50003+2) + + import refactoring + from test_refactoring import delete, createFile, FILE, getInitialFile, getRenameRefactored + createFile(FILE, getInitialFile()) + + sToWrite.send('@@REFACTORrenameByCoordinates %s %s %s %sEND@@'%(FILE, 1+1, 6, 'G')) + result = self.readMsg() + print 'result', result + + self.sendKillMsg(sToWrite) + + + while not hasattr(t, 'ended'): + pass #wait until it receives the message and quits. + + + sToRead.close() + sToWrite.close() + self.connToRead.close() + + if __name__ == '__main__': unittest.main() Index: refactoring.py =================================================================== RCS file: /cvsroot/pydev/org.python.pydev/PySrc/refactoring.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** refactoring.py 15 Sep 2004 17:36:08 -0000 1.2 --- refactoring.py 16 Sep 2004 15:27:25 -0000 1.3 *************** *** 16,21 **** --- 16,47 ---- def __init__(self): + self.progress = StringIO.StringIO() + self.warning = StringIO.StringIO() self.init() + + def getLastProgressMsg(self): + progress = self.progress.getvalue().split('\n') + msg = '' + i = -1 + while msg == '' and i > -5: + try: + msg = progress[i] + except: + msg = '' + i -= 1 + return msg + def getLastProgressMsgs(self, v): + progress = self.progress.getvalue().split('\n') + msg = '' + i = -1 + while i > -v: + try: + msg += progress[i]+'\n' + except: + pass + i -= 1 + return msg + def init(self): """ *************** *** 23,28 **** """ self.brmctx = bike.init() ! self.brmctx.setProgressLogger(sys.stdout) ! self.brmctx.setWarningLogger(sys.stderr) def handleReset(self): --- 49,54 ---- """ self.brmctx = bike.init() ! self.brmctx.setProgressLogger(self.progress) ! self.brmctx.setWarningLogger(self.warning) def handleReset(self): *************** *** 61,65 **** return __Refactoring ! def HandleRefactorMessage(msg): ''' The message received should have: the method of the class --- 87,102 ---- return __Refactoring ! def releaseRefactorerBuffers(): ! GetRefactorer().warning.close() ! GetRefactorer().progress.close() ! ! GetRefactorer().warning.__init__() ! GetRefactorer().progress.__init__() ! ! def restartRefactorer(): ! global __Refactoring ! __Refactoring = Refactoring() ! ! def HandleRefactorMessage(msg, keepAliveThread): ''' The message received should have: the method of the class *************** *** 69,83 **** func = msgSplit.pop(0) ! func = getattr(GetRefactorer(), func) try: ! return func(*msgSplit)+'END@@' except: import sys s = StringIO.StringIO() exc_info = sys.exc_info() print >> s, str(exc_info[1]) traceback.print_exception(exc_info[0], exc_info[1], exc_info[2], limit=None, file = s) ! return 'ERROR: %s\nEND@@'%(s.getvalue()) --- 106,137 ---- func = msgSplit.pop(0) ! refactorer = GetRefactorer() ! func = getattr(refactorer, func) ! ! keepAliveThread.processMsgFunc = refactorer.getLastProgressMsg try: ! f = func(*msgSplit)+'END@@' ! releaseRefactorerBuffers() ! return f except: import sys s = StringIO.StringIO() exc_info = sys.exc_info() + print >> s, str(exc_info[1]) + + print >> s, '\nWARNINGS:\n' + print >> s, refactorer.warning.getvalue() + + print >> s, '\nPROGRESS:\n' + print >> s, refactorer.getLastProgressMsgs(8) + + print >> s, '\nDETAILS:\n' traceback.print_exception(exc_info[0], exc_info[1], exc_info[2], limit=None, file = s) ! ! releaseRefactorerBuffers() ! restartRefactorer() ! return 'ERROR:%s\nEND@@'%(s.getvalue().replace('END@@','')) |
From: Fabio Z. <fa...@us...> - 2004-09-16 15:26:40
|
Update of /cvsroot/pydev/org.python.pydev/PySrc/Refactoring In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv24018/PySrc/Refactoring Removed Files: __init__.py Refactoring.py MatchesForm.py MatchesForm.ui MatchesDialog.py Log Message: changed package name. --- MatchesForm.py DELETED --- --- MatchesDialog.py DELETED --- --- MatchesForm.ui DELETED --- --- __init__.py DELETED --- --- Refactoring.py DELETED --- |
From: Fabio Z. <fa...@us...> - 2004-09-15 17:52:27
|
Update of /cvsroot/pydev/org.python.pydev.test In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv29887 Modified Files: .project Log Message: Index: .project =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.test/.project,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** .project 11 May 2004 06:21:17 -0000 1.1 --- .project 15 Sep 2004 17:52:18 -0000 1.2 *************** *** 8,11 **** --- 8,12 ---- </buildSpec> <natures> + <nature>org.python.pydev.pythonNature</nature> </natures> </projectDescription> |
From: Fabio Z. <fa...@us...> - 2004-09-15 17:51:35
|
Update of /cvsroot/pydev/org.python.pydev.help In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv29763 Modified Files: plugin.xml Log Message: Updated to version 3.0 Index: plugin.xml =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.help/plugin.xml,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** plugin.xml 25 Jul 2004 13:52:42 -0000 1.4 --- plugin.xml 15 Sep 2004 17:51:25 -0000 1.5 *************** *** 1,3 **** --- 1,4 ---- <?xml version="1.0" encoding="UTF-8"?> + <?eclipse version="3.0"?> <plugin id="org.python.pydev.help" |
From: Fabio Z. <fa...@us...> - 2004-09-15 17:49:16
|
Update of /cvsroot/pydev/org.pydev.jython In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv29338 Modified Files: .project plugin.xml Log Message: Updated to version 3.0 Index: .project =================================================================== RCS file: /cvsroot/pydev/org.pydev.jython/.project,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** .project 25 May 2004 18:01:56 -0000 1.1 --- .project 15 Sep 2004 17:49:07 -0000 1.2 *************** *** 4,9 **** <comment></comment> <projects> - <project>org.eclipse.core.boot</project> - <project>org.eclipse.core.runtime</project> </projects> <buildSpec> --- 4,7 ---- Index: plugin.xml =================================================================== RCS file: /cvsroot/pydev/org.pydev.jython/plugin.xml,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** plugin.xml 14 Jun 2004 01:03:42 -0000 1.2 --- plugin.xml 15 Sep 2004 17:49:07 -0000 1.3 *************** *** 1,3 **** --- 1,4 ---- <?xml version="1.0" encoding="UTF-8"?> + <?eclipse version="3.0"?> <plugin id="org.pydev.jython" |
From: Fabio Z. <fa...@us...> - 2004-09-15 17:36:18
|
Update of /cvsroot/pydev/org.python.pydev/src/org/python/pydev/editor/actions In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv25438/src/org/python/pydev/editor/actions Modified Files: PySelection.java Log Message: Making refactoring. Index: PySelection.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev/src/org/python/pydev/editor/actions/PySelection.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** PySelection.java 16 Aug 2004 13:31:00 -0000 1.3 --- PySelection.java 15 Sep 2004 17:36:09 -0000 1.4 *************** *** 44,47 **** --- 44,48 ---- /** Cursor offset. */ public int absoluteCursorOffset; + public ITextSelection textSelection; /** *************** *** 77,80 **** --- 78,82 ---- // Grab the selection ITextSelection selection = getITextSelection(); + this.textSelection = selection; this.absoluteCursorOffset = selection.getOffset(); |
From: Fabio Z. <fa...@us...> - 2004-09-15 17:36:18
|
Update of /cvsroot/pydev/org.python.pydev In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv25438 Modified Files: plugin.xml Log Message: Making refactoring. Index: plugin.xml =================================================================== RCS file: /cvsroot/pydev/org.python.pydev/plugin.xml,v retrieving revision 1.35 retrieving revision 1.36 diff -C2 -d -r1.35 -r1.36 *** plugin.xml 14 Sep 2004 17:42:08 -0000 1.35 --- plugin.xml 15 Sep 2004 17:36:09 -0000 1.36 *************** *** 4,8 **** id="org.python.pydev" name="Pydev - Python Development Environment" ! version="0.5.9.4" provider-name="AleksTotic" class="org.python.pydev.plugin.PydevPlugin"> --- 4,8 ---- id="org.python.pydev" name="Pydev - Python Development Environment" ! version="0.5.9.5a" provider-name="AleksTotic" class="org.python.pydev.plugin.PydevPlugin"> *************** *** 256,259 **** --- 256,276 ---- </separator> </menu> + <menu + label="Refactoring" + id="org.python.pydev.refactoring"> + <separator name="refactorings"/> + </menu> + <action + label="Extract Method" + class="org.python.pydev.editor.actions.refactoring.PyExtractMethod" + menubarPath="org.python.pydev.refactoring/refactorings" + id="org.python.pydev.refactoring.extractmethod"> + </action> + <action + label="Rename" + class="org.python.pydev.editor.actions.refactoring.PyRename" + menubarPath="org.python.pydev.refactoring/refactorings" + id="org.python.pydev.refactoring.rename"> + </action> <action label="Convert space-tabs to tabs" *************** *** 555,558 **** --- 572,593 ---- configuration="org.eclipse.ui.defaultAcceleratorConfiguration"> </keyBinding> + + <!-- category: Refactor + <category + name="Refactor category" + description="Python refactor category" + id="org.python.pydev.ui.category.refactor"/> + command: Extract Method + <command + category="org.python.pydev.ui.category.refactor" + name="Python Extract Method" + id="org.python.pydev.refactor.extractmethod"/> + <keyBinding + string="Shift+Alt+M" + scope="org.python.pydev.ui.editor.scope" + command="org.python.pydev.refactor.extractmethod" + configuration="org.eclipse.ui.defaultAcceleratorConfiguration"> + </keyBinding> + --> </extension> <!-- file type extensions for the team (CVS) --> |
From: Fabio Z. <fa...@us...> - 2004-09-15 17:36:18
|
Update of /cvsroot/pydev/org.python.pydev/src/org/python/pydev/editor/codecompletion In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv25438/src/org/python/pydev/editor/codecompletion Modified Files: PythonShell.java PythonCompletionProcessor.java Log Message: Making refactoring. Index: PythonShell.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev/src/org/python/pydev/editor/codecompletion/PythonShell.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** PythonShell.java 14 Sep 2004 17:42:14 -0000 1.4 --- PythonShell.java 15 Sep 2004 17:36:09 -0000 1.5 *************** *** 40,48 **** } return pytonShell; - } ! public static final int BUFFER_SIZE = 1024 * 4; /** * Python server process. --- 40,47 ---- } return pytonShell; } ! public static final int BUFFER_SIZE = 1024 ; /** * Python server process. *************** *** 134,142 **** process = Runtime.getRuntime().exec("python "+serverFile.getAbsolutePath()+" "+pWrite+" "+pRead); ! sleepALittle(); ! ! socketToWrite = new Socket("127.0.0.1",pWrite); //we should write in this port ! serverSocket = new ServerSocket(pRead); //and read in this port ! socketToRead = serverSocket.accept(); } catch (IOException e) { --- 133,150 ---- process = Runtime.getRuntime().exec("python "+serverFile.getAbsolutePath()+" "+pWrite+" "+pRead); ! boolean connected = false; ! int attempts = 0; ! while(!connected && attempts < 20){ ! attempts += 1; ! sleepALittle(); ! try { ! socketToWrite = new Socket("127.0.0.1",pWrite); //we should write in this port ! serverSocket = new ServerSocket(pRead); //and read in this port ! socketToRead = serverSocket.accept(); ! connected = true; ! } catch (IOException e1) { ! e1.printStackTrace(); ! } ! } } catch (IOException e) { *************** *** 144,147 **** --- 152,156 ---- process.destroy(); } + process = null; e.printStackTrace(); throw e; *************** *** 158,177 **** int j = 0; ! while(str.indexOf("END@@") == -1 && j != 100){ byte[] b = new byte[PythonShell.BUFFER_SIZE]; this.socketToRead.getInputStream().read(b); ! // System.out.println("READ:"+new String(b)); String s = new String(b); ! str += s; ! j++; } //remove @@COMPLETIONS str = str.replaceFirst("@@COMPLETIONS",""); //remove END@@ ! return str.substring(0, str.lastIndexOf("END@@")); } --- 167,210 ---- int j = 0; ! while(j != 100){ byte[] b = new byte[PythonShell.BUFFER_SIZE]; + // System.out.println("WILL READ"); this.socketToRead.getInputStream().read(b); ! // System.out.println("READ"); String s = new String(b); ! if(s.indexOf("@@PROCESSING_END@@") != -1){ //each time we get a processing message, reset j to 0. ! s = s.replaceAll("@@PROCESSING_END@@", ""); ! j = 0; ! // System.out.println("Processing msg received."); ! } ! s = s.replaceAll((char)0+"",""); //python sends this char as payload. ! System.out.println("RECEIVED:"+s); str += s; ! ! if(str.indexOf("END@@") != -1){ ! // System.out.println("WILL BREAK"); ! break; ! }else{ ! // System.out.println("WILL SLEEP"); ! j++; ! sleepALittle(10); ! } ! } + // System.out.println("OUT"); //remove @@COMPLETIONS str = str.replaceFirst("@@COMPLETIONS",""); //remove END@@ ! ! try { ! return str.substring(0, str.lastIndexOf("END@@")); ! } catch (RuntimeException e) { ! System.out.println("ERROR WIT STRING:"+str); ! e.printStackTrace(); ! return ""; ! } } *************** *** 182,186 **** */ public void write(String str) throws IOException { - // System.out.println("WRITING:"+str); this.socketToWrite.getOutputStream().write(str.getBytes()); } --- 215,218 ---- *************** *** 213,225 **** * @throws IOException */ ! void endIt() { try { closeConn(); ! } catch (IOException e) { e.printStackTrace(); } if (process!= null){ try { int i = process.getErrorStream().available(); byte b[] = new byte[i]; --- 245,259 ---- * @throws IOException */ ! public void endIt() { try { closeConn(); ! } catch (Exception e) { e.printStackTrace(); } if (process!= null){ try { + + process.getOutputStream().close(); int i = process.getErrorStream().available(); byte b[] = new byte[i]; *************** *** 229,233 **** i = process.getInputStream().available(); b = new byte[i]; ! process.getErrorStream().read(b); System.out.println(new String(b)); } catch (Exception e1) { --- 263,267 ---- i = process.getInputStream().available(); b = new byte[i]; ! process.getInputStream().read(b); System.out.println(new String(b)); } catch (Exception e1) { *************** *** 256,260 **** file = file.getParentFile(); } - System.out.println("changing dir:"+file.getAbsolutePath()); this.write("@@CHANGE_DIR:"+file.getAbsolutePath()+"END@@"); String ok = this.read(); //this should be the ok message... --- 290,293 ---- *************** *** 310,319 **** e.printStackTrace(); ! this.endIt(); ! try { ! this.startIt(); ! } catch (IOException e2) { ! e2.printStackTrace(); ! } return getInvalidCompletion(); } --- 343,347 ---- e.printStackTrace(); ! restartShell(); return getInvalidCompletion(); } *************** *** 321,324 **** --- 349,369 ---- /** + * + */ + public void restartShell() { + try { + this.endIt(); + } catch (Exception e2) { + e2.printStackTrace(); + } + try { + this.startIt(); + } catch (IOException e2) { + e2.printStackTrace(); + } + } + + + /** * @return */ Index: PythonCompletionProcessor.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev/src/org/python/pydev/editor/codecompletion/PythonCompletionProcessor.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** PythonCompletionProcessor.java 14 Sep 2004 17:42:14 -0000 1.5 --- PythonCompletionProcessor.java 15 Sep 2004 17:36:09 -0000 1.6 *************** *** 85,89 **** } }else{ //everything is a part of the qualifier. ! qualifier = activationToken; activationToken = ""; } --- 85,89 ---- } }else{ //everything is a part of the qualifier. ! qualifier = activationToken.trim(); activationToken = ""; } *************** *** 153,157 **** private List getTemplateProposals(ITextViewer viewer, int documentOffset, String activationToken, java.lang.String qualifier, List allProposals) { List propList = new ArrayList(); ! if(activationToken.trim().equals("") == false){ //templates proposals are added here. this.templatesCompletion.addTemplateProposals(viewer, documentOffset, --- 153,157 ---- private List getTemplateProposals(ITextViewer viewer, int documentOffset, String activationToken, java.lang.String qualifier, List allProposals) { List propList = new ArrayList(); ! if(activationToken.trim().equals("") == false || qualifier.trim().equals("") == false){ //templates proposals are added here. this.templatesCompletion.addTemplateProposals(viewer, documentOffset, |
From: Fabio Z. <fa...@us...> - 2004-09-15 17:36:17
|
Update of /cvsroot/pydev/org.python.pydev/src/org/python/pydev/editor/refactoring In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv25438/src/org/python/pydev/editor/refactoring Modified Files: PyRefactoring.java Log Message: Making refactoring. Index: PyRefactoring.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev/src/org/python/pydev/editor/refactoring/PyRefactoring.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** PyRefactoring.java 14 Sep 2004 17:42:15 -0000 1.1 --- PyRefactoring.java 15 Sep 2004 17:36:08 -0000 1.2 *************** *** 6,9 **** --- 6,15 ---- package org.python.pydev.editor.refactoring; + import java.io.File; + import java.io.IOException; + + import org.eclipse.core.runtime.CoreException; + import org.python.pydev.editor.codecompletion.PythonShell; + /** * This class is used to make the refactorings. *************** *** 18,21 **** --- 24,133 ---- */ public class PyRefactoring { + + /** + * Reference to a 'global python shell' + */ + private static PythonShell pytonShell; + + /** + * Instead of making all static, let's use a singleton... it may be useful... + */ + private static PyRefactoring pyRefactoring; + + + private PyRefactoring(){ + + } + + public static PyRefactoring getPyRefactoring(){ + if (pyRefactoring == null){ + pyRefactoring = new PyRefactoring(); + } + return pyRefactoring; + } + + /** + * @return + * @throws CoreException + * @throws IOException + * + */ + private PythonShell getServerShell() throws IOException, CoreException { + if(pytonShell == null){ + pytonShell = new PythonShell(); + pytonShell.startIt(); + } + return pytonShell; + } + + /** + * This method can be used to write something to the server and get its answer. + * + * @param str + * @return + */ + private String makeAction(String str){ + PythonShell pytonShell; + try { + pytonShell = getServerShell(); + try { + pytonShell.write(str); + + return pytonShell.read(); + } catch (Exception e) { + e.printStackTrace(); + + pytonShell.restartShell(); + } + } catch (Exception e1) { + e1.printStackTrace(); + } + return null; + } + + + /** + * @param editorFile + * @param beginLine + * @param beginCol + * @param endLine + * @param endCol + * @param name + */ + public void extract(File editorFile, int beginLine, int beginCol, int endLine, int endCol, String name) { + String s = "@@REFACTOR"; + s+= "extractMethod"; + s+= " "+editorFile.getAbsolutePath(); + s+= " "+beginLine; + s+= " "+beginCol; + s+= " "+endLine; + s+= " "+endCol; + s+= " "+name; + s+= "END@@"; + System.out.println("Extract: "+s); + String string = makeAction(s); + System.out.println("REFACTOR RESULT:"+string); + + } + + /** + * @param editorFile + * @param beginLine + * @param beginCol + * @param name + */ + public void rename(File editorFile, int beginLine, int beginCol, String name) { + String s = "@@REFACTOR"; + s+= "renameByCoordinates"; + s+= " "+editorFile.getAbsolutePath(); + s+= " "+beginLine; + s+= " "+beginCol; + s+= " "+name; + s+= "END@@"; + System.out.println("Extract: "+s); + String string = makeAction(s); + System.out.println("REFACTOR RESULT:"+string); + + } } |
From: Fabio Z. <fa...@us...> - 2004-09-15 17:36:17
|
Update of /cvsroot/pydev/org.python.pydev/PySrc In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv25438/PySrc Modified Files: test_pyserver.py pycompletionserver.py refactoring.py Added Files: test_refactoring.py Log Message: Making refactoring. Index: pycompletionserver.py =================================================================== RCS file: /cvsroot/pydev/org.python.pydev/PySrc/pycompletionserver.py,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** pycompletionserver.py 14 Sep 2004 17:42:07 -0000 1.6 --- pycompletionserver.py 15 Sep 2004 17:36:08 -0000 1.7 *************** *** 5,8 **** --- 5,10 ---- import time import simpleTipper + import refactoring + import sys HOST = '127.0.0.1' # Symbolic name meaning the local host *************** *** 18,24 **** MSG_CHANGE_DIR = '@@CHANGE_DIR:' MSG_OK = '@@MSG_OK_END@@' ! BUFFER_SIZE = 1024 * 4 class T(threading.Thread): --- 20,43 ---- MSG_CHANGE_DIR = '@@CHANGE_DIR:' MSG_OK = '@@MSG_OK_END@@' + MSG_REFACTOR = '@@REFACTOR' + MSG_PROCESSING = '@@PROCESSING_END@@' ! BUFFER_SIZE = 1024 + class KeepAliveThread(threading.Thread): + def __init__(self, socket): + threading.Thread.__init__(self) + self.socket = socket + self.lastMsg = None + + def run(self): + time.sleep(0.1) + while self.lastMsg == None: + print 'sending', MSG_PROCESSING + self.socket.send(MSG_PROCESSING) + time.sleep(0.1) + print 'sending', self.lastMsg + self.socket.send(self.lastMsg) + class T(threading.Thread): *************** *** 55,70 **** return '%s(%s)%s'%(MSG_COMPLETIONS, compMsg, MSG_END) ! def sendCompletionsMessage(self, completionsList): ''' ! Send message with completions. ''' ! self.socket.send(self.formatCompletionMessage(completionsList)) ! ! def sendReceivedInvalidMessage(self): ! self.socket.send(MSG_INVALID_REQUEST) - def sendOkMsg(self): - self.socket.send(MSG_OK) - def getTokenAndData(self, data): ''' --- 74,83 ---- return '%s(%s)%s'%(MSG_COMPLETIONS, compMsg, MSG_END) ! def getCompletionsMessage(self, completionsList): ''' ! get message with completions. ''' ! return self.formatCompletionMessage(completionsList) def getTokenAndData(self, data): ''' *************** *** 103,145 **** while 1: data = '' ! while not data.endswith(MSG_END): ! data+=conn.recv(BUFFER_SIZE) ! if MSG_KILL_SERVER in data: ! #break if we received kill message. ! break; ! ! elif MSG_RELOAD_MODULES in data: ! simpleTipper.ReloadModules() ! self.sendOkMsg() ! ! else: ! data = data[:data.find(MSG_END)] ! if MSG_GLOBALS in data: ! data = data.replace(MSG_GLOBALS, '') ! comps = simpleTipper.GenerateTip(data, None, False) ! self.sendCompletionsMessage(comps) ! ! elif MSG_TOKEN_GLOBALS in data: ! data = data.replace(MSG_TOKEN_GLOBALS, '') ! token, data = self.getTokenAndData(data) ! comps = simpleTipper.GenerateTip(data, token, False) ! self.sendCompletionsMessage(comps) ! elif MSG_CLASS_GLOBALS in data: ! data = data.replace(MSG_CLASS_GLOBALS, '') ! token, data = self.getTokenAndData(data) ! comps = simpleTipper.GenerateTip(data, token, True) ! self.sendCompletionsMessage(comps) - elif MSG_CHANGE_DIR in data: - data = data.replace(MSG_CHANGE_DIR, '') - simpleTipper.CompleteFromDir(data) - self.sendOkMsg() - else: ! self.sendReceivedInvalidMessage() ! conn.close() --- 116,169 ---- while 1: data = '' ! returnMsg = '' ! keepAliveThread = KeepAliveThread(self.socket) ! while not data.endswith(MSG_END): ! data += conn.recv(BUFFER_SIZE) ! try: ! if MSG_KILL_SERVER in data: ! #break if we received kill message. ! break; ! keepAliveThread.start() ! ! if MSG_RELOAD_MODULES in data: ! simpleTipper.ReloadModules() ! returnMsg = MSG_OK else: ! data = data[:data.find(MSG_END)] ! ! if data.startswith(MSG_GLOBALS): ! data = data.replace(MSG_GLOBALS, '') ! comps = simpleTipper.GenerateTip(data, None, False) ! returnMsg = self.getCompletionsMessage(comps) ! ! elif data.startswith(MSG_TOKEN_GLOBALS ): ! data = data.replace(MSG_TOKEN_GLOBALS, '') ! token, data = self.getTokenAndData(data) ! comps = simpleTipper.GenerateTip(data, token, False) ! returnMsg = self.getCompletionsMessage(comps) ! ! elif data.startswith(MSG_CLASS_GLOBALS ): ! data = data.replace(MSG_CLASS_GLOBALS, '') ! token, data = self.getTokenAndData(data) ! comps = simpleTipper.GenerateTip(data, token, True) ! returnMsg = self.getCompletionsMessage(comps) ! ! elif data.startswith(MSG_CHANGE_DIR ): ! data = data.replace(MSG_CHANGE_DIR, '') ! simpleTipper.CompleteFromDir(data) ! returnMsg = MSG_OK ! ! elif data.startswith(MSG_REFACTOR): ! data = data.replace(MSG_REFACTOR, '') ! returnMsg = refactoring.HandleRefactorMessage(data) ! ! else: ! returnMsg = MSG_INVALID_REQUEST ! finally: ! keepAliveThread.lastMsg = returnMsg conn.close() *************** *** 147,156 **** if __name__ == '__main__': - import sys thisPort = int(sys.argv[1]) #this is from where we want to receive messages. serverPort = int(sys.argv[2])#this is where we want to write messages. t = T(thisPort, serverPort) t.start() --- 171,184 ---- if __name__ == '__main__': + #let's log this!! + out = open('c:/temp/pydev.log', 'w') + sys.stdout = out + sys.stderr = out thisPort = int(sys.argv[1]) #this is from where we want to receive messages. serverPort = int(sys.argv[2])#this is where we want to write messages. t = T(thisPort, serverPort) + print 'will start' t.start() --- NEW FILE: test_refactoring.py --- ''' Refactoring tests. ''' from coilib import unittest import refactoring import os #=============================================================================== # delete #=============================================================================== def delete(filename): '''Removes filename, or does nothing if the file doesn't exist. ''' try: os.remove(filename) except OSError: pass #================================================================================ # createFile #================================================================================ def createFile(filename, contents='', flag='w'): '''Creates the given filename with the given contents. ''' f = file(filename, flag) f.write(contents) f.close() FILE = 'temporary_file.py' class Test(unittest.TestCase): def getInitialFile(self): s = \ ''' class C: def a(self): a = 2 b = 3 c = a+b #this should be refactored. return c ''' return s def getRefactoredFile(self): s = \ ''' class C: def a(self): a = 2 b = 3 c = self.plusMet(a, b) return c def plusMet(self, a, b): c = a+b #this should be refactored. return c ''' return s def setUp(self): unittest.TestCase.setUp(self) createFile(FILE, self.getInitialFile()) def tearDown(self): unittest.TestCase.tearDown(self) delete(FILE) def testIt(self): r = refactoring.Refactoring() s = r.extractMethod(FILE, 5+1, 0, 5+1, 44, 'plusMet') f = file(FILE, 'r') contents = f.read() f.close() self.assertEquals(contents, self.getRefactoredFile()) if __name__ == '__main__': unittest.main() Index: test_pyserver.py =================================================================== RCS file: /cvsroot/pydev/org.python.pydev/PySrc/test_pyserver.py,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** test_pyserver.py 14 Sep 2004 17:42:07 -0000 1.4 --- test_pyserver.py 15 Sep 2004 17:36:08 -0000 1.5 *************** *** 34,38 **** self.assertEquals('@@COMPLETIONS((Def,description),(Def1,description1),(Def2,description2))END@@', msg) ! def testSocketsAndMessages(self): t = pycompletionserver.T(50002,50003) --- 34,41 ---- self.assertEquals('@@COMPLETIONS((Def,description),(Def1,description1),(Def2,description2))END@@', msg) ! def createConnections(self): ! ''' ! Creates the connections needed for testing. ! ''' t = pycompletionserver.T(50002,50003) *************** *** 47,55 **** connToRead, addr = sToRead.accept() #now that we have the connections all set up, check the code completion messages. sToWrite.send('@@GLOBALS:import math\nEND@@') #only 1 global should be returned: math itself. ! completions = connToRead.recv(1024) self.assertEquals('@@COMPLETIONS((math,This module is always available. It provides access to the\n'\ 'mathematical functions defined by the C standard.))END@@', --- 50,75 ---- connToRead, addr = sToRead.accept() + + return t, sToWrite, sToRead, connToRead, addr + + # def testRefactoring(self): + # t, sToWrite, sToRead, connToRead, addr = self.createConnections() + # self. + + def readMsg(self): + msg = '@@PROCESSING_END@@' + while msg == '@@PROCESSING_END@@': + msg = self.connToRead.recv(1024*4) + + return msg + + def testSocketsAndMessages(self): + t, sToWrite, sToRead, self.connToRead, addr = self.createConnections() #now that we have the connections all set up, check the code completion messages. sToWrite.send('@@GLOBALS:import math\nEND@@') #only 1 global should be returned: math itself. ! completions = self.readMsg() ! self.assertEquals('@@COMPLETIONS((math,This module is always available. It provides access to the\n'\ 'mathematical functions defined by the C standard.))END@@', *************** *** 59,63 **** #check token msg. sToWrite.send('@@TOKEN_GLOBALS(math):import math\nEND@@') ! completions = connToRead.recv(4086) self.assert_('@@COMPLETIONS' in completions) --- 79,83 ---- #check token msg. sToWrite.send('@@TOKEN_GLOBALS(math):import math\nEND@@') ! completions = self.readMsg() self.assert_('@@COMPLETIONS' in completions) *************** *** 83,90 **** sToWrite.send('@@TOKEN_GLOBALS(C):%s\nEND@@'%s) ! completions = connToRead.recv(4086) sToWrite.send('@@CLASS_GLOBALS(C):%s\nEND@@'%s) ! completions2 = connToRead.recv(4086) self.assert_(len(completions) != len(completions2)) --- 103,110 ---- sToWrite.send('@@TOKEN_GLOBALS(C):%s\nEND@@'%s) ! completions = self.readMsg() sToWrite.send('@@CLASS_GLOBALS(C):%s\nEND@@'%s) ! completions2 = self.readMsg() self.assert_(len(completions) != len(completions2)) *************** *** 92,96 **** #reload modules test # sToWrite.send('@@RELOAD_MODULES_END@@') ! # ok = connToRead.recv(4086) # self.assertEquals('@@MSG_OK_END@@' , ok) # this test is not executed because it breaks our current enviroment. --- 112,116 ---- #reload modules test # sToWrite.send('@@RELOAD_MODULES_END@@') ! # ok = self.readMsg() # self.assertEquals('@@MSG_OK_END@@' , ok) # this test is not executed because it breaks our current enviroment. *************** *** 109,116 **** self.assert_(newDir != None) sToWrite.send('@@CHANGE_DIR:%sEND@@'%newDir) ! ok = connToRead.recv(4086) self.assertEquals('@@MSG_OK_END@@' , ok) sToWrite.send('@@TOKEN_GLOBALS(math acos):import math\nEND@@') ! completions = connToRead.recv(4086) self.sendKillMsg(sToWrite) --- 129,136 ---- self.assert_(newDir != None) sToWrite.send('@@CHANGE_DIR:%sEND@@'%newDir) ! ok = self.readMsg() self.assertEquals('@@MSG_OK_END@@' , ok) sToWrite.send('@@TOKEN_GLOBALS(math acos):import math\nEND@@') ! completions = self.readMsg() self.sendKillMsg(sToWrite) Index: refactoring.py =================================================================== RCS file: /cvsroot/pydev/org.python.pydev/PySrc/refactoring.py,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** refactoring.py 14 Sep 2004 17:42:07 -0000 1.1 --- refactoring.py 15 Sep 2004 17:36:08 -0000 1.2 *************** *** 3,7 **** import sys import os ! --- 3,8 ---- import sys import os ! import traceback ! import StringIO *************** *** 22,31 **** """ self.brmctx = bike.init() ! self.logging = Preferences.getRefactoring("Logging") ! if self.logging: ! self.brmctx.setProgressLogger(self.ui.stdout) ! else: ! self.brmctx.setProgressLogger(SilentLogger()) ! self.brmctx.setWarningLogger(self.ui.stderr) def handleReset(self): --- 23,28 ---- """ self.brmctx = bike.init() ! self.brmctx.setProgressLogger(sys.stdout) ! self.brmctx.setWarningLogger(sys.stderr) def handleReset(self): *************** *** 35,39 **** --- 32,83 ---- self.init() + + def extractMethod(self, filename, startline, startcolumn, + endline, endcolumn, newname): + ''' + Receives all as a string and changes to correct type. + ''' + self.brmctx.extractMethod(filename, int(startline), int(startcolumn), + int(endline), int(endcolumn), + newname) + savedfiles = self.brmctx.save() + return str(savedfiles) + + def renameByCoordinates(self, filename, line, column, newname): + ''' + Receives all as a string and changes to correct type. + ''' + self.brmctx.renameByCoordinates(filename, int(line), int(column), newname) + savedfiles = self.brmctx.save() + return str(savedfiles) + + __Refactoring = None + + def GetRefactorer(): + global __Refactoring + if __Refactoring is None: + __Refactoring = Refactoring() + return __Refactoring + + def HandleRefactorMessage(msg): + ''' + The message received should have: the method of the class + ''' + msgSplit = msg.split(' ') + func = msgSplit.pop(0) + + func = getattr(GetRefactorer(), func) + + try: + return func(*msgSplit)+'END@@' + except: + import sys + s = StringIO.StringIO() + exc_info = sys.exc_info() + print >> s, str(exc_info[1]) + traceback.print_exception(exc_info[0], exc_info[1], exc_info[2], limit=None, file = s) + return 'ERROR: %s\nEND@@'%(s.getvalue()) + |
From: Fabio Z. <fa...@us...> - 2004-09-15 17:36:17
|
Update of /cvsroot/pydev/org.python.pydev/src/org/python/pydev/editor/actions/refactoring In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv25438/src/org/python/pydev/editor/actions/refactoring Added Files: PyExtractMethod.java PyRefactorAction.java PyRename.java Log Message: Making refactoring. --- NEW FILE: PyRename.java --- /* * Created on Sep 15, 2004 * * @author Fabio Zadrozny */ package org.python.pydev.editor.actions.refactoring; import java.io.File; import org.eclipse.jface.action.IAction; import org.python.pydev.editor.refactoring.PyRefactoring; /** * @author Fabio Zadrozny */ public class PyRename extends PyRefactorAction { /** * we need: * * renameByCoordinates(filename, line, column, newname) */ protected void perform(IAction action) throws Exception { File editorFile = getPyEdit().getEditorFile(); //testing first with whole lines. int beginLine = getStartLine(); int beginCol = getStartCol(); String name = getInput(getPyEdit(),"Please inform the new name."); if(name.equals("") == false){ PyRefactoring.getPyRefactoring().rename(editorFile, beginLine, beginCol, name); refreshEditor(getPyEdit()); } } } --- NEW FILE: PyExtractMethod.java --- /* * Created on Sep 14, 2004 * * @author Fabio Zadrozny */ package org.python.pydev.editor.actions.refactoring; import java.io.File; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.action.IAction; import org.eclipse.jface.text.BadLocationException; import org.python.pydev.editor.refactoring.PyRefactoring; /** * @author Fabio Zadrozny */ public class PyExtractMethod extends PyRefactorAction { /** * we need: * * def extract(self, filename_path, * begin_line, begin_col, * end_line, end_col, * name): * @throws BadLocationException * @throws CoreException */ protected void perform(IAction action) throws BadLocationException, CoreException { File editorFile = getPyEdit().getEditorFile(); //testing first with whole lines. int beginLine = getStartLine(); int beginCol = getStartCol(); int endLine = getEndLine(); int endCol = getEndCol(); String name = getInput(getPyEdit(),"Please inform the new name."); if(name.equals("") == false){ PyRefactoring.getPyRefactoring().extract(editorFile, beginLine, beginCol, endLine, endCol, name); refreshEditor(getPyEdit()); } } } --- NEW FILE: PyRefactorAction.java --- /* * Created on Sep 15, 2004 * * @author Fabio Zadrozny */ package org.python.pydev.editor.actions.refactoring; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.action.IAction; import org.eclipse.jface.dialogs.InputDialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.part.FileEditorInput; import org.python.pydev.editor.PyEdit; import org.python.pydev.editor.actions.PyAction; import org.python.pydev.editor.actions.PySelection; /** * @author Fabio Zadrozny */ public abstract class PyRefactorAction extends PyAction { /** * @param edit * @param msg */ protected String getInput(PyEdit edit, String msg) { InputDialog d = new InputDialog(edit.getSite().getShell(),"Refactoring", msg,"",null); int retCode = d.open(); if(retCode == InputDialog.OK){ return d.getValue(); } return ""; } /** * @param edit * @throws CoreException */ protected void refreshEditor(PyEdit edit) throws CoreException { IFile file = (IFile) ((FileEditorInput)edit.getEditorInput()).getAdapter(IFile.class); file.refreshLocal(IResource.DEPTH_INFINITE, null); } /** * @param edit */ protected boolean areRefactorPreconditionsOK(PyEdit edit) { IWorkbenchWindow workbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); IEditorPart[] dirtyEditors = workbenchWindow.getActivePage().getDirtyEditors(); boolean saveEditors = false; if(dirtyEditors.length > 0){ saveEditors = MessageDialog.openQuestion(edit.getSite().getShell(), "Save All?", "All the editors must be saved to make this operation.\nIs it ok to save them?"); if(saveEditors==false){ return false; } } if(saveEditors){ boolean editorsSaved = workbenchWindow.getActivePage().saveAllEditors(false); if (!editorsSaved){ return false; } } return true; } protected PySelection ps; /** * @return */ protected int getEndCol() { return ps.absoluteCursorOffset + ps.selLength - ps.endLine.getOffset(); } /** * @return */ protected int getEndLine() { return ps.endLineIndex+1; } /** * @return */ protected int getStartCol() { return ps.absoluteCursorOffset - ps.startLine.getOffset(); } /** * @return */ protected int getStartLine() { return ps.startLineIndex+1; } /* (non-Javadoc) * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction) */ public void run(IAction action) { System.out.println("PyExtractMethod "); try { // Select from text editor ps = new PySelection ( getTextEditor ( ), false ); if(areRefactorPreconditionsOK(getPyEdit())==false){ return; } // Perform the action perform ( action ); // Put cursor at the first area of the selection getTextEditor ( ).selectAndReveal ( ps.endLine.getOffset ( ), 0 ); } catch ( Exception e ) { beep ( e ); } } /** * @param action */ protected abstract void perform(IAction action) throws Exception; } |
From: Fabio Z. <fa...@us...> - 2004-09-15 17:36:04
|
Update of /cvsroot/pydev/org.python.pydev/src/org/python/pydev/editor/actions/refactoring In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv25379/src/org/python/pydev/editor/actions/refactoring Log Message: Directory /cvsroot/pydev/org.python.pydev/src/org/python/pydev/editor/actions/refactoring added to the repository |
Update of /cvsroot/pydev/org.python.pydev/src/org/python/pydev/editor/codecompletion In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv9579/src/org/python/pydev/editor/codecompletion Modified Files: PyCodeCompletion.java CompletionCache.java PythonShell.java PythonCompletionProcessor.java Added Files: ProposalsComparator.java Log Message: Code completion improvements. Starting refactoring integration with bicycle repair man. --- NEW FILE: ProposalsComparator.java --- /* * Created on Sep 14, 2004 * * @author Fabio Zadrozny */ package org.python.pydev.editor.codecompletion; import java.util.Comparator; import org.eclipse.jface.text.contentassist.ICompletionProposal; /** * @author Fabio Zadrozny */ public class ProposalsComparator implements Comparator { public int compare(Object o1, Object o2) { ICompletionProposal p1 = (ICompletionProposal) o1; ICompletionProposal p2 = (ICompletionProposal) o2; return p1.getDisplayString().compareToIgnoreCase(p2.getDisplayString()); } } Index: PythonShell.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev/src/org/python/pydev/editor/codecompletion/PythonShell.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** PythonShell.java 13 Sep 2004 19:47:54 -0000 1.3 --- PythonShell.java 14 Sep 2004 17:42:14 -0000 1.4 *************** *** 15,27 **** import org.eclipse.core.runtime.CoreException; /** - * TODO: Still only a test!! * @author Fabio Zadrozny */ public class PythonShell { ! public static final int BUFFER_SIZE = 1024; /** * Python server process. --- 15,48 ---- import org.eclipse.core.runtime.CoreException; + import org.python.pydev.plugin.SocketUtil; /** * @author Fabio Zadrozny */ public class PythonShell { + /** + * Reference to a 'global python shell' + */ + private static PythonShell pytonShell; + + + /** + * @return + * @throws CoreException + * @throws IOException + * + */ + public static PythonShell getServerShell() throws IOException, CoreException { + if(pytonShell == null){ + pytonShell = new PythonShell(); + pytonShell.startIt(); + } + return pytonShell; + + } + ! public static final int BUFFER_SIZE = 1024 * 4; /** * Python server process. *************** *** 105,114 **** public void startIt() throws IOException{ try { ! process = Runtime.getRuntime().exec("python "+serverFile.getAbsolutePath()+" 50007 50008"); sleepALittle(); ! socketToWrite = new Socket("127.0.0.1",50007); //we should write in port 50007 ! serverSocket = new ServerSocket(50008); //and read in port 50008 socketToRead = serverSocket.accept(); } catch (IOException e) { --- 126,141 ---- public void startIt() throws IOException{ try { ! ! int pWrite = SocketUtil.findUnusedLocalPort("127.0.0.1", 50000, 55000); ! int pRead = SocketUtil.findUnusedLocalPort("127.0.0.1", 55001, 60000); ! ! if(process != null) ! endIt(); ! process = Runtime.getRuntime().exec("python "+serverFile.getAbsolutePath()+" "+pWrite+" "+pRead); sleepALittle(); ! socketToWrite = new Socket("127.0.0.1",pWrite); //we should write in this port ! serverSocket = new ServerSocket(pRead); //and read in this port socketToRead = serverSocket.accept(); } catch (IOException e) { *************** *** 130,140 **** String str = ""; ! while(str.indexOf("END@@") == -1 ){ byte[] b = new byte[PythonShell.BUFFER_SIZE]; this.socketToRead.getInputStream().read(b); String s = new String(b); str += s; } --- 157,171 ---- String str = ""; ! int j = 0; ! while(str.indexOf("END@@") == -1 && j != 100){ byte[] b = new byte[PythonShell.BUFFER_SIZE]; this.socketToRead.getInputStream().read(b); + // System.out.println("READ:"+new String(b)); + String s = new String(b); str += s; + j++; } *************** *** 142,146 **** str = str.replaceFirst("@@COMPLETIONS",""); //remove END@@ ! return str.substring(0, str.indexOf("END@@")); } --- 173,177 ---- str = str.replaceFirst("@@COMPLETIONS",""); //remove END@@ ! return str.substring(0, str.lastIndexOf("END@@")); } *************** *** 151,154 **** --- 182,186 ---- */ public void write(String str) throws IOException { + // System.out.println("WRITING:"+str); this.socketToWrite.getOutputStream().write(str.getBytes()); } *************** *** 181,185 **** * @throws IOException */ ! void endIt() throws IOException { try { --- 213,217 ---- * @throws IOException */ ! void endIt() { try { *************** *** 189,206 **** } if (process!= null){ ! int i = process.getErrorStream().available(); ! byte b[] = new byte[i]; ! process.getErrorStream().read(b); ! System.out.println(new String(b)); ! ! i = process.getInputStream().available(); ! b = new byte[i]; ! process.getErrorStream().read(b); ! System.out.println(new String(b)); ! ! process.destroy(); try { process.waitFor(); ! } catch (InterruptedException e1) { e1.printStackTrace(); } --- 221,247 ---- } if (process!= null){ ! try { ! int i = process.getErrorStream().available(); ! byte b[] = new byte[i]; ! process.getErrorStream().read(b); ! System.out.println(new String(b)); ! ! i = process.getInputStream().available(); ! b = new byte[i]; ! process.getErrorStream().read(b); ! System.out.println(new String(b)); ! } catch (Exception e1) { ! e1.printStackTrace(); ! } ! ! try { ! process.destroy(); ! } catch (Exception e2) { ! e2.printStackTrace(); ! } ! try { process.waitFor(); ! } catch (Exception e1) { e1.printStackTrace(); } *************** *** 210,214 **** } ! /** --- 251,277 ---- } ! public void sendGoToDirMsg(File file){ ! try { ! if(file.isDirectory() == false){ ! file = file.getParentFile(); ! } ! System.out.println("changing dir:"+file.getAbsolutePath()); ! this.write("@@CHANGE_DIR:"+file.getAbsolutePath()+"END@@"); ! String ok = this.read(); //this should be the ok message... ! ! } catch (IOException e) { ! e.printStackTrace(); ! } ! } ! ! public void sendReloadModulesMsg(){ ! try { ! this.write("@@RELOAD_MODULES_END@@"); ! String ok = this.read(); //this should be the ok message... ! ! } catch (IOException e) { ! e.printStackTrace(); ! } ! } /** *************** *** 217,241 **** */ public List getGlobalCompletions(String str) { ! try { ! this.write("@@GLOBALS:"+str+"\nEND@@"); ! ! return getCompletions(); ! } catch (IOException e) { ! e.printStackTrace(); ! try { ! this.endIt(); ! } catch (IOException e1) { ! // TODO Auto-generated catch block ! e1.printStackTrace(); ! } ! try { ! this.startIt(); ! } catch (IOException e2) { ! // TODO Auto-generated catch block ! e2.printStackTrace(); ! } ! return getInvalidCompletion(); ! } ! } --- 280,284 ---- */ public List getGlobalCompletions(String str) { ! return this.getTheCompletions("@@GLOBALS:"+str+"\nEND@@"); } *************** *** 246,269 **** public List getTokenCompletions(String token, String str) { String s = "@@TOKEN_GLOBALS("+token+"):"+str+"\nEND@@"; ! try { ! this.write(s); ! ! return getCompletions(); ! } catch (IOException e) { ! e.printStackTrace(); ! try { ! this.endIt(); ! } catch (IOException e1) { ! // TODO Auto-generated catch block ! e1.printStackTrace(); ! } ! try { ! this.startIt(); ! } catch (IOException e2) { ! // TODO Auto-generated catch block ! e2.printStackTrace(); ! } ! return getInvalidCompletion(); ! } } --- 289,293 ---- public List getTokenCompletions(String token, String str) { String s = "@@TOKEN_GLOBALS("+token+"):"+str+"\nEND@@"; ! return this.getTheCompletions(s); } *************** *** 275,294 **** public List getClassCompletions(String token, String str) { String s = "@@CLASS_GLOBALS("+token+"):"+str+"\nEND@@"; try { ! this.write(s); return getCompletions(); ! } catch (IOException e) { e.printStackTrace(); ! try { ! this.endIt(); ! } catch (IOException e1) { ! // TODO Auto-generated catch block ! e1.printStackTrace(); ! } try { this.startIt(); } catch (IOException e2) { - // TODO Auto-generated catch block e2.printStackTrace(); } --- 299,317 ---- public List getClassCompletions(String token, String str) { String s = "@@CLASS_GLOBALS("+token+"):"+str+"\nEND@@"; + return this.getTheCompletions(s); + } + + private List getTheCompletions(String str){ try { ! this.write(str); return getCompletions(); ! } catch (Exception e) { e.printStackTrace(); ! ! this.endIt(); try { this.startIt(); } catch (IOException e2) { e2.printStackTrace(); } *************** *** 296,300 **** } } ! /** * @return --- 319,323 ---- } } ! /** * @return Index: PyCodeCompletion.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev/src/org/python/pydev/editor/codecompletion/PyCodeCompletion.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** PyCodeCompletion.java 13 Sep 2004 19:47:54 -0000 1.5 --- PyCodeCompletion.java 14 Sep 2004 17:42:14 -0000 1.6 *************** *** 6,17 **** package org.python.pydev.editor.codecompletion; - import java.io.BufferedReader; import java.io.File; import java.io.IOException; - import java.io.InputStreamReader; - import java.io.OutputStreamWriter; import java.net.URL; import java.util.ArrayList; - import java.util.Iterator; import java.util.List; --- 6,13 ---- *************** *** 64,78 **** * @param documentOffset * - * @param theCode * @param theActivationToken * @return */ ! public List autoComplete(PyEdit edit, IDocument doc, int documentOffset, java.lang.String theCode, java.lang.String theActivationToken) { ! if(PyCodeCompletionPreferencesPage.useServerTipEnviroment()){ ! return serverCompletion(theActivationToken, edit, doc, documentOffset, theCode); ! }else{ ! return consoleCompletion(theCode); ! } } --- 60,69 ---- * @param documentOffset * * @param theActivationToken * @return */ ! public List autoComplete(PyEdit edit, IDocument doc, int documentOffset, java.lang.String theActivationToken) { ! return serverCompletion(theActivationToken, edit, doc, documentOffset); } *************** *** 82,93 **** * @param doc * @param documentOffset - * @param theCode - * @param theCode */ ! private List serverCompletion(String theActivationToken, PyEdit edit, IDocument doc, int documentOffset, String theCode) { List theList = new ArrayList(); PythonShell serverShell = null; try { ! serverShell = getServerShell(); } catch (Exception e) { throw new RuntimeException(e); --- 73,82 ---- * @param doc * @param documentOffset */ ! private List serverCompletion(String theActivationToken, PyEdit edit, IDocument doc, int documentOffset) { List theList = new ArrayList(); PythonShell serverShell = null; try { ! serverShell = PythonShell.getServerShell(); } catch (Exception e) { throw new RuntimeException(e); *************** *** 98,102 **** String trimmed = theActivationToken.replace('.',' ').trim(); ! if (trimmed.equals("") == false){ List completions; --- 87,91 ---- String trimmed = theActivationToken.replace('.',' ').trim(); ! if (trimmed.equals("") == false && theActivationToken.indexOf('.') != -1){ List completions; *************** *** 115,119 **** } else{ //go to globals - // System.out.println("simpleCompletion - ''"); List completions = serverShell.getGlobalCompletions(docToParse); theList.addAll(completions); --- 104,107 ---- *************** *** 151,156 **** newDoc += wholeDoc.substring(lineInformation.getOffset() + lineInformation.getLength(), docLength); - // System.out.println("DOC:"+newDoc); - } catch (BadLocationException e1) { e1.printStackTrace(); --- 139,142 ---- *************** *** 159,247 **** } - /** - * @return - * @throws CoreException - * @throws IOException - * - */ - private PythonShell getServerShell() throws IOException, CoreException { - if(pytonShell == null){ - pytonShell = new PythonShell(); - pytonShell.startIt(); - } - return pytonShell; - - } - - /** - * @param theCode - */ - private List consoleCompletion(java.lang.String theCode) { - List theList = new ArrayList(); - File tipperFile=null; - try { - - tipperFile = getAutoCompleteScript(false); - - } catch (CoreException e) { - - e.printStackTrace(); - } - - try { - Process p = Runtime.getRuntime().exec(new String[]{"python"}); - - //we have the process... - OutputStreamWriter writer = new OutputStreamWriter(p.getOutputStream()); - BufferedReader in = new BufferedReader(new InputStreamReader(p - .getInputStream())); - BufferedReader eIn = new BufferedReader(new InputStreamReader( - p.getErrorStream())); - - //we have to put the tipper in sys.path - writer.write("import sys\n"); - writer.write("sys.path.insert(0,r'"+tipperFile.getParent()+"')\n"); - - writer.write("from tipper import GenerateTip\n"); - - theCode = theCode.replaceAll("\r",""); - theCode = theCode.replaceAll("\n","\\\\n"); - - theCode = theCode.replaceAll("'","@l@l@*"); //TODO: that's a really bad way to do it... - - writer.write("s = '"+theCode+"'\n"); - writer.write("s = s.replace('@l@l@*', '\\'')\n"); - - writer.write("GenerateTip(s)\n\n\n"); - writer.flush(); - writer.close(); - - String str; - while ((str = in.readLine()) != null) { - if (!str.startsWith("tip: ")){ - // System.out.println("std output: " + str); - continue; - } - - str = str.substring(5); - - theList.add(new String[]{str,""}); - } - in.close(); - while ((str = eIn.readLine()) != null) { - // System.out.println("error output: " + str); - } - eIn.close(); - p.waitFor(); - } catch (IOException e) { - - e.printStackTrace(); - } catch (InterruptedException e) { - - e.printStackTrace(); - } - return theList; - } /** --- 145,149 ---- *************** *** 252,261 **** * @throws CoreException */ ! public static File getAutoCompleteScript(boolean useSimpleTipper) throws CoreException { ! if(useSimpleTipper){ ! return getScriptWithinPySrc("simpleTipper.py"); ! }else{ ! return getScriptWithinPySrc("tipper.py"); ! } } --- 154,159 ---- * @throws CoreException */ ! public static File getAutoCompleteScript() throws CoreException { ! return getScriptWithinPySrc("simpleTipper.py"); } Index: PythonCompletionProcessor.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev/src/org/python/pydev/editor/codecompletion/PythonCompletionProcessor.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** PythonCompletionProcessor.java 13 Sep 2004 17:11:50 -0000 1.4 --- PythonCompletionProcessor.java 14 Sep 2004 17:42:14 -0000 1.5 *************** *** 6,9 **** --- 6,10 ---- import java.util.ArrayList; + import java.util.Arrays; import java.util.Iterator; import java.util.List; *************** *** 34,37 **** --- 35,40 ---- private PyEdit edit; + private ProposalsComparator proposalsComparator = new ProposalsComparator(); + /** * @param edit *************** *** 66,70 **** java.lang.String qualifier = ""; - char[] cs = new char[]{'.', '(', ' '}; //we complete on '.' and '('. --- 69,72 ---- *************** *** 74,78 **** //we have to get the qualifier. e.g. bla.foo = foo is the qualifier. if(activationToken.indexOf('.')!= -1){ ! while (endsWithSomeChar(cs, activationToken) == false && activationToken.length() > 0) { --- 76,80 ---- //we have to get the qualifier. e.g. bla.foo = foo is the qualifier. if(activationToken.indexOf('.')!= -1){ ! while (endsWithSomeChar(new char[]{'.'}, activationToken) == false && activationToken.length() > 0) { *************** *** 82,85 **** --- 84,90 ---- .length() - 1); } + }else{ //everything is a part of the qualifier. + qualifier = activationToken; + activationToken = ""; } *************** *** 89,92 **** --- 94,105 ---- theDoc += "\n" + activationToken; + + try { + PythonShell.getServerShell().sendGoToDirMsg(edit.getEditorFile()); + } catch (Exception e) { + //if we don't suceed, we don't have to fail... just go on and try to complete... + e.printStackTrace(); + } + List pythonProposals = getPythonProposals(documentOffset, doc, theDoc, activationToken, qlen); *************** *** 110,113 **** --- 123,128 ---- // and fill with list elements returnProposals.toArray(proposals); + + Arrays.sort(proposals, proposalsComparator); // Return the proposals return proposals; Index: CompletionCache.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev/src/org/python/pydev/editor/codecompletion/CompletionCache.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** CompletionCache.java 13 Sep 2004 17:11:50 -0000 1.2 --- CompletionCache.java 14 Sep 2004 17:42:14 -0000 1.3 *************** *** 44,49 **** if(allProposals == null){ //no cache proposals ! List theList = codeCompletion.autoComplete(edit, doc, ! documentOffset, partialDoc, activationToken); allProposals = new ArrayList(); --- 44,48 ---- if(allProposals == null){ //no cache proposals ! List theList = codeCompletion.autoComplete(edit, doc, documentOffset, activationToken); allProposals = new ArrayList(); *************** *** 56,66 **** allProposals.add(proposal); } ! cacheEntries.add(partialDoc); ! cache.put(partialDoc, allProposals); ! //we don't want this to get huge... ! if (cacheEntries.size() > 2) { ! Object entry = cacheEntries.remove(0); ! cache.remove(entry); ! } } return allProposals; --- 55,59 ---- allProposals.add(proposal); } ! addProposalsToCache(partialDoc, allProposals); } return allProposals; *************** *** 70,73 **** --- 63,80 ---- /** * @param partialDoc + * @param allProposals + */ + private void addProposalsToCache(String partialDoc, List allProposals) { + cacheEntries.add(partialDoc); + cache.put(partialDoc, allProposals); + //we don't want this to get huge... + if (cacheEntries.size() > 4) { + Object entry = cacheEntries.remove(0); + cache.remove(entry); + } + } + + /** + * @param partialDoc * @param documentOffset * @param qlen |
From: Fabio Z. <fa...@us...> - 2004-09-14 17:42:54
|
Update of /cvsroot/pydev/org.python.pydev In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv9579 Modified Files: plugin.xml Log Message: Code completion improvements. Starting refactoring integration with bicycle repair man. Index: plugin.xml =================================================================== RCS file: /cvsroot/pydev/org.python.pydev/plugin.xml,v retrieving revision 1.34 retrieving revision 1.35 diff -C2 -d -r1.34 -r1.35 *** plugin.xml 25 Aug 2004 17:24:23 -0000 1.34 --- plugin.xml 14 Sep 2004 17:42:08 -0000 1.35 *************** *** 4,8 **** id="org.python.pydev" name="Pydev - Python Development Environment" ! version="0.5.9.1" provider-name="AleksTotic" class="org.python.pydev.plugin.PydevPlugin"> --- 4,8 ---- id="org.python.pydev" name="Pydev - Python Development Environment" ! version="0.5.9.4" provider-name="AleksTotic" class="org.python.pydev.plugin.PydevPlugin"> *************** *** 172,175 **** --- 172,182 ---- </action> <action + definitionId="org.python.pydev.editor.actions.pyReloadCodeCompletionModules" + label="Reload the modules used for code completion" + class="org.python.pydev.editor.actions.PyReloadCodeCompletionModules" + menubarPath="org.python.pydev.editor.actions.sourceMenu/addGroup" + id="org.python.pydev.editor.actions.pyReloadCodeCompletionModules"> + </action> + <action definitionId="org.python.pydev.editor.actions.navigation.nextMethod" label="Goto next method or class" *************** *** 406,409 **** --- 413,429 ---- configuration="org.eclipse.ui.defaultAcceleratorConfiguration"> </keyBinding> + <!-- command: reload modules --> + <command + name="Reload the code completion modules" + description="Creates a python comment block" + category="org.python.pydev.ui.category.source" + id="org.python.pydev.editor.actions.pyReloadCodeCompletionModules"> + </command> + <keyBinding + string="Ctrl+Shift+Space" + scope="org.python.pydev.ui.editor.scope" + command="org.python.pydev.editor.actions.pyReloadCodeCompletionModules" + configuration="org.eclipse.ui.defaultAcceleratorConfiguration"> + </keyBinding> <!-- command: block--> <command |
From: Fabio Z. <fa...@us...> - 2004-09-14 17:42:48
|
Update of /cvsroot/pydev/org.python.pydev/PySrc In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv9579/PySrc Modified Files: pycompletionserver.py simpleTipper.py test_pyserver.py test_simpleTipper.py Added Files: importsTipper.py refactoring.py Log Message: Code completion improvements. Starting refactoring integration with bicycle repair man. Index: pycompletionserver.py =================================================================== RCS file: /cvsroot/pydev/org.python.pydev/PySrc/pycompletionserver.py,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** pycompletionserver.py 13 Sep 2004 19:47:54 -0000 1.5 --- pycompletionserver.py 14 Sep 2004 17:42:07 -0000 1.6 *************** *** 8,12 **** HOST = '127.0.0.1' # Symbolic name meaning the local host - MSG_KILL_SERVER = '@@KILL_SERVER_END@@' MSG_COMPLETIONS = '@@COMPLETIONS' --- 8,11 ---- *************** *** 16,21 **** MSG_CLASS_GLOBALS = '@@CLASS_GLOBALS(' MSG_INVALID_REQUEST = '@@INVALID_REQUEST' ! BUFFER_SIZE = 1024 class T(threading.Thread): --- 15,23 ---- MSG_CLASS_GLOBALS = '@@CLASS_GLOBALS(' MSG_INVALID_REQUEST = '@@INVALID_REQUEST' + MSG_RELOAD_MODULES = '@@RELOAD_MODULES_END@@' + MSG_CHANGE_DIR = '@@CHANGE_DIR:' + MSG_OK = '@@MSG_OK_END@@' ! BUFFER_SIZE = 1024 * 4 class T(threading.Thread): *************** *** 62,65 **** --- 64,70 ---- self.socket.send(MSG_INVALID_REQUEST) + def sendOkMsg(self): + self.socket.send(MSG_OK) + def getTokenAndData(self, data): ''' *************** *** 99,132 **** data = '' while not data.endswith(MSG_END): ! data += conn.recv(BUFFER_SIZE) if MSG_KILL_SERVER in data: #break if we received kill message. break; - else: - data = data.rstrip(MSG_END) - - if MSG_GLOBALS in data: - data = data.replace(MSG_GLOBALS, '') - comps = simpleTipper.GenerateTip(data, None, False) - self.sendCompletionsMessage(comps) - - elif MSG_TOKEN_GLOBALS in data: - data = data.replace(MSG_TOKEN_GLOBALS, '') - token, data = self.getTokenAndData(data) - comps = simpleTipper.GenerateTip(data, token, False) - self.sendCompletionsMessage(comps) ! elif MSG_CLASS_GLOBALS in data: ! data = data.replace(MSG_CLASS_GLOBALS, '') ! token, data = self.getTokenAndData(data) ! comps = simpleTipper.GenerateTip(data, token, True) ! self.sendCompletionsMessage(comps) else: ! self.sendReceivedInvalidMessage() - conn.send(data) conn.close() --- 104,145 ---- data = '' while not data.endswith(MSG_END): ! data+=conn.recv(BUFFER_SIZE) if MSG_KILL_SERVER in data: #break if we received kill message. break; ! elif MSG_RELOAD_MODULES in data: ! simpleTipper.ReloadModules() ! self.sendOkMsg() else: ! data = data[:data.find(MSG_END)] + if MSG_GLOBALS in data: + data = data.replace(MSG_GLOBALS, '') + comps = simpleTipper.GenerateTip(data, None, False) + self.sendCompletionsMessage(comps) + + elif MSG_TOKEN_GLOBALS in data: + data = data.replace(MSG_TOKEN_GLOBALS, '') + token, data = self.getTokenAndData(data) + comps = simpleTipper.GenerateTip(data, token, False) + self.sendCompletionsMessage(comps) + + elif MSG_CLASS_GLOBALS in data: + data = data.replace(MSG_CLASS_GLOBALS, '') + token, data = self.getTokenAndData(data) + comps = simpleTipper.GenerateTip(data, token, True) + self.sendCompletionsMessage(comps) + + elif MSG_CHANGE_DIR in data: + data = data.replace(MSG_CHANGE_DIR, '') + simpleTipper.CompleteFromDir(data) + self.sendOkMsg() + + else: + self.sendReceivedInvalidMessage() conn.close() Index: simpleTipper.py =================================================================== RCS file: /cvsroot/pydev/org.python.pydev/PySrc/simpleTipper.py,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** simpleTipper.py 13 Sep 2004 19:47:54 -0000 1.3 --- simpleTipper.py 14 Sep 2004 17:42:07 -0000 1.4 *************** *** 3,7 **** --- 3,35 ---- ''' import compiler + import sys + + __eraseThisCurrDirModule = None + def CompleteFromDir(dir): + ''' + This is necessary so that we get the imports from the same dir where the file + we are completing is located. + ''' + global __eraseThisCurrDirModule + if __eraseThisCurrDirModule is not None: + del sys.path[__eraseThisCurrDirModule] + + sys.path.insert(0, dir) + + def GenerateImportsTip(theDoc): + pass + + def ReloadModules(): + ''' + Reload all the modules in sys.modules + ''' + import sys + for m,n in sys.modules.items(): + try: + reload(n) + except: #some errors may arise because some modules may not be reloaded... + pass + def GenerateTip (theDoc, token, checkForSelf): ''' *************** *** 37,47 **** for d in dir(%s): __eraseThisTips.append([d,inspect.getdoc(getattr(%s, d))]) ! ''' % (token,token) import simpleinspect try: __eraseThis = compiler.compile(theDoc, 'temporary_file_completion.py', 'exec') simpleinspect.__eraseThisTips = [] --- 65,78 ---- for d in dir(%s): __eraseThisTips.append([d,inspect.getdoc(getattr(%s, d))]) ! ''' % (token.replace(' ','.'),token.replace(' ','.')) import simpleinspect + __eraseThisMsg = '' try: + __eraseThisMsg += 'Compiling \n%s\n'%theDoc __eraseThis = compiler.compile(theDoc, 'temporary_file_completion.py', 'exec') + __eraseThisMsg += 'Compiled' simpleinspect.__eraseThisTips = [] *************** *** 50,53 **** --- 81,85 ---- simpleinspect.__eraseThisTips = [] + __eraseThisMsg += 'Getting self variables \n%s\n' % originalDoc if checkForSelf: toReturn += GetSelfVariables(originalDoc, token) *************** *** 57,62 **** import sys s = str(sys.exc_info()[1]) ! print s ! return [('ERROR_COMPLETING',s)] class Visitor(compiler.visitor.ASTVisitor): --- 89,93 ---- import sys s = str(sys.exc_info()[1]) ! return [('ERROR_COMPLETING','%s\nerror tracing:\n%s'%(s,__eraseThisMsg))] class Visitor(compiler.visitor.ASTVisitor): Index: test_pyserver.py =================================================================== RCS file: /cvsroot/pydev/org.python.pydev/PySrc/test_pyserver.py,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** test_pyserver.py 13 Sep 2004 19:47:54 -0000 1.3 --- test_pyserver.py 14 Sep 2004 17:42:07 -0000 1.4 *************** *** 6,9 **** --- 6,10 ---- import pycompletionserver import socket + import os class Test(unittest.TestCase): *************** *** 88,91 **** --- 89,117 ---- self.assert_(len(completions) != len(completions2)) + + #reload modules test + # sToWrite.send('@@RELOAD_MODULES_END@@') + # ok = connToRead.recv(4086) + # self.assertEquals('@@MSG_OK_END@@' , ok) + # this test is not executed because it breaks our current enviroment. + + + + #change dir test + curr = os.getcwd( ) + newDir = None + + if curr.find('/') != -1: + newDir = curr[0:curr.rindex('/')] + elif curr.find('\\') != -1: + newDir = curr[0:curr.rindex('\\')] + + self.assert_(newDir != None) + sToWrite.send('@@CHANGE_DIR:%sEND@@'%newDir) + ok = connToRead.recv(4086) + self.assertEquals('@@MSG_OK_END@@' , ok) + sToWrite.send('@@TOKEN_GLOBALS(math acos):import math\nEND@@') + completions = connToRead.recv(4086) + self.sendKillMsg(sToWrite) *************** *** 104,105 **** --- 130,132 ---- if __name__ == '__main__': unittest.main() + --- NEW FILE: refactoring.py --- import sys import os sys.path.insert(1, os.path.join(os.path.dirname(sys.argv[0]), "ThirdParty", "brm")) import ThirdParty.brm.bike as bike class Refactoring(object): def __init__(self): self.init() def init(self): """ Private slot to handle the Reset action. """ self.brmctx = bike.init() self.logging = Preferences.getRefactoring("Logging") if self.logging: self.brmctx.setProgressLogger(self.ui.stdout) else: self.brmctx.setProgressLogger(SilentLogger()) self.brmctx.setWarningLogger(self.ui.stderr) def handleReset(self): """ Private slot to handle the Reset action. """ self.init() Index: test_simpleTipper.py =================================================================== RCS file: /cvsroot/pydev/org.python.pydev/PySrc/test_simpleTipper.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** test_simpleTipper.py 13 Sep 2004 19:47:54 -0000 1.2 --- test_simpleTipper.py 14 Sep 2004 17:42:07 -0000 1.3 *************** *** 5,9 **** import unittest import simpleTipper ! class Test(unittest.TestCase): --- 5,10 ---- import unittest import simpleTipper ! import importsTipper ! class Test(unittest.TestCase): *************** *** 95,99 **** --- 96,111 ---- + def getDoc3(self): + pass + + def testImports(self): + raise RuntimeError('not implemented') + importsTipper.GenerateImportsTip(0) + + + + + if __name__ == '__main__': unittest.main() --- NEW FILE: importsTipper.py --- def GenerateImportsTip(theDoc): pass |
From: Fabio Z. <fa...@us...> - 2004-09-14 17:42:29
|
Update of /cvsroot/pydev/org.python.pydev/src/org/python/pydev/editor In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv9579/src/org/python/pydev/editor Modified Files: PyEdit.java Log Message: Code completion improvements. Starting refactoring integration with bicycle repair man. Index: PyEdit.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev/src/org/python/pydev/editor/PyEdit.java,v retrieving revision 1.21 retrieving revision 1.22 diff -C2 -d -r1.21 -r1.22 *** PyEdit.java 13 Sep 2004 17:11:53 -0000 1.21 --- PyEdit.java 14 Sep 2004 17:42:17 -0000 1.22 *************** *** 6,9 **** --- 6,10 ---- package org.python.pydev.editor; + import java.io.File; import java.util.ArrayList; import java.util.Iterator; *************** *** 31,34 **** --- 32,36 ---- import org.eclipse.ui.PartInitException; import org.eclipse.ui.editors.text.ILocationProvider; + import org.eclipse.ui.part.FileEditorInput; import org.eclipse.ui.texteditor.DefaultRangeIndicator; import org.eclipse.ui.texteditor.IEditorStatusLine; *************** *** 189,194 **** } ! ! // cleanup public void dispose() { PydevPrefs.getPreferences().removePropertyChangeListener(prefListener); --- 191,213 ---- } ! ! ! /** ! * @return ! * ! */ ! public File getEditorFile() { ! File f = null; ! IEditorInput editorInput = this.getEditorInput(); ! if (editorInput instanceof FileEditorInput){ ! IFile file = (IFile) ((FileEditorInput)editorInput).getAdapter(IFile.class); ! ! IPath path = file.getLocation().makeAbsolute(); ! f = path.toFile(); ! } ! return f; ! } ! ! // cleanup public void dispose() { PydevPrefs.getPreferences().removePropertyChangeListener(prefListener); |
From: Fabio Z. <fa...@us...> - 2004-09-14 17:42:29
|
Update of /cvsroot/pydev/org.python.pydev/src/org/python/pydev/editor/actions In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv9579/src/org/python/pydev/editor/actions Added Files: PyReloadCodeCompletionModules.java Log Message: Code completion improvements. Starting refactoring integration with bicycle repair man. --- NEW FILE: PyReloadCodeCompletionModules.java --- /* * Created on Sep 14, 2004 * * @author Fabio Zadrozny */ package org.python.pydev.editor.actions; import java.io.IOException; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.action.IAction; import org.python.pydev.editor.codecompletion.PythonShell; /** * @author Fabio Zadrozny */ public class PyReloadCodeCompletionModules extends PyAction{ /* (non-Javadoc) * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction) */ public void run(IAction action) { try { PythonShell.getServerShell().sendReloadModulesMsg(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } |
From: Fabio Z. <fa...@us...> - 2004-09-14 17:42:29
|
Update of /cvsroot/pydev/org.python.pydev/src/org/python/pydev/plugin In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv9579/src/org/python/pydev/plugin Added Files: SocketUtil.java Log Message: Code completion improvements. Starting refactoring integration with bicycle repair man. --- NEW FILE: SocketUtil.java --- /* * Author: atotic * Created on Mar 22, 2004 * License: Common Public License v1.0 */ package org.python.pydev.plugin; import java.io.IOException; import java.net.ConnectException; import java.net.Socket; import java.util.Random; /** * Utility class to find a port to debug on. * * Straight copy of package org.eclipse.jdt.launching.SocketUtil. * I just could not figure out how to import that one. * No dependencies kept it on the classpath reliably */ public class SocketUtil { private static final Random fgRandom= new Random(System.currentTimeMillis()); /** * Returns a free port number on the specified host within the given range, * or -1 if none found. * * @param host name or IP addres of host on which to find a free port * @param searchFrom the port number from which to start searching * @param searchTo the port number at which to stop searching * @return a free port in the specified range, or -1 of none found */ public static int findUnusedLocalPort(String host, int searchFrom, int searchTo) { for (int i= 0; i < 10; i++) { Socket s= null; int port= getRandomPort(searchFrom, searchTo); try { s= new Socket(host, port); } catch (ConnectException e) { return port; } catch (IOException e) { } finally { if (s != null) { try { s.close(); } catch (IOException ioe) { } } } } return -1; } private static int getRandomPort(int low, int high) { return (int)(fgRandom.nextFloat() * (high-low)) + low; } } |
From: Fabio Z. <fa...@us...> - 2004-09-14 17:42:27
|
Update of /cvsroot/pydev/org.python.pydev/PySrc/ThirdParty In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv9579/PySrc/ThirdParty Added Files: __init__.py Log Message: Code completion improvements. Starting refactoring integration with bicycle repair man. --- NEW FILE: __init__.py --- |
From: Fabio Z. <fa...@us...> - 2004-09-14 17:42:27
|
Update of /cvsroot/pydev/org.python.pydev/PySrc/ThirdParty/brm/bike/transformer In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv9579/PySrc/ThirdParty/brm/bike/transformer Added Files: undo.py save.py WordRewriter.py __init__.py Log Message: Code completion improvements. Starting refactoring integration with bicycle repair man. --- NEW FILE: __init__.py --- """ Package containing modules which transform the internal representation of the sourcecode. """ --- NEW FILE: WordRewriter.py --- from bike.parsing.load import getSourceNode from bike.transformer.undo import getUndoStack from bike.transformer.save import queueFileToSave import re # This class maintains a set of changed lines to the original source # nodes. This is important because the act of changing a line messes # up the coordinates on which renames are done. # Commit writes the changes back to the source nodes class WordRewriter: def __init__(self): self.modifiedsrc = {} def rewriteString(self, srcnode, lineno, colno, newname): filename = srcnode.filename if not self.modifiedsrc.has_key(filename): getUndoStack().addSource(filename,srcnode.getSource()) self.modifiedsrc[filename] = {} if not self.modifiedsrc[filename].has_key(lineno): line = srcnode.getLines()[lineno-1] self.modifiedsrc[filename][lineno] = self._lineToDict(line) self.modifiedsrc[filename][lineno][colno] = newname # writes all the changes back to the src nodes def commit(self): for filename in self.modifiedsrc.keys(): srcnode = getSourceNode(filename) for lineno in self.modifiedsrc[filename]: lines = srcnode.getLines() lines[lineno-1] = self._dictToLine(self.modifiedsrc[filename][lineno]) queueFileToSave(filename,"".join(srcnode.getLines())) # this function creates a dictionary with each word referenced by # its column position in the original line def _lineToDict(self, line): words = re.split("(\w+)", line) h = {};i = 0 for word in words: h[i] = word i+=len(word) return h def _dictToLine(self, d): cols = d.keys() cols.sort() return "".join([d[colno]for colno in cols]) --- NEW FILE: save.py --- from bike import log outputqueue = {} def getQueuedFile(filename): try: return outputqueue[filename] except: pass #print "HERE!" def resetOutputQueue(): global outputqueue outputqueue = {} def queueFileToSave(filename,src): outputqueue[filename] = src from bike.parsing.load import getSourceNode getSourceNode(filename).resetWithSource(src) def save(): from bike.transformer.undo import getUndoStack global outputqueue savedFiles = [] for filename,src in outputqueue.iteritems(): print >> log.progress, "Writing:",filename f = file(filename, "w+") f.write(outputqueue[filename]) f.close() savedFiles.append(filename) outputqueue = {} #print "stack is "+ str(getUndoStack().stack) getUndoStack().commitUndoFrame() return savedFiles --- NEW FILE: undo.py --- from bike import log from bike.transformer.save import queueFileToSave _undoStack = None def getUndoStack(forceNewStack = 0): global _undoStack if _undoStack is None or forceNewStack: _undoStack = UndoStack() return _undoStack class UndoStackEmptyException: pass class UndoStack(object): def __init__(self): self.stack = [] self.stack.append({}) self.frame = self.stack[-1] self.setUndoBufferSize(10) def setUndoBufferSize(self, undoBufferSize): self.undoBufferSize = undoBufferSize def addSource(self, filename, src): if filename not in self.frame: self.frame[filename] = src def commitUndoFrame(self): #restrict size of buffer while len(self.stack) > self.undoBufferSize: #print "clipping undo stack" del self.stack[0] if len(self.frame) != 0: #print "commitUndoFrame" self.stack.append({}) self.frame = self.stack[-1] def undo(self, **opts): #print "undo called",self.stack if len(self.stack) < 2: raise UndoStackEmptyException() undoframe = self.stack[-2] #print "undoframe is",undoframe for filename,src in undoframe.iteritems(): print >>log.progress, "Undoing:",filename queueFileToSave(filename,src) self.stack = self.stack[:-2] self.stack.append({}) self.frame = self.stack[-1] |