pydev-cvs Mailing List for PyDev for Eclipse (Page 3)
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...> - 2008-09-27 20:04:03
|
Update of /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/ui/pages/extractmethod In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv21605/src/org/python/pydev/refactoring/ui/pages/extractmethod Modified Files: ExtractMethodPage.java ExtractMethodComposite.java Log Message: Synching to latest changes: Pydev <ul> <li><strong>Editor</strong>: Cursor settings no longer overridden</li> <li><strong>Code-completion</strong>: If __all__ is defined with runtime elements (and not only in a single assign statement), it's ignored for code-completion purposes</li> <li><strong>Debugger</strong>: Pythonpath the same in debug and regular modes (sys.path[0] is the same directory as the file run)</li> <li><strong>Debugger</strong>: Persist choices done in the debugger when files from the debugger are not found</li> <li><strong>Interpreter config</strong>: "email" automatically added to the "forced builtins"</li> <li><strong>Parser</strong>: Correctly recognizing absolute import with 3 or more levels</li> <li><strong>Syntax check</strong>: Option to do only on active editor</li> </ul> Also: tabs changed for spaces Index: ExtractMethodComposite.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/ui/pages/extractmethod/ExtractMethodComposite.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** ExtractMethodComposite.java 20 Oct 2007 19:31:05 -0000 1.3 --- ExtractMethodComposite.java 27 Sep 2008 20:00:47 -0000 1.4 *************** *** 53,438 **** public class ExtractMethodComposite extends Composite { ! private Label functionPreviewLabel; ! private Label functionSignatureLabel; ! private Label argumentsLabel; ! private Button editArgumentsButton; ! private TableColumn nameColumn; ! private Table argumentsTable; ! private Button downArgumentsButton; ! private Button upArgumentsButton; ! private LabeledEdit functionNameEdit; ! private TableCellEditorListener cellEditorListener; ! private AbstractScopeNode<?> scopeAdapter; ! private IValidationPage page; ! private FunctionSignatureListener signatureListener; ! private OffsetStrategyProvider strategyProvider; ! private ComboViewer methodInsertionComb; ! private CLabel methodInsertionLbl; ! private Composite argumentsComposite; ! public ExtractMethodComposite(IValidationPage page, Composite parent, boolean hasArguments, AbstractScopeNode<?> scope) { ! super(parent, SWT.NONE); ! this.page = page; ! this.scopeAdapter = scope; ! this.strategyProvider = new OffsetStrategyProvider(scopeAdapter, IOffsetStrategy.AFTERINIT | IOffsetStrategy.BEGIN ! | IOffsetStrategy.END); ! createComposite(hasArguments); ! } ! public void createComposite(boolean hasArguments) { ! setLayout(new GridLayout()); ! createFunctionName(this); ! if (hasArguments) { ! createArguments(this); ! } ! createOffsetStrategy(this); ! createFunctionSignature(this); ! pack(); ! } ! private void createFunctionSignature(Composite control) { ! Composite functionSignatureComposite = new Composite(control, SWT.NONE); ! GridLayout compositeLayout = new GridLayout(); ! compositeLayout.makeColumnsEqualWidth = true; ! GridData compositeLData = new GridData(); ! compositeLData.horizontalAlignment = GridData.FILL; ! compositeLData.grabExcessHorizontalSpace = true; ! functionSignatureComposite.setLayoutData(compositeLData); ! functionSignatureComposite.setLayout(compositeLayout); ! functionSignatureLabel = new Label(functionSignatureComposite, SWT.NONE); ! GridData labelLData = new GridData(); ! labelLData.horizontalAlignment = GridData.FILL; ! labelLData.grabExcessHorizontalSpace = true; ! functionSignatureLabel.setLayoutData(labelLData); ! functionSignatureLabel.setText(Messages.extractMethodFunctionPreview); ! functionPreviewLabel = new Label(functionSignatureComposite, SWT.NONE); ! GridData functionSignaturePreviewData = new GridData(); ! functionSignaturePreviewData.horizontalAlignment = GridData.FILL; ! functionSignaturePreviewData.grabExcessHorizontalSpace = true; ! functionSignaturePreviewData.verticalAlignment = GridData.FILL; ! functionSignaturePreviewData.grabExcessVerticalSpace = true; ! functionPreviewLabel.setLayoutData(functionSignaturePreviewData); ! functionPreviewLabel.setText(""); ! } ! private Button createButton(Composite parent, String name) { ! Button button = new Button(parent, SWT.PUSH | SWT.CENTER); ! GridData buttonLData = new GridData(); ! buttonLData.horizontalAlignment = GridData.FILL; ! buttonLData.grabExcessHorizontalSpace = true; ! button.setLayoutData(buttonLData); ! button.setText(name); ! return button; ! } ! private void createArguments(Composite control) { ! argumentsComposite = new Composite(control, SWT.NONE); ! GridLayout compositeLayout = new GridLayout(); ! compositeLayout.makeColumnsEqualWidth = true; ! GridData compositeLData = new GridData(); ! compositeLData.grabExcessHorizontalSpace = true; ! compositeLData.horizontalAlignment = GridData.FILL; ! compositeLData.grabExcessVerticalSpace = true; ! compositeLData.verticalAlignment = GridData.FILL; ! argumentsComposite.setLayoutData(compositeLData); ! argumentsComposite.setLayout(compositeLayout); ! createArgumentsLabel(argumentsComposite); ! createArgumentsTable(argumentsComposite); ! } ! private void createArgumentsButton(Composite ArgumentsTableComposite) { ! Composite argumentsButtonComposite = new Composite(ArgumentsTableComposite, SWT.NONE); ! GridLayout compositeLayout = new GridLayout(); ! compositeLayout.makeColumnsEqualWidth = true; ! FormData compositeLData = new FormData(0, 0); ! compositeLData.width = 80; ! compositeLData.bottom = new FormAttachment(1000, 1000, 0); ! compositeLData.right = new FormAttachment(1000, 1000, 0); ! compositeLData.top = new FormAttachment(0, 1000, 0); ! argumentsButtonComposite.setLayoutData(compositeLData); ! argumentsButtonComposite.setLayout(compositeLayout); ! editArgumentsButton = createButton(argumentsButtonComposite, Messages.extractMethodEditButton); ! editArgumentsButton.setEnabled(false); ! upArgumentsButton = createButton(argumentsButtonComposite, Messages.extractMethodUpButton); ! upArgumentsButton.setEnabled(false); ! downArgumentsButton = createButton(argumentsButtonComposite, Messages.extractMethodDownButton); ! downArgumentsButton.setEnabled(false); ! } ! private void registerDownButtonListener() { ! downArgumentsButton.addSelectionListener(new SelectionAdapter() { ! @Override ! public void widgetSelected(SelectionEvent e) { ! int selectionIndex = argumentsTable.getSelectionIndex(); ! if (argumentsTable.getSelectionCount() == 1 && selectionIndex != argumentsTable.getItemCount()) { ! TableItem item = argumentsTable.getSelection()[0]; ! if (item instanceof SimpleTableItem) { ! SimpleTableItem tableItem = (SimpleTableItem) item; ! new SimpleTableItem(argumentsTable, tableItem.getOriginalName(), tableItem.getText(), selectionIndex + 2); ! argumentsTable.remove(selectionIndex); ! argumentsTable.setSelection(selectionIndex + 1); ! argumentsTable.notifyListeners(SWT.Selection, new Event()); ! page.validate(); ! } ! } ! } ! }); ! } ! private void registerUpButtonListener() { ! upArgumentsButton.addSelectionListener(new SelectionAdapter() { ! @Override ! public void widgetSelected(SelectionEvent e) { ! int selectionIndex = argumentsTable.getSelectionIndex(); ! if (argumentsTable.getSelectionCount() == 1 && selectionIndex > 0) { ! TableItem item = argumentsTable.getSelection()[0]; ! if (item instanceof SimpleTableItem) { ! SimpleTableItem tableItem = (SimpleTableItem) item; ! new SimpleTableItem(argumentsTable, tableItem.getOriginalName(), tableItem.getText(), selectionIndex - 1); ! argumentsTable.remove(selectionIndex + 1); ! argumentsTable.setSelection(selectionIndex - 1); ! argumentsTable.notifyListeners(SWT.Selection, new Event()); ! page.validate(); ! } ! } ! } ! }); ! } ! private Composite createArgumentsTable(Composite parent) { ! final Composite argumentsComposite = new Composite(parent, SWT.NONE); ! FormLayout compositeLayout = new FormLayout(); ! GridData compositeLData = new GridData(GridData.FILL_BOTH); ! argumentsComposite.setLayoutData(compositeLData); ! argumentsComposite.setLayout(compositeLayout); ! argumentsTable = new Table(argumentsComposite, SWT.BORDER | SWT.FULL_SELECTION); ! FormData tableLData = new FormData(); ! tableLData.bottom = new FormAttachment(1000, 1000, 0); ! tableLData.left = new FormAttachment(0, 1000, 0); ! tableLData.right = new FormAttachment(1000, 1000, -80); ! tableLData.top = new FormAttachment(0, 1000, 4); ! argumentsTable.setLayoutData(tableLData); ! argumentsTable.setHeaderVisible(true); ! argumentsTable.setLinesVisible(true); ! nameColumn = new TableColumn(argumentsTable, SWT.NONE); ! nameColumn.setText(Messages.extractMethodArgumentName); ! createArgumentsButton(argumentsComposite); ! argumentsComposite.addControlListener(new ControlAdapter() { ! public void controlResized(ControlEvent e) { ! Rectangle area = argumentsTable.getClientArea(); ! Point preferredSize = argumentsTable.computeSize(SWT.DEFAULT, SWT.DEFAULT); ! int width = area.width - 2 * argumentsTable.getBorderWidth(); ! if (preferredSize.y > area.height + argumentsTable.getHeaderHeight()) { ! Point vBarSize = argumentsTable.getVerticalBar().getSize(); ! width -= vBarSize.x; ! } ! Point oldSize = argumentsTable.getSize(); ! if (oldSize.x > area.width) { ! nameColumn.setWidth(width); ! argumentsTable.setSize(area.width, area.height); ! } else { ! argumentsTable.setSize(area.width, area.height); ! nameColumn.setWidth(width); ! } ! } ! }); ! argumentsComposite.notifyListeners(SWT.CONTROL, new Event()); ! return argumentsComposite; ! } ! private void createArgumentsLabel(Composite ArgumentsComposite) { ! argumentsLabel = new Label(ArgumentsComposite, SWT.NONE); ! GridData labelLData = new GridData(); ! labelLData.grabExcessHorizontalSpace = true; ! labelLData.horizontalAlignment = GridData.FILL; ! argumentsLabel.setLayoutData(labelLData); ! argumentsLabel.setText(Messages.extractMethodArgumentsTitle); ! } ! private void createFunctionName(Composite control) { ! Composite methodNameComposite = new Composite(control, SWT.NONE); ! FillLayout compositeLayout = new FillLayout(SWT.HORIZONTAL); ! GridData gridData = new GridData(); ! gridData.horizontalAlignment = GridData.FILL; ! methodNameComposite.setLayoutData(gridData); ! methodNameComposite.setLayout(compositeLayout); ! functionNameEdit = new LabeledEdit(methodNameComposite, Messages.extractMethodFunctionTitle); ! } ! private void createOffsetStrategy(Composite mainComp) { ! FillLayout fillLayout = new FillLayout(); ! fillLayout.type = org.eclipse.swt.SWT.VERTICAL; ! GridData gridData7 = new GridData(); ! gridData7.horizontalSpan = 2; ! gridData7.verticalAlignment = GridData.CENTER; ! gridData7.grabExcessHorizontalSpace = true; ! gridData7.horizontalAlignment = GridData.FILL; ! Composite comboComp = new Composite(mainComp, SWT.NONE); ! comboComp.setLayoutData(gridData7); ! comboComp.setLayout(fillLayout); ! methodInsertionLbl = new CLabel(comboComp, SWT.NONE); ! methodInsertionLbl.setText(Messages.offsetStrategyInsertionPointMethod); ! methodInsertionComb = createComboViewer(comboComp); ! methodInsertionComb.getCombo().select(0); ! } ! private ComboViewer createComboViewer(Composite comboComp) { ! ComboViewer v = new ComboViewer(comboComp); ! v.setContentProvider(this.strategyProvider); ! v.setLabelProvider(new LabelProvider()); ! v.setInput(""); ! return v; ! } ! public LabeledEdit getFunctionNameEdit() { ! return this.functionNameEdit; ! } ! public Label getSignaturePreview() { ! return this.functionPreviewLabel; ! } ! public Table getArgumentsTable() { ! return this.argumentsTable; ! } ! public Button getUpButton() { ! return this.upArgumentsButton; ! } ! public Button getDownButton() { ! return this.downArgumentsButton; ! } ! public Button getEditButton() { ! return this.editArgumentsButton; ! } ! public void registerListeners(final IValidationPage page) { ! signatureListener = new FunctionSignatureListener(page, getSignaturePreview(), getFunctionNameEdit(), getArgumentsTable()); ! functionNameEdit.getEdit().addListener(SWT.Modify, page); ! functionNameEdit.getEdit().addListener(SWT.Modify, signatureListener); ! ButtonActivationListener buttonActivationListener = new ButtonActivationListener(getArgumentsTable(), getUpButton(), ! getDownButton(), getEditButton()); ! if (argumentsTable != null) { ! cellEditorListener = new TableCellEditorListener(page, argumentsTable); ! argumentsTable.addListener(SWT.MouseDoubleClick, cellEditorListener); ! argumentsTable.addListener(SWT.DefaultSelection, cellEditorListener); ! argumentsTable.addListener(SWT.Selection, buttonActivationListener); ! argumentsTable.addListener(SWT.Selection, signatureListener); ! editArgumentsButton.addListener(SWT.Selection, cellEditorListener); ! registerUpButtonListener(); ! registerDownButtonListener(); ! } ! methodInsertionComb.addSelectionChangedListener(new ISelectionChangedListener() { ! public void selectionChanged(SelectionChangedEvent event) { ! IStructuredSelection sel = (IStructuredSelection) event.getSelection(); ! if (!sel.isEmpty()) { ! page.validate(); ! } ! } ! }); ! } ! public void initTable(List<String> arguments) { ! for (String argument : arguments) { ! new SimpleTableItem(getArgumentsTable(), argument); ! } ! } ! public Composite getArgumentsComposite() { ! return argumentsComposite; ! } ! public String getFunctionName() { ! return getFunctionNameEdit().getEdit().getText(); ! } ! public int getOffsetStrategy() { ! IStructuredSelection sel = (IStructuredSelection) methodInsertionComb.getSelection(); ! if (!sel.isEmpty()) { ! OffsetStrategyModel elem = (OffsetStrategyModel) sel.getFirstElement(); ! return elem.getStrategy(); ! } ! return strategyProvider.get(0).getStrategy(); ! } ! public boolean validate() { ! if (argumentsTable != null) { ! VariableCellValidator cellValidator = new VariableCellValidator(this.page, getArgumentsTable(), scopeAdapter); ! cellValidator.validate(); ! } ! NameValidator nameValidator = new NameValidator(scopeAdapter); ! try { ! nameValidator.validateMethodName(getFunctionName()); ! nameValidator.validateUniqueFunction(getFunctionName()); ! } catch (Throwable e) { ! page.setErrorMessage(e.getMessage()); ! } ! return page.getErrorMessage() == null; ! } } --- 53,438 ---- public class ExtractMethodComposite extends Composite { ! private Label functionPreviewLabel; ! private Label functionSignatureLabel; ! private Label argumentsLabel; ! private Button editArgumentsButton; ! private TableColumn nameColumn; ! private Table argumentsTable; ! private Button downArgumentsButton; ! private Button upArgumentsButton; ! private LabeledEdit functionNameEdit; ! private TableCellEditorListener cellEditorListener; ! private AbstractScopeNode<?> scopeAdapter; ! private IValidationPage page; ! private FunctionSignatureListener signatureListener; ! private OffsetStrategyProvider strategyProvider; ! private ComboViewer methodInsertionComb; ! private CLabel methodInsertionLbl; ! private Composite argumentsComposite; ! public ExtractMethodComposite(IValidationPage page, Composite parent, boolean hasArguments, AbstractScopeNode<?> scope) { ! super(parent, SWT.NONE); ! this.page = page; ! this.scopeAdapter = scope; ! this.strategyProvider = new OffsetStrategyProvider(scopeAdapter, IOffsetStrategy.AFTERINIT | IOffsetStrategy.BEGIN ! | IOffsetStrategy.END); ! createComposite(hasArguments); ! } ! public void createComposite(boolean hasArguments) { ! setLayout(new GridLayout()); ! createFunctionName(this); ! if (hasArguments) { ! createArguments(this); ! } ! createOffsetStrategy(this); ! createFunctionSignature(this); ! pack(); ! } ! private void createFunctionSignature(Composite control) { ! Composite functionSignatureComposite = new Composite(control, SWT.NONE); ! GridLayout compositeLayout = new GridLayout(); ! compositeLayout.makeColumnsEqualWidth = true; ! GridData compositeLData = new GridData(); ! compositeLData.horizontalAlignment = GridData.FILL; ! compositeLData.grabExcessHorizontalSpace = true; ! functionSignatureComposite.setLayoutData(compositeLData); ! functionSignatureComposite.setLayout(compositeLayout); ! functionSignatureLabel = new Label(functionSignatureComposite, SWT.NONE); ! GridData labelLData = new GridData(); ! labelLData.horizontalAlignment = GridData.FILL; ! labelLData.grabExcessHorizontalSpace = true; ! functionSignatureLabel.setLayoutData(labelLData); ! functionSignatureLabel.setText(Messages.extractMethodFunctionPreview); ! functionPreviewLabel = new Label(functionSignatureComposite, SWT.NONE); ! GridData functionSignaturePreviewData = new GridData(); ! functionSignaturePreviewData.horizontalAlignment = GridData.FILL; ! functionSignaturePreviewData.grabExcessHorizontalSpace = true; ! functionSignaturePreviewData.verticalAlignment = GridData.FILL; ! functionSignaturePreviewData.grabExcessVerticalSpace = true; ! functionPreviewLabel.setLayoutData(functionSignaturePreviewData); ! functionPreviewLabel.setText(""); ! } ! private Button createButton(Composite parent, String name) { ! Button button = new Button(parent, SWT.PUSH | SWT.CENTER); ! GridData buttonLData = new GridData(); ! buttonLData.horizontalAlignment = GridData.FILL; ! buttonLData.grabExcessHorizontalSpace = true; ! button.setLayoutData(buttonLData); ! button.setText(name); ! return button; ! } ! private void createArguments(Composite control) { ! argumentsComposite = new Composite(control, SWT.NONE); ! GridLayout compositeLayout = new GridLayout(); ! compositeLayout.makeColumnsEqualWidth = true; ! GridData compositeLData = new GridData(); ! compositeLData.grabExcessHorizontalSpace = true; ! compositeLData.horizontalAlignment = GridData.FILL; ! compositeLData.grabExcessVerticalSpace = true; ! compositeLData.verticalAlignment = GridData.FILL; ! argumentsComposite.setLayoutData(compositeLData); ! argumentsComposite.setLayout(compositeLayout); ! createArgumentsLabel(argumentsComposite); ! createArgumentsTable(argumentsComposite); ! } ! private void createArgumentsButton(Composite ArgumentsTableComposite) { ! Composite argumentsButtonComposite = new Composite(ArgumentsTableComposite, SWT.NONE); ! GridLayout compositeLayout = new GridLayout(); ! compositeLayout.makeColumnsEqualWidth = true; ! FormData compositeLData = new FormData(0, 0); ! compositeLData.width = 80; ! compositeLData.bottom = new FormAttachment(1000, 1000, 0); ! compositeLData.right = new FormAttachment(1000, 1000, 0); ! compositeLData.top = new FormAttachment(0, 1000, 0); ! argumentsButtonComposite.setLayoutData(compositeLData); ! argumentsButtonComposite.setLayout(compositeLayout); ! editArgumentsButton = createButton(argumentsButtonComposite, Messages.extractMethodEditButton); ! editArgumentsButton.setEnabled(false); ! upArgumentsButton = createButton(argumentsButtonComposite, Messages.extractMethodUpButton); ! upArgumentsButton.setEnabled(false); ! downArgumentsButton = createButton(argumentsButtonComposite, Messages.extractMethodDownButton); ! downArgumentsButton.setEnabled(false); ! } ! private void registerDownButtonListener() { ! downArgumentsButton.addSelectionListener(new SelectionAdapter() { ! @Override ! public void widgetSelected(SelectionEvent e) { ! int selectionIndex = argumentsTable.getSelectionIndex(); ! if (argumentsTable.getSelectionCount() == 1 && selectionIndex != argumentsTable.getItemCount()) { ! TableItem item = argumentsTable.getSelection()[0]; ! if (item instanceof SimpleTableItem) { ! SimpleTableItem tableItem = (SimpleTableItem) item; ! new SimpleTableItem(argumentsTable, tableItem.getOriginalName(), tableItem.getText(), selectionIndex + 2); ! argumentsTable.remove(selectionIndex); ! argumentsTable.setSelection(selectionIndex + 1); ! argumentsTable.notifyListeners(SWT.Selection, new Event()); ! page.validate(); ! } ! } ! } ! }); ! } ! private void registerUpButtonListener() { ! upArgumentsButton.addSelectionListener(new SelectionAdapter() { ! @Override ! public void widgetSelected(SelectionEvent e) { ! int selectionIndex = argumentsTable.getSelectionIndex(); ! if (argumentsTable.getSelectionCount() == 1 && selectionIndex > 0) { ! TableItem item = argumentsTable.getSelection()[0]; ! if (item instanceof SimpleTableItem) { ! SimpleTableItem tableItem = (SimpleTableItem) item; ! new SimpleTableItem(argumentsTable, tableItem.getOriginalName(), tableItem.getText(), selectionIndex - 1); ! argumentsTable.remove(selectionIndex + 1); ! argumentsTable.setSelection(selectionIndex - 1); ! argumentsTable.notifyListeners(SWT.Selection, new Event()); ! page.validate(); ! } ! } ! } ! }); ! } ! private Composite createArgumentsTable(Composite parent) { ! final Composite argumentsComposite = new Composite(parent, SWT.NONE); ! FormLayout compositeLayout = new FormLayout(); ! GridData compositeLData = new GridData(GridData.FILL_BOTH); ! argumentsComposite.setLayoutData(compositeLData); ! argumentsComposite.setLayout(compositeLayout); ! argumentsTable = new Table(argumentsComposite, SWT.BORDER | SWT.FULL_SELECTION); ! FormData tableLData = new FormData(); ! tableLData.bottom = new FormAttachment(1000, 1000, 0); ! tableLData.left = new FormAttachment(0, 1000, 0); ! tableLData.right = new FormAttachment(1000, 1000, -80); ! tableLData.top = new FormAttachment(0, 1000, 4); ! argumentsTable.setLayoutData(tableLData); ! argumentsTable.setHeaderVisible(true); ! argumentsTable.setLinesVisible(true); ! nameColumn = new TableColumn(argumentsTable, SWT.NONE); ! nameColumn.setText(Messages.extractMethodArgumentName); ! createArgumentsButton(argumentsComposite); ! argumentsComposite.addControlListener(new ControlAdapter() { ! public void controlResized(ControlEvent e) { ! Rectangle area = argumentsTable.getClientArea(); ! Point preferredSize = argumentsTable.computeSize(SWT.DEFAULT, SWT.DEFAULT); ! int width = area.width - 2 * argumentsTable.getBorderWidth(); ! if (preferredSize.y > area.height + argumentsTable.getHeaderHeight()) { ! Point vBarSize = argumentsTable.getVerticalBar().getSize(); ! width -= vBarSize.x; ! } ! Point oldSize = argumentsTable.getSize(); ! if (oldSize.x > area.width) { ! nameColumn.setWidth(width); ! argumentsTable.setSize(area.width, area.height); ! } else { ! argumentsTable.setSize(area.width, area.height); ! nameColumn.setWidth(width); ! } ! } ! }); ! argumentsComposite.notifyListeners(SWT.CONTROL, new Event()); ! return argumentsComposite; ! } ! private void createArgumentsLabel(Composite ArgumentsComposite) { ! argumentsLabel = new Label(ArgumentsComposite, SWT.NONE); ! GridData labelLData = new GridData(); ! labelLData.grabExcessHorizontalSpace = true; ! labelLData.horizontalAlignment = GridData.FILL; ! argumentsLabel.setLayoutData(labelLData); ! argumentsLabel.setText(Messages.extractMethodArgumentsTitle); ! } ! private void createFunctionName(Composite control) { ! Composite methodNameComposite = new Composite(control, SWT.NONE); ! FillLayout compositeLayout = new FillLayout(SWT.HORIZONTAL); ! GridData gridData = new GridData(); ! gridData.horizontalAlignment = GridData.FILL; ! methodNameComposite.setLayoutData(gridData); ! methodNameComposite.setLayout(compositeLayout); ! functionNameEdit = new LabeledEdit(methodNameComposite, Messages.extractMethodFunctionTitle); ! } ! private void createOffsetStrategy(Composite mainComp) { ! FillLayout fillLayout = new FillLayout(); ! fillLayout.type = org.eclipse.swt.SWT.VERTICAL; ! GridData gridData7 = new GridData(); ! gridData7.horizontalSpan = 2; ! gridData7.verticalAlignment = GridData.CENTER; ! gridData7.grabExcessHorizontalSpace = true; ! gridData7.horizontalAlignment = GridData.FILL; ! Composite comboComp = new Composite(mainComp, SWT.NONE); ! comboComp.setLayoutData(gridData7); ! comboComp.setLayout(fillLayout); ! methodInsertionLbl = new CLabel(comboComp, SWT.NONE); ! methodInsertionLbl.setText(Messages.offsetStrategyInsertionPointMethod); ! methodInsertionComb = createComboViewer(comboComp); ! methodInsertionComb.getCombo().select(0); ! } ! private ComboViewer createComboViewer(Composite comboComp) { ! ComboViewer v = new ComboViewer(comboComp); ! v.setContentProvider(this.strategyProvider); ! v.setLabelProvider(new LabelProvider()); ! v.setInput(""); ! return v; ! } ! public LabeledEdit getFunctionNameEdit() { ! return this.functionNameEdit; ! } ! public Label getSignaturePreview() { ! return this.functionPreviewLabel; ! } ! public Table getArgumentsTable() { ! return this.argumentsTable; ! } ! public Button getUpButton() { ! return this.upArgumentsButton; ! } ! public Button getDownButton() { ! return this.downArgumentsButton; ! } ! public Button getEditButton() { ! return this.editArgumentsButton; ! } ! public void registerListeners(final IValidationPage page) { ! signatureListener = new FunctionSignatureListener(page, getSignaturePreview(), getFunctionNameEdit(), getArgumentsTable()); ! functionNameEdit.getEdit().addListener(SWT.Modify, page); ! functionNameEdit.getEdit().addListener(SWT.Modify, signatureListener); ! ButtonActivationListener buttonActivationListener = new ButtonActivationListener(getArgumentsTable(), getUpButton(), ! getDownButton(), getEditButton()); ! if (argumentsTable != null) { ! cellEditorListener = new TableCellEditorListener(page, argumentsTable); ! argumentsTable.addListener(SWT.MouseDoubleClick, cellEditorListener); ! argumentsTable.addListener(SWT.DefaultSelection, cellEditorListener); ! argumentsTable.addListener(SWT.Selection, buttonActivationListener); ! argumentsTable.addListener(SWT.Selection, signatureListener); ! editArgumentsButton.addListener(SWT.Selection, cellEditorListener); ! registerUpButtonListener(); ! registerDownButtonListener(); ! } ! methodInsertionComb.addSelectionChangedListener(new ISelectionChangedListener() { ! public void selectionChanged(SelectionChangedEvent event) { ! IStructuredSelection sel = (IStructuredSelection) event.getSelection(); ! if (!sel.isEmpty()) { ! page.validate(); ! } ! } ! }); ! } ! public void initTable(List<String> arguments) { ! for (String argument : arguments) { ! new SimpleTableItem(getArgumentsTable(), argument); ! } ! } ! public Composite getArgumentsComposite() { ! return argumentsComposite; ! } ! public String getFunctionName() { ! return getFunctionNameEdit().getEdit().getText(); ! } ! public int getOffsetStrategy() { ! IStructuredSelection sel = (IStructuredSelection) methodInsertionComb.getSelection(); ! if (!sel.isEmpty()) { ! OffsetStrategyModel elem = (OffsetStrategyModel) sel.getFirstElement(); ! return elem.getStrategy(); ! } ! return strategyProvider.get(0).getStrategy(); ! } ! public boolean validate() { ! if (argumentsTable != null) { ! VariableCellValidator cellValidator = new VariableCellValidator(this.page, getArgumentsTable(), scopeAdapter); ! cellValidator.validate(); ! } ! NameValidator nameValidator = new NameValidator(scopeAdapter); ! try { ! nameValidator.validateMethodName(getFunctionName()); ! nameValidator.validateUniqueFunction(getFunctionName()); ! } catch (Throwable e) { ! page.setErrorMessage(e.getMessage()); ! } ! return page.getErrorMessage() == null; ! } } Index: ExtractMethodPage.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/ui/pages/extractmethod/ExtractMethodPage.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** ExtractMethodPage.java 20 Oct 2007 19:31:05 -0000 1.1 --- ExtractMethodPage.java 27 Sep 2008 20:00:47 -0000 1.2 *************** *** 22,98 **** public class ExtractMethodPage extends PyDevInputWizardPage { ! private ExtractMethodRequestProcessor requestProcessor; ! private ExtractMethodComposite extractComposite; ! private Composite parent; ! public ExtractMethodPage(String name, ExtractMethodRequestProcessor requestProcessor) { ! super(name); ! this.setTitle(name); ! this.requestProcessor = requestProcessor; ! } ! public void createControl(Composite parent) { ! this.parent = parent; ! setupComposite(); ! } ! public void setupComposite() { ! if (extractComposite != null) { ! extractComposite.dispose(); ! extractComposite = null; ! } ! boolean hasArguments = this.requestProcessor.getDeducer().getParameters().size() > 0; ! extractComposite = new ExtractMethodComposite(this, parent, hasArguments, requestProcessor.getScopeAdapter()); ! extractComposite.registerListeners(this); ! updateArgumentTable(); ! setControl(this.extractComposite); ! voodooResizeToPage(); ! setPageComplete(false); ! } ! public void updateArgumentTable() { ! if (extractComposite != null && extractComposite.getArgumentsTable() != null) { ! extractComposite.initTable(requestProcessor.getDeducer().getParameters()); ! } ! } ! @Override ! public boolean canFlipToNextPage() { ! return isPageComplete(); ! } ! public void validate() { ! setErrorMessage(null); ! extractComposite.validate(); ! setPageComplete(getErrorMessage() == null); ! if (isPageComplete()) { ! applySettings(); ! } ! } ! private void applySettings() { ! this.requestProcessor.setMethodName(extractComposite.getFunctionName()); ! this.requestProcessor.setOffsetStrategy(extractComposite.getOffsetStrategy()); ! if (extractComposite.getArgumentsTable() != null) { ! List<String> parameterOrder = new ArrayList<String>(); ! Map<String, String> parameterMap = new HashMap<String, String>(); ! for (TableItem item : extractComposite.getArgumentsTable().getItems()) { ! if (item instanceof SimpleTableItem) { ! SimpleTableItem tableItem = (SimpleTableItem) item; ! parameterMap.put(tableItem.getOriginalName(), tableItem.getText()); ! parameterOrder.add(tableItem.getOriginalName()); ! } ! } ! requestProcessor.setParameterMap(parameterMap); ! requestProcessor.setParameterOrder(parameterOrder); ! } ! } ! public void handleEvent(Event event) { ! validate(); ! } } --- 22,98 ---- public class ExtractMethodPage extends PyDevInputWizardPage { ! private ExtractMethodRequestProcessor requestProcessor; ! private ExtractMethodComposite extractComposite; ! private Composite parent; ! public ExtractMethodPage(String name, ExtractMethodRequestProcessor requestProcessor) { ! super(name); ! this.setTitle(name); ! this.requestProcessor = requestProcessor; ! } ! public void createControl(Composite parent) { ! this.parent = parent; ! setupComposite(); ! } ! public void setupComposite() { ! if (extractComposite != null) { ! extractComposite.dispose(); ! extractComposite = null; ! } ! boolean hasArguments = this.requestProcessor.getDeducer().getParameters().size() > 0; ! extractComposite = new ExtractMethodComposite(this, parent, hasArguments, requestProcessor.getScopeAdapter()); ! extractComposite.registerListeners(this); ! updateArgumentTable(); ! setControl(this.extractComposite); ! voodooResizeToPage(); ! setPageComplete(false); ! } ! public void updateArgumentTable() { ! if (extractComposite != null && extractComposite.getArgumentsTable() != null) { ! extractComposite.initTable(requestProcessor.getDeducer().getParameters()); ! } ! } ! @Override ! public boolean canFlipToNextPage() { ! return isPageComplete(); ! } ! public void validate() { ! setErrorMessage(null); ! extractComposite.validate(); ! setPageComplete(getErrorMessage() == null); ! if (isPageComplete()) { ! applySettings(); ! } ! } ! private void applySettings() { ! this.requestProcessor.setMethodName(extractComposite.getFunctionName()); ! this.requestProcessor.setOffsetStrategy(extractComposite.getOffsetStrategy()); ! if (extractComposite.getArgumentsTable() != null) { ! List<String> parameterOrder = new ArrayList<String>(); ! Map<String, String> parameterMap = new HashMap<String, String>(); ! for (TableItem item : extractComposite.getArgumentsTable().getItems()) { ! if (item instanceof SimpleTableItem) { ! SimpleTableItem tableItem = (SimpleTableItem) item; ! parameterMap.put(tableItem.getOriginalName(), tableItem.getText()); ! parameterOrder.add(tableItem.getOriginalName()); ! } ! } ! requestProcessor.setParameterMap(parameterMap); ! requestProcessor.setParameterOrder(parameterOrder); ! } ! } ! public void handleEvent(Event event) { ! validate(); ! } } |
Update of /cvsroot/pydev/org.python.pydev.refactoring/contrib/ch/hsr/ukistler/astgraph In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv21605/contrib/ch/hsr/ukistler/astgraph Modified Files: GraphVisitor.java ASTGraph.java GraphView.java GraphPrinter.java ImageWriter.java Log Message: Synching to latest changes: Pydev <ul> <li><strong>Editor</strong>: Cursor settings no longer overridden</li> <li><strong>Code-completion</strong>: If __all__ is defined with runtime elements (and not only in a single assign statement), it's ignored for code-completion purposes</li> <li><strong>Debugger</strong>: Pythonpath the same in debug and regular modes (sys.path[0] is the same directory as the file run)</li> <li><strong>Debugger</strong>: Persist choices done in the debugger when files from the debugger are not found</li> <li><strong>Interpreter config</strong>: "email" automatically added to the "forced builtins"</li> <li><strong>Parser</strong>: Correctly recognizing absolute import with 3 or more levels</li> <li><strong>Syntax check</strong>: Option to do only on active editor</li> </ul> Also: tabs changed for spaces Index: GraphVisitor.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/contrib/ch/hsr/ukistler/astgraph/GraphVisitor.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** GraphVisitor.java 20 Oct 2007 19:31:04 -0000 1.3 --- GraphVisitor.java 27 Sep 2008 20:00:48 -0000 1.4 *************** *** 30,152 **** public class GraphVisitor extends VisitorBase { ! private static final int DEPTH_STEP = 30; ! private static final int INDENT_STEP = 40; ! private Color nodeColor; ! private List<DefaultGraphCell> cells; ! private FastStack<DefaultGraphCell> stack; ! int depth; ! int indent; ! public GraphVisitor() throws IOException { ! cells = new ArrayList<DefaultGraphCell>(); ! stack = new FastStack<DefaultGraphCell>(); ! depth = 0; ! indent = 0; ! nodeColor = Color.GRAY; ! } ! private DefaultEdge createConnection(DefaultGraphCell cell) { ! DefaultEdge edge = new DefaultEdge(); ! edge.setSource(stack.peek().getChildAt(0)); ! edge.setTarget(cell); ! // Set Arrow Style for edge ! int arrow = GraphConstants.ARROW_TECHNICAL; ! GraphConstants.setLineEnd(edge.getAttributes(), arrow); ! GraphConstants.setEndFill(edge.getAttributes(), true); ! return edge; ! } ! public DefaultGraphCell createVertex(String name, double x, double y, Color bg, boolean raised) { ! // Create vertex with the given name ! DefaultGraphCell cell = new DefaultGraphCell(name); ! GraphConstants.setBorder(cell.getAttributes(), BorderFactory.createEtchedBorder()); ! GraphConstants.setBounds(cell.getAttributes(), new Rectangle2D.Double(x, y, 10, 10)); ! GraphConstants.setResize(cell.getAttributes(), true); ! GraphConstants.setAutoSize(cell.getAttributes(), true); ! // Set fill color ! if (bg != null) { ! GraphConstants.setOpaque(cell.getAttributes(), true); ! GraphConstants.setGradientColor(cell.getAttributes(), bg); ! } ! // Set raised border ! if (raised) ! GraphConstants.setBorder(cell.getAttributes(), BorderFactory.createRaisedBevelBorder()); ! else ! // Set black border ! GraphConstants.setBorderColor(cell.getAttributes(), Color.black); ! return cell; ! } ! private void decrementPosition() { ! stack.pop(); ! indent -= INDENT_STEP; ! } ! public DefaultGraphCell[] getCells() { ! return cells.toArray(new DefaultGraphCell[0]); ! } ! private void incrementPosition(DefaultGraphCell cell) { ! stack.push(cell); ! indent += INDENT_STEP; ! depth += DEPTH_STEP; ! } ! private void parentAddPort() { ! Point2D point = new Point2D.Double(0, GraphConstants.PERMILLE); ! stack.peek().addPort(point); ! } ! @Override ! public void traverse(SimpleNode node) throws Exception { ! node.traverse(this); ! decrementPosition(); ! } ! @Override ! protected Object unhandled_node(SimpleNode node) throws Exception { ! DefaultGraphCell cell = null; ! String caption = node.toString(); ! parentAddPort(); ! cell = createVertex(caption, indent, depth, nodeColor, false); ! DefaultEdge edge = createConnection(cell); ! cells.add(cell); ! cells.add(edge); ! incrementPosition(cell); ! return null; ! } ! /** ! * Entry point ! */ ! @Override ! public Object visitModule(Module node) throws Exception { ! // String caption = node.toString(); ! DefaultGraphCell moduleCell = createVertex("Module", indent, depth, nodeColor, false); ! cells.add(moduleCell); ! incrementPosition(moduleCell); ! traverse(node); ! return null; ! } } --- 30,152 ---- public class GraphVisitor extends VisitorBase { ! private static final int DEPTH_STEP = 30; ! private static final int INDENT_STEP = 40; ! private Color nodeColor; ! private List<DefaultGraphCell> cells; ! private FastStack<DefaultGraphCell> stack; ! int depth; ! int indent; ! public GraphVisitor() throws IOException { ! cells = new ArrayList<DefaultGraphCell>(); ! stack = new FastStack<DefaultGraphCell>(); ! depth = 0; ! indent = 0; ! nodeColor = Color.GRAY; ! } ! private DefaultEdge createConnection(DefaultGraphCell cell) { ! DefaultEdge edge = new DefaultEdge(); ! edge.setSource(stack.peek().getChildAt(0)); ! edge.setTarget(cell); ! // Set Arrow Style for edge ! int arrow = GraphConstants.ARROW_TECHNICAL; ! GraphConstants.setLineEnd(edge.getAttributes(), arrow); ! GraphConstants.setEndFill(edge.getAttributes(), true); ! return edge; ! } ! public DefaultGraphCell createVertex(String name, double x, double y, Color bg, boolean raised) { ! // Create vertex with the given name ! DefaultGraphCell cell = new DefaultGraphCell(name); ! GraphConstants.setBorder(cell.getAttributes(), BorderFactory.createEtchedBorder()); ! GraphConstants.setBounds(cell.getAttributes(), new Rectangle2D.Double(x, y, 10, 10)); ! GraphConstants.setResize(cell.getAttributes(), true); ! GraphConstants.setAutoSize(cell.getAttributes(), true); ! // Set fill color ! if (bg != null) { ! GraphConstants.setOpaque(cell.getAttributes(), true); ! GraphConstants.setGradientColor(cell.getAttributes(), bg); ! } ! // Set raised border ! if (raised) ! GraphConstants.setBorder(cell.getAttributes(), BorderFactory.createRaisedBevelBorder()); ! else ! // Set black border ! GraphConstants.setBorderColor(cell.getAttributes(), Color.black); ! return cell; ! } ! private void decrementPosition() { ! stack.pop(); ! indent -= INDENT_STEP; ! } ! public DefaultGraphCell[] getCells() { ! return cells.toArray(new DefaultGraphCell[0]); ! } ! private void incrementPosition(DefaultGraphCell cell) { ! stack.push(cell); ! indent += INDENT_STEP; ! depth += DEPTH_STEP; ! } ! private void parentAddPort() { ! Point2D point = new Point2D.Double(0, GraphConstants.PERMILLE); ! stack.peek().addPort(point); ! } ! @Override ! public void traverse(SimpleNode node) throws Exception { ! node.traverse(this); ! decrementPosition(); ! } ! @Override ! protected Object unhandled_node(SimpleNode node) throws Exception { ! DefaultGraphCell cell = null; ! String caption = node.toString(); ! parentAddPort(); ! cell = createVertex(caption, indent, depth, nodeColor, false); ! DefaultEdge edge = createConnection(cell); ! cells.add(cell); ! cells.add(edge); ! incrementPosition(cell); ! return null; ! } ! /** ! * Entry point ! */ ! @Override ! public Object visitModule(Module node) throws Exception { ! // String caption = node.toString(); ! DefaultGraphCell moduleCell = createVertex("Module", indent, depth, nodeColor, false); ! cells.add(moduleCell); ! incrementPosition(moduleCell); ! traverse(node); ! return null; ! } } Index: ASTGraph.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/contrib/ch/hsr/ukistler/astgraph/ASTGraph.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** ASTGraph.java 20 Oct 2007 19:31:05 -0000 1.3 --- ASTGraph.java 27 Sep 2008 20:00:48 -0000 1.4 *************** *** 27,56 **** public class ASTGraph { ! public Tuple<SimpleNode, Throwable> parseFile(String fileName) throws FileNotFoundException, IOException, Throwable { ! File pythonSource = new File(fileName); ! BufferedReader in = new BufferedReader(new FileReader(pythonSource)); ! String line = ""; ! StringBuilder source = new StringBuilder(); ! while ((line = in.readLine()) != null) { ! source.append(line); ! source.append("\n"); ! } ! IDocument doc = new Document(source.toString()); ! Tuple<SimpleNode, Throwable> objects = PyParser.reparseDocument(new PyParser.ParserInfo(doc, false, ! IPythonNature.LATEST_GRAMMAR_VERSION)); ! if (objects.o2 != null) ! throw objects.o2; ! return objects; ! } ! public DefaultGraphCell[] generateTree(SimpleNode node) throws IOException, Exception { ! GraphVisitor visitor = new GraphVisitor(); ! node.accept(visitor); ! DefaultGraphCell[] cells = visitor.getCells(); ! return cells; ! } } --- 27,56 ---- public class ASTGraph { ! public Tuple<SimpleNode, Throwable> parseFile(String fileName) throws FileNotFoundException, IOException, Throwable { ! File pythonSource = new File(fileName); ! BufferedReader in = new BufferedReader(new FileReader(pythonSource)); ! String line = ""; ! StringBuilder source = new StringBuilder(); ! while ((line = in.readLine()) != null) { ! source.append(line); ! source.append("\n"); ! } ! IDocument doc = new Document(source.toString()); ! Tuple<SimpleNode, Throwable> objects = PyParser.reparseDocument(new PyParser.ParserInfo(doc, false, ! IPythonNature.LATEST_GRAMMAR_VERSION)); ! if (objects.o2 != null) ! throw objects.o2; ! return objects; ! } ! public DefaultGraphCell[] generateTree(SimpleNode node) throws IOException, Exception { ! GraphVisitor visitor = new GraphVisitor(); ! node.accept(visitor); ! DefaultGraphCell[] cells = visitor.getCells(); ! return cells; ! } } Index: ImageWriter.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/contrib/ch/hsr/ukistler/astgraph/ImageWriter.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** ImageWriter.java 20 Oct 2007 19:31:04 -0000 1.2 --- ImageWriter.java 27 Sep 2008 20:00:48 -0000 1.3 *************** *** 13,38 **** public class ImageWriter implements Runnable { ! private BufferedImage img; ! private String fileName; ! public ImageWriter(BufferedImage img, String fileName) throws Throwable { ! if (img == null) ! throw new Exception("Image cannot be retrieved"); ! this.img = img; ! this.fileName = fileName; ! } ! public void run() { ! FileOutputStream out; ! try { ! out = new FileOutputStream(new File(fileName)); ! ImageIO.write(img, "png", out); ! out.flush(); ! out.close(); ! } catch (Throwable e) { ! } ! } } --- 13,38 ---- public class ImageWriter implements Runnable { ! private BufferedImage img; ! private String fileName; ! public ImageWriter(BufferedImage img, String fileName) throws Throwable { ! if (img == null) ! throw new Exception("Image cannot be retrieved"); ! this.img = img; ! this.fileName = fileName; ! } ! public void run() { ! FileOutputStream out; ! try { ! out = new FileOutputStream(new File(fileName)); ! ImageIO.write(img, "png", out); ! out.flush(); ! out.close(); ! } catch (Throwable e) { ! } ! } } Index: GraphView.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/contrib/ch/hsr/ukistler/astgraph/GraphView.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** GraphView.java 20 Oct 2007 19:31:05 -0000 1.3 --- GraphView.java 27 Sep 2008 20:00:48 -0000 1.4 *************** *** 32,252 **** public class GraphView extends JFrame { ! /** ! * ! */ ! private static final long serialVersionUID = -3925214828169513991L; ! private JPanel boxPanel = null; ! private JFileChooser fc = null; ! private JGraph graph = null; ! private JScrollPane graphpane = null; ! private JPanel navPane = null; ! private JButton saveImage = null; ! private JButton loadPython = null; ! /** ! * This method initializes ! * ! */ ! public GraphView() { ! super("Python AST Viewer"); ! initialize(); ! } ! /** ! * This method initializes this ! * ! */ ! private void initialize() { ! this.fc = new JFileChooser(); ! this.setContentPane(getBoxPanel()); ! this.setSize(new Dimension(640, 480)); ! this.pack(); ! this.setExtendedState(javax.swing.JFrame.MAXIMIZED_BOTH); ! } ! /** ! * This method initializes boxPanel ! * ! * @return javax.swing.JPanel ! */ ! private JPanel getBoxPanel() { ! if (boxPanel == null) { ! boxPanel = new JPanel(); ! boxPanel.setLayout(new BorderLayout()); ! boxPanel.add(getNavPane(), BorderLayout.NORTH); ! boxPanel.add(getGraphpane(), BorderLayout.CENTER); ! } ! return boxPanel; ! } ! /** ! * This method initializes graphpane ! * ! * @return javax.swing.JScrollPane ! */ ! private JScrollPane getGraphpane() { ! if (graphpane == null) { ! graphpane = new JScrollPane(); ! this.graph = setupGraph(); ! graphpane.setViewportView(this.graph); ! } ! return graphpane; ! } ! /** ! * This method initializes navPane ! * ! * @return javax.swing.JPanel ! */ ! private JPanel getNavPane() { ! if (navPane == null) { ! navPane = new JPanel(); ! navPane.setLayout(new FlowLayout()); ! navPane.add(getSaveImage()); ! navPane.add(getLoadPython()); ! } ! return navPane; ! } ! /** ! * This method initializes saveImage ! * ! * @return javax.swing.JButton ! */ ! private JButton getSaveImage() { ! if (saveImage == null) { ! saveImage = new JButton(); ! saveImage.setText("Save as PNG"); ! saveImage.addActionListener(new java.awt.event.ActionListener() { ! public void actionPerformed(java.awt.event.ActionEvent event) { ! FileFilter filter = new PNGFilter(); ! try { ! fc.addChoosableFileFilter(filter); ! int returnVal = fc.showSaveDialog(GraphView.this); ! if (returnVal == JFileChooser.APPROVE_OPTION) { ! File file = fc.getSelectedFile(); ! createImage(file.getAbsolutePath()); ! } ! } finally { ! fc.removeChoosableFileFilter(filter); ! } ! } ! }); ! } ! return saveImage; ! } ! /** ! * This method initializes loadPython ! * ! * @return javax.swing.JButton ! */ ! private JButton getLoadPython() { ! if (loadPython == null) { ! loadPython = new JButton(); ! loadPython.setText("Load Python source"); ! loadPython.addActionListener(new java.awt.event.ActionListener() { ! public void actionPerformed(java.awt.event.ActionEvent event) { ! FileFilter filter = new PythonFilter(); ! try { ! fc.addChoosableFileFilter(filter); ! int returnVal = fc.showOpenDialog(GraphView.this); ! if (returnVal == JFileChooser.APPROVE_OPTION) { ! File file = fc.getSelectedFile(); ! loadGraph(file.getAbsolutePath()); ! } ! } catch (Throwable e) { ! JOptionPane msgbox = new JOptionPane("Error writing file: " + e.getMessage()); ! msgbox.setVisible(true); ! } finally { ! fc.removeChoosableFileFilter(filter); ! } ! } ! }); ! } ! return loadPython; ! } ! private JGraph setupGraph() { ! // Construct Model and Graph ! GraphModel model = new DefaultGraphModel(); ! JGraph graph = new JGraph(model); ! // Control-drag should clone selection ! graph.setCloneable(true); ! // Enable edit without final RETURN keystroke ! graph.setInvokesStopCellEditing(true); ! // When over a cell, jump to its default port (we only have one, anyway) ! graph.setJumpToDefaultPort(true); ! return graph; ! } ! private void loadGraph(String fileName) throws FileNotFoundException, IOException, Throwable { ! ASTGraph ast = new ASTGraph(); ! Tuple<SimpleNode, Throwable> objects = ast.parseFile(fileName); ! graph.setGraphLayoutCache(new GraphLayoutCache()); ! DefaultGraphCell[] cells = ast.generateTree(objects.o1); ! graph.getGraphLayoutCache().insert(cells); ! graph.clearSelection(); ! } ! private void createImage(String imageName) { ! if (graph == null) { ! return; ! } ! try { ! ImageWriter writer; ! writer = new ImageWriter(graph.getImage(null, GraphConstants.DEFAULTINSET), imageName); ! SwingUtilities.invokeLater(writer); ! } catch (Throwable e) { ! JOptionPane msgbox = new JOptionPane("Error writing file: " + e.getMessage()); ! msgbox.setVisible(true); ! } ! } ! class PNGFilter extends javax.swing.filechooser.FileFilter { ! public boolean accept(File file) { ! if (file.isDirectory()) ! return true; ! String filename = file.getName(); ! return filename.endsWith(".png"); ! } ! public String getDescription() { ! return "PNG image (*.png)"; ! } ! } ! class PythonFilter extends javax.swing.filechooser.FileFilter { ! public boolean accept(File file) { ! if (file.isDirectory()) ! return true; ! String filename = file.getName(); ! return filename.endsWith(".py"); ! } ! public String getDescription() { ! return "Python Source code (*.py)"; ! } ! } } // @jve:decl-index=0:visual-constraint="10,10" --- 32,252 ---- public class GraphView extends JFrame { ! /** ! * ! */ ! private static final long serialVersionUID = -3925214828169513991L; ! private JPanel boxPanel = null; ! private JFileChooser fc = null; ! private JGraph graph = null; ! private JScrollPane graphpane = null; ! private JPanel navPane = null; ! private JButton saveImage = null; ! private JButton loadPython = null; ! /** ! * This method initializes ! * ! */ ! public GraphView() { ! super("Python AST Viewer"); ! initialize(); ! } ! /** ! * This method initializes this ! * ! */ ! private void initialize() { ! this.fc = new JFileChooser(); ! this.setContentPane(getBoxPanel()); ! this.setSize(new Dimension(640, 480)); ! this.pack(); ! this.setExtendedState(javax.swing.JFrame.MAXIMIZED_BOTH); ! } ! /** ! * This method initializes boxPanel ! * ! * @return javax.swing.JPanel ! */ ! private JPanel getBoxPanel() { ! if (boxPanel == null) { ! boxPanel = new JPanel(); ! boxPanel.setLayout(new BorderLayout()); ! boxPanel.add(getNavPane(), BorderLayout.NORTH); ! boxPanel.add(getGraphpane(), BorderLayout.CENTER); ! } ! return boxPanel; ! } ! /** ! * This method initializes graphpane ! * ! * @return javax.swing.JScrollPane ! */ ! private JScrollPane getGraphpane() { ! if (graphpane == null) { ! graphpane = new JScrollPane(); ! this.graph = setupGraph(); ! graphpane.setViewportView(this.graph); ! } ! return graphpane; ! } ! /** ! * This method initializes navPane ! * ! * @return javax.swing.JPanel ! */ ! private JPanel getNavPane() { ! if (navPane == null) { ! navPane = new JPanel(); ! navPane.setLayout(new FlowLayout()); ! navPane.add(getSaveImage()); ! navPane.add(getLoadPython()); ! } ! return navPane; ! } ! /** ! * This method initializes saveImage ! * ! * @return javax.swing.JButton ! */ ! private JButton getSaveImage() { ! if (saveImage == null) { ! saveImage = new JButton(); ! saveImage.setText("Save as PNG"); ! saveImage.addActionListener(new java.awt.event.ActionListener() { ! public void actionPerformed(java.awt.event.ActionEvent event) { ! FileFilter filter = new PNGFilter(); ! try { ! fc.addChoosableFileFilter(filter); ! int returnVal = fc.showSaveDialog(GraphView.this); ! if (returnVal == JFileChooser.APPROVE_OPTION) { ! File file = fc.getSelectedFile(); ! createImage(file.getAbsolutePath()); ! } ! } finally { ! fc.removeChoosableFileFilter(filter); ! } ! } ! }); ! } ! return saveImage; ! } ! /** ! * This method initializes loadPython ! * ! * @return javax.swing.JButton ! */ ! private JButton getLoadPython() { ! if (loadPython == null) { ! loadPython = new JButton(); ! loadPython.setText("Load Python source"); ! loadPython.addActionListener(new java.awt.event.ActionListener() { ! public void actionPerformed(java.awt.event.ActionEvent event) { ! FileFilter filter = new PythonFilter(); ! try { ! fc.addChoosableFileFilter(filter); ! int returnVal = fc.showOpenDialog(GraphView.this); ! if (returnVal == JFileChooser.APPROVE_OPTION) { ! File file = fc.getSelectedFile(); ! loadGraph(file.getAbsolutePath()); ! } ! } catch (Throwable e) { ! JOptionPane msgbox = new JOptionPane("Error writing file: " + e.getMessage()); ! msgbox.setVisible(true); ! } finally { ! fc.removeChoosableFileFilter(filter); ! } ! } ! }); ! } ! return loadPython; ! } ! private JGraph setupGraph() { ! // Construct Model and Graph ! GraphModel model = new DefaultGraphModel(); ! JGraph graph = new JGraph(model); ! // Control-drag should clone selection ! graph.setCloneable(true); ! // Enable edit without final RETURN keystroke ! graph.setInvokesStopCellEditing(true); ! // When over a cell, jump to its default port (we only have one, anyway) ! graph.setJumpToDefaultPort(true); ! return graph; ! } ! private void loadGraph(String fileName) throws FileNotFoundException, IOException, Throwable { ! ASTGraph ast = new ASTGraph(); ! Tuple<SimpleNode, Throwable> objects = ast.parseFile(fileName); ! graph.setGraphLayoutCache(new GraphLayoutCache()); ! DefaultGraphCell[] cells = ast.generateTree(objects.o1); ! graph.getGraphLayoutCache().insert(cells); ! graph.clearSelection(); ! } ! private void createImage(String imageName) { ! if (graph == null) { ! return; ! } ! try { ! ImageWriter writer; ! writer = new ImageWriter(graph.getImage(null, GraphConstants.DEFAULTINSET), imageName); ! SwingUtilities.invokeLater(writer); ! } catch (Throwable e) { ! JOptionPane msgbox = new JOptionPane("Error writing file: " + e.getMessage()); ! msgbox.setVisible(true); ! } ! } ! class PNGFilter extends javax.swing.filechooser.FileFilter { ! public boolean accept(File file) { ! if (file.isDirectory()) ! return true; ! String filename = file.getName(); ! return filename.endsWith(".png"); ! } ! public String getDescription() { ! return "PNG image (*.png)"; ! } ! } ! class PythonFilter extends javax.swing.filechooser.FileFilter { ! public boolean accept(File file) { ! if (file.isDirectory()) ! return true; ! String filename = file.getName(); ! return filename.endsWith(".py"); ! } ! public String getDescription() { ! return "Python Source code (*.py)"; ! } ! } } // @jve:decl-index=0:visual-constraint="10,10" Index: GraphPrinter.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/contrib/ch/hsr/ukistler/astgraph/GraphPrinter.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** GraphPrinter.java 20 Oct 2007 19:31:04 -0000 1.2 --- GraphPrinter.java 27 Sep 2008 20:00:48 -0000 1.3 *************** *** 7,16 **** public class GraphPrinter { ! public static void main(String[] args) throws Throwable { ! GraphView view = new GraphView(); ! view.setVisible(true); ! } } --- 7,16 ---- public class GraphPrinter { ! public static void main(String[] args) throws Throwable { ! GraphView view = new GraphView(); ! view.setVisible(true); ! } } |
From: Fabio Z. <fa...@us...> - 2008-09-27 20:03:47
|
Update of /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/ui/propertypages In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv20604/src/org/python/pydev/debug/ui/propertypages Modified Files: PythonBreakpointPage.java BreakpointConditionEditor.java Log Message: Synching to latest changes: Pydev <ul> <li><strong>Editor</strong>: Cursor settings no longer overridden</li> <li><strong>Code-completion</strong>: If __all__ is defined with runtime elements (and not only in a single assign statement), it's ignored for code-completion purposes</li> <li><strong>Debugger</strong>: Pythonpath the same in debug and regular modes (sys.path[0] is the same directory as the file run)</li> <li><strong>Debugger</strong>: Persist choices done in the debugger when files from the debugger are not found</li> <li><strong>Interpreter config</strong>: "email" automatically added to the "forced builtins"</li> <li><strong>Parser</strong>: Correctly recognizing absolute import with 3 or more levels</li> <li><strong>Syntax check</strong>: Option to do only on active editor</li> </ul> Also: tabs changed for spaces Index: PythonBreakpointPage.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/ui/propertypages/PythonBreakpointPage.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** PythonBreakpointPage.java 17 Dec 2005 12:58:45 -0000 1.1 --- PythonBreakpointPage.java 27 Sep 2008 19:59:09 -0000 1.2 *************** *** 36,87 **** public class PythonBreakpointPage extends PropertyPage { ! ! private Button fEnableConditionButton; ! private BreakpointConditionEditor fConditionEditor; ! private Label fConditionIsTrue; ! private Button fConditionHasChanged; ! private Label fSuspendWhenLabel; ! // Watchpoint editors ! private Button fFieldAccess; ! private Button fFieldModification; ! // Method breakpoint editors ! private Button fMethodEntry; ! private Button fMethodExit; ! ! private static final String fgMethodBreakpointError= "Must suspend on method entry or exit";//$NON-NLS-1$ ! protected Button fEnabledButton; ! protected Button fHitCountButton; ! protected Button fSuspendThreadButton; ! protected Button fSuspendVMButton; ! protected Text fHitCountText; ! protected List fErrorMessages= new ArrayList(); ! ! /** ! * Attribute used to indicate that a breakpoint should be deleted ! * when cancel is pressed. ! */ ! public static final String ATTR_DELETE_ON_CANCEL = PyDebugModelPresentation.PY_DEBUG_MODEL_ID + ".ATTR_DELETE_ON_CANCEL"; //$NON-NLS-1$ ! ! @Override ! protected Control createContents(Composite parent) { ! noDefaultAndApplyButton(); ! Composite mainComposite = createComposite(parent, 1); ! createLabels(mainComposite); ! try { ! createEnabledButton(mainComposite); ! //createHitCountEditor(mainComposite); ! createTypeSpecificEditors(mainComposite); ! //createSuspendPolicyEditor(mainComposite); // Suspend policy is considered uncommon. Add it last. ! } catch (CoreException e) { ! PydevDebugPlugin.log(IStatus.ERROR,e.getLocalizedMessage(),e); ! } ! setValid(true); ! // if this breakpoint is being created, change the shell title to indicate 'creation' ! try { if (getBreakpoint().getMarker().getAttribute(ATTR_DELETE_ON_CANCEL) != null) { ! getShell().addShellListener(new ShellListener() { public void shellActivated(ShellEvent e) { Shell shell = (Shell)e.getSource(); --- 36,87 ---- public class PythonBreakpointPage extends PropertyPage { ! ! private Button fEnableConditionButton; ! private BreakpointConditionEditor fConditionEditor; ! private Label fConditionIsTrue; ! private Button fConditionHasChanged; ! private Label fSuspendWhenLabel; ! // Watchpoint editors ! private Button fFieldAccess; ! private Button fFieldModification; ! // Method breakpoint editors ! private Button fMethodEntry; ! private Button fMethodExit; ! ! private static final String fgMethodBreakpointError= "Must suspend on method entry or exit";//$NON-NLS-1$ ! protected Button fEnabledButton; ! protected Button fHitCountButton; ! protected Button fSuspendThreadButton; ! protected Button fSuspendVMButton; ! protected Text fHitCountText; ! protected List fErrorMessages= new ArrayList(); ! ! /** ! * Attribute used to indicate that a breakpoint should be deleted ! * when cancel is pressed. ! */ ! public static final String ATTR_DELETE_ON_CANCEL = PyDebugModelPresentation.PY_DEBUG_MODEL_ID + ".ATTR_DELETE_ON_CANCEL"; //$NON-NLS-1$ ! ! @Override ! protected Control createContents(Composite parent) { ! noDefaultAndApplyButton(); ! Composite mainComposite = createComposite(parent, 1); ! createLabels(mainComposite); ! try { ! createEnabledButton(mainComposite); ! //createHitCountEditor(mainComposite); ! createTypeSpecificEditors(mainComposite); ! //createSuspendPolicyEditor(mainComposite); // Suspend policy is considered uncommon. Add it last. ! } catch (CoreException e) { ! PydevDebugPlugin.log(IStatus.ERROR,e.getLocalizedMessage(),e); ! } ! setValid(true); ! // if this breakpoint is being created, change the shell title to indicate 'creation' ! try { if (getBreakpoint().getMarker().getAttribute(ATTR_DELETE_ON_CANCEL) != null) { ! getShell().addShellListener(new ShellListener() { public void shellActivated(ShellEvent e) { Shell shell = (Shell)e.getSource(); *************** *** 101,247 **** } catch (CoreException e) { } ! return mainComposite; ! } ! /** ! * Creates a fully configured composite with the given number of columns ! * @param parent ! * @param numColumns ! * @return the configured composite ! */ ! protected Composite createComposite(Composite parent, int numColumns) { ! Composite composit= new Composite(parent, SWT.NONE); ! composit.setFont(parent.getFont()); ! GridLayout layout= new GridLayout(); ! layout.numColumns= numColumns; ! layout.marginWidth= 0; ! layout.marginHeight= 0; ! composit.setLayout(layout); ! composit.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); ! return composit; ! } ! ! /** ! * Creates a fully configured label with the given text. ! * @param parent the parent composite ! * @param text the test of the returned label ! * @return a fully configured label ! */ ! protected Label createLabel(Composite parent, String text) { ! Label label= new Label(parent, SWT.NONE); ! label.setText(text); ! label.setFont(parent.getFont()); ! label.setLayoutData(new GridData()); ! return label; ! } ! ! /** ! * Creates the labels displayed for the breakpoint. ! * @param parent ! */ ! protected void createLabels(Composite parent) { ! PyBreakpoint breakpoint= (PyBreakpoint) getElement(); ! Composite labelComposite= createComposite(parent, 2); ! String typeName = breakpoint.getFile(); ! if (typeName != null) { ! createLabel(labelComposite, "File"); //$NON-NLS-1$ ! createLabel(labelComposite, typeName); ! } ! createTypeSpecificLabels(labelComposite); ! } ! ! /** ! * Creates the button to toggle enablement of the breakpoint ! * @param parent ! * @throws CoreException ! */ ! protected void createEnabledButton(Composite parent) throws CoreException { ! fEnabledButton= createCheckButton(parent, "&Enabled"); //$NON-NLS-1$ ! fEnabledButton.setSelection(getBreakpoint().isEnabled()); ! } ! ! /** ! * Allows subclasses to add type specific labels to the common Java ! * breakpoint page. ! * @param parent ! */ ! protected void createTypeSpecificLabels(Composite parent) { ! // Line number ! PyBreakpoint breakpoint = (PyBreakpoint) getBreakpoint(); ! StringBuffer lineNumber = new StringBuffer(4); ! try { ! int lNumber = breakpoint.getLineNumber(); ! if (lNumber > 0) { ! lineNumber.append(lNumber); ! } ! } catch (CoreException ce) { ! PydevDebugPlugin.log(IStatus.ERROR,ce.getLocalizedMessage(),ce); ! } ! if (lineNumber.length() > 0) { ! createLabel(parent, "&Line Number:"); ! createLabel(parent, lineNumber.toString()); ! } ! // Member ! /* ! try { ! IMember member = BreakpointUtils.getMember(breakpoint); ! if (member == null) { ! return; ! } ! String label = PropertyPageMessages.JavaLineBreakpointPage_3; //$NON-NLS-1$ ! String memberName = fJavaLabelProvider.getText(member); ! if (breakpoint instanceof IJavaMethodBreakpoint) { ! label = PropertyPageMessages.JavaLineBreakpointPage_4; //$NON-NLS-1$ ! } else if (breakpoint instanceof IJavaWatchpoint) { ! label = PropertyPageMessages.JavaLineBreakpointPage_5; //$NON-NLS-1$ ! } ! createLabel(parent, label); ! createLabel(parent, memberName); ! } catch (CoreException exception) { ! PydevDebugPlugin.log(IStatus.ERROR,e.getLocalizedMessage(),exception); ! }*/ ! } ! /** ! * Allows subclasses to add type specific editors to the common Java ! * breakpoint page. ! * @param parent ! */ protected void createTypeSpecificEditors(Composite parent) throws CoreException { ! PyBreakpoint breakpoint= (PyBreakpoint) getBreakpoint(); ! if (breakpoint.supportsCondition()) { ! createConditionEditor(parent); ! } } ! private void validateMethodBreakpoint() { ! if (fEnabledButton.getSelection() && !(fMethodEntry.getSelection() || fMethodExit.getSelection())) { ! addErrorMessage(fgMethodBreakpointError); ! } else { ! removeErrorMessage(fgMethodBreakpointError); ! } ! } ! /** ! * Creates a fully configured check button with the given text. ! * @param parent the parent composite ! * @param text the label of the returned check button ! * @return a fully configured check button ! */ ! protected Button createCheckButton(Composite parent, String text) { ! Button button= new Button(parent, SWT.CHECK | SWT.LEFT); ! button.setText(text); ! button.setFont(parent.getFont()); ! button.setLayoutData(new GridData()); ! return button; ! } ! ! /** ! * Returns the breakpoint that this preference page configures ! * @return the breakpoint this page configures ! */ ! protected PyBreakpoint getBreakpoint() { ! return (PyBreakpoint) getElement(); ! } /** --- 101,247 ---- } catch (CoreException e) { } ! return mainComposite; ! } ! /** ! * Creates a fully configured composite with the given number of columns ! * @param parent ! * @param numColumns ! * @return the configured composite ! */ ! protected Composite createComposite(Composite parent, int numColumns) { ! Composite composit= new Composite(parent, SWT.NONE); ! composit.setFont(parent.getFont()); ! GridLayout layout= new GridLayout(); ! layout.numColumns= numColumns; ! layout.marginWidth= 0; ! layout.marginHeight= 0; ! composit.setLayout(layout); ! composit.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); ! return composit; ! } ! ! /** ! * Creates a fully configured label with the given text. ! * @param parent the parent composite ! * @param text the test of the returned label ! * @return a fully configured label ! */ ! protected Label createLabel(Composite parent, String text) { ! Label label= new Label(parent, SWT.NONE); ! label.setText(text); ! label.setFont(parent.getFont()); ! label.setLayoutData(new GridData()); ! return label; ! } ! ! /** ! * Creates the labels displayed for the breakpoint. ! * @param parent ! */ ! protected void createLabels(Composite parent) { ! PyBreakpoint breakpoint= (PyBreakpoint) getElement(); ! Composite labelComposite= createComposite(parent, 2); ! String typeName = breakpoint.getFile(); ! if (typeName != null) { ! createLabel(labelComposite, "File"); //$NON-NLS-1$ ! createLabel(labelComposite, typeName); ! } ! createTypeSpecificLabels(labelComposite); ! } ! ! /** ! * Creates the button to toggle enablement of the breakpoint ! * @param parent ! * @throws CoreException ! */ ! protected void createEnabledButton(Composite parent) throws CoreException { ! fEnabledButton= createCheckButton(parent, "&Enabled"); //$NON-NLS-1$ ! fEnabledButton.setSelection(getBreakpoint().isEnabled()); ! } ! ! /** ! * Allows subclasses to add type specific labels to the common Java ! * breakpoint page. ! * @param parent ! */ ! protected void createTypeSpecificLabels(Composite parent) { ! // Line number ! PyBreakpoint breakpoint = (PyBreakpoint) getBreakpoint(); ! StringBuffer lineNumber = new StringBuffer(4); ! try { ! int lNumber = breakpoint.getLineNumber(); ! if (lNumber > 0) { ! lineNumber.append(lNumber); ! } ! } catch (CoreException ce) { ! PydevDebugPlugin.log(IStatus.ERROR,ce.getLocalizedMessage(),ce); ! } ! if (lineNumber.length() > 0) { ! createLabel(parent, "&Line Number:"); ! createLabel(parent, lineNumber.toString()); ! } ! // Member ! /* ! try { ! IMember member = BreakpointUtils.getMember(breakpoint); ! if (member == null) { ! return; ! } ! String label = PropertyPageMessages.JavaLineBreakpointPage_3; //$NON-NLS-1$ ! String memberName = fJavaLabelProvider.getText(member); ! if (breakpoint instanceof IJavaMethodBreakpoint) { ! label = PropertyPageMessages.JavaLineBreakpointPage_4; //$NON-NLS-1$ ! } else if (breakpoint instanceof IJavaWatchpoint) { ! label = PropertyPageMessages.JavaLineBreakpointPage_5; //$NON-NLS-1$ ! } ! createLabel(parent, label); ! createLabel(parent, memberName); ! } catch (CoreException exception) { ! PydevDebugPlugin.log(IStatus.ERROR,e.getLocalizedMessage(),exception); ! }*/ ! } ! /** ! * Allows subclasses to add type specific editors to the common Java ! * breakpoint page. ! * @param parent ! */ protected void createTypeSpecificEditors(Composite parent) throws CoreException { ! PyBreakpoint breakpoint= (PyBreakpoint) getBreakpoint(); ! if (breakpoint.supportsCondition()) { ! createConditionEditor(parent); ! } } ! private void validateMethodBreakpoint() { ! if (fEnabledButton.getSelection() && !(fMethodEntry.getSelection() || fMethodExit.getSelection())) { ! addErrorMessage(fgMethodBreakpointError); ! } else { ! removeErrorMessage(fgMethodBreakpointError); ! } ! } ! /** ! * Creates a fully configured check button with the given text. ! * @param parent the parent composite ! * @param text the label of the returned check button ! * @return a fully configured check button ! */ ! protected Button createCheckButton(Composite parent, String text) { ! Button button= new Button(parent, SWT.CHECK | SWT.LEFT); ! button.setText(text); ! button.setFont(parent.getFont()); ! button.setLayoutData(new GridData()); ! return button; ! } ! ! /** ! * Returns the breakpoint that this preference page configures ! * @return the breakpoint this page configures ! */ ! protected PyBreakpoint getBreakpoint() { ! return (PyBreakpoint) getElement(); ! } /** *************** *** 259,465 **** } return "";//$NON-NLS-1$ ! } ! ! ! /** ! * Store the breakpoint properties. ! * @see org.eclipse.jface.preference.IPreferencePage#performOk() ! */ ! public boolean performOk() { ! IWorkspaceRunnable wr = new IWorkspaceRunnable() { ! public void run(IProgressMonitor monitor) throws CoreException { ! PyBreakpoint breakpoint = getBreakpoint(); ! boolean delOnCancel = breakpoint.getMarker().getAttribute(ATTR_DELETE_ON_CANCEL) != null; ! if (delOnCancel) { ! // if this breakpoint is being created, remove the "delete on cancel" attribute ! // and register with the breakpoint manager ! breakpoint.getMarker().setAttribute(ATTR_DELETE_ON_CANCEL, (String)null); ! breakpoint.setRegistered(true); ! } ! doStore(); ! } ! }; ! try { ! ResourcesPlugin.getWorkspace().run(wr, null, 0, null); ! } catch (CoreException e) { ! PydevDebugPlugin.errorDialog("An exception occurred while saving breakpoint properties.", e); //$NON-NLS-1$ ! PydevDebugPlugin.log(IStatus.ERROR,e.getLocalizedMessage(),e); ! } ! return super.performOk(); ! } ! ! /** ! * Check to see if the breakpoint should be deleted. ! */ ! public boolean performCancel() { ! try { ! if (getBreakpoint().getMarker().getAttribute(ATTR_DELETE_ON_CANCEL) != null) { ! // if this breakpoint is being created, delete on cancel ! getBreakpoint().delete(); ! } ! } catch (CoreException e) { ! PydevDebugPlugin.errorDialog("Unable to cancel breakpoint creation", e); //$NON-NLS-1$ ! } ! return super.performCancel(); ! } ! ! /** ! * Stores the values configured in this page. This method ! * should be called from within a workspace runnable to ! * reduce the number of resource deltas. ! */ ! protected void doStore() throws CoreException { ! PyBreakpoint breakpoint= getBreakpoint(); ! storeEnabled(breakpoint); ! ! ! if (fConditionEditor != null) { ! boolean enableCondition= fEnableConditionButton.getSelection(); ! String condition = fConditionEditor.getCondition(); ! //boolean suspendOnTrue= fConditionIsTrue.getSelection(); ! boolean suspendOnTrue= true; ! if (breakpoint.isConditionEnabled() != enableCondition) { ! breakpoint.setConditionEnabled(enableCondition); ! } ! if (!condition.equals(breakpoint.getCondition())) { ! breakpoint.setCondition(condition); ! } ! } ! } ! ! /** ! * Stores the value of the enabled state in the breakpoint. ! * @param breakpoint the breakpoint to update ! * @throws CoreException if an exception occurs while setting ! * the enabled state ! */ ! private void storeEnabled(PyBreakpoint breakpoint) throws CoreException { ! boolean enabled= fEnabledButton.getSelection(); ! breakpoint.setEnabled(enabled); ! } ! ! /** ! * Creates the controls that allow the user to specify the breakpoint's ! * condition ! * @param parent the composite in which the condition editor should be created ! * @throws CoreException if an exception occurs accessing the breakpoint ! */ ! private void createConditionEditor(Composite parent) throws CoreException { ! PyBreakpoint breakpoint = (PyBreakpoint) getBreakpoint(); ! String label = null; ! ICommandManager commandManager= PlatformUI.getWorkbench().getCommandSupport().getCommandManager(); ! ICommand command = commandManager.getCommand("org.eclipse.ui.edit.text.contentAssist.proposals"); //$NON-NLS-1$ ! if (command != null) { ! List keyBindings = command.getKeySequenceBindings(); ! if (keyBindings != null && keyBindings.size() > 0) { ! IKeySequenceBinding binding = (IKeySequenceBinding)keyBindings.get(0); ! label = MessageFormat.format("E&nable Condition", new String[] {binding.getKeySequence().format()}); //$NON-NLS-1$ ! } ! } ! if (label == null) { ! label = "E&nable Condition (code assist not available)"; //$NON-NLS-1$ ! } ! Composite conditionComposite= new Group(parent, SWT.NONE); ! conditionComposite.setFont(parent.getFont()); ! conditionComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); ! conditionComposite.setLayout(new GridLayout()); ! fEnableConditionButton= createCheckButton(conditionComposite, label); ! fEnableConditionButton.setSelection(breakpoint.isConditionEnabled()); ! fEnableConditionButton.addSelectionListener(new SelectionAdapter() { ! public void widgetSelected(SelectionEvent e) { ! setConditionEnabled(fEnableConditionButton.getSelection()); ! } ! }); ! ! fConditionEditor = new BreakpointConditionEditor(conditionComposite, this); //$NON-NLS-1$ ! ! //fSuspendWhenLabel= createLabel(conditionComposite, "Suspend when:"); ! //fConditionIsTrue= createRadioButton(conditionComposite, "condition is \'tr&ue\'"); ! //fConditionIsTrue= createLabel(conditionComposite, "condition is \'tr&ue\'"); ! //fConditionHasChanged= createRadioButton(conditionComposite, "value of condition ch&anges"); ! // if (breakpoint.isConditionSuspendOnTrue()) { ! // fConditionIsTrue.setSelection(true); ! // } else { ! // fConditionHasChanged.setSelection(true); ! // } ! setConditionEnabled(fEnableConditionButton.getSelection()); ! } ! ! /** ! * Sets the enabled state of the condition editing controls. ! * @param enabled ! */ ! private void setConditionEnabled(boolean enabled) { ! fConditionEditor.setEnabled(enabled); ! // fSuspendWhenLabel.setEnabled(enabled); ! // fConditionIsTrue.setEnabled(enabled); ! //fConditionHasChanged.setEnabled(enabled); ! } ! ! /** ! * Overridden here to increase visibility ! * @see org.eclipse.jface.dialogs.DialogPage#convertHeightInCharsToPixels(int) ! */ ! public int convertHeightInCharsToPixels(int chars) { ! return super.convertHeightInCharsToPixels(chars); ! } ! ! /** ! * Overridden here to increase visibility ! * @see org.eclipse.jface.dialogs.DialogPage#convertWidthInCharsToPixels(int) ! */ ! public int convertWidthInCharsToPixels(int chars) { ! return super.convertWidthInCharsToPixels(chars); ! } ! ! /** ! * Adds the given error message to the errors currently displayed on this page. ! * The page displays the most recently added error message. ! * Clients should retain messages that are passed into this method as the ! * message should later be passed into removeErrorMessage(String) to clear the error. ! * This method should be used instead of setErrorMessage(String). ! * @param message the error message to display on this page. ! */ ! public void addErrorMessage(String message) { ! if (message == null) { ! return; ! } ! fErrorMessages.remove(message); ! fErrorMessages.add(message); ! setErrorMessage(message); ! setValid(false); ! } ! ! /** ! * Removes the given error message from the errors currently displayed on this page. ! * When an error message is removed, the page displays the error that was added ! * before the given message. This is akin to popping the message from a stack. ! * Clients should call this method instead of setErrorMessage(null). ! * @param message the error message to clear ! */ ! public void removeErrorMessage(String message) { ! fErrorMessages.remove(message); ! if (fErrorMessages.isEmpty()) { ! setErrorMessage(null); ! setValid(true); ! } else { ! setErrorMessage((String) fErrorMessages.get(fErrorMessages.size() - 1)); ! } ! } ! ! /** ! * Creates a fully configured radio button with the given text. ! * @param parent the parent composite ! * @param text the label of the returned radio button ! * @return a fully configured radio button ! */ ! protected Button createRadioButton(Composite parent, String text) { ! Button button= new Button(parent, SWT.RADIO | SWT.LEFT); ! button.setText(text); ! button.setFont(parent.getFont()); ! button.setLayoutData(new GridData()); ! return button; ! } } --- 259,465 ---- } return "";//$NON-NLS-1$ ! } ! ! ! /** ! * Store the breakpoint properties. ! * @see org.eclipse.jface.preference.IPreferencePage#performOk() ! */ ! public boolean performOk() { ! IWorkspaceRunnable wr = new IWorkspaceRunnable() { ! public void run(IProgressMonitor monitor) throws CoreException { ! PyBreakpoint breakpoint = getBreakpoint(); ! boolean delOnCancel = breakpoint.getMarker().getAttribute(ATTR_DELETE_ON_CANCEL) != null; ! if (delOnCancel) { ! // if this breakpoint is being created, remove the "delete on cancel" attribute ! // and register with the breakpoint manager ! breakpoint.getMarker().setAttribute(ATTR_DELETE_ON_CANCEL, (String)null); ! breakpoint.setRegistered(true); ! } ! doStore(); ! } ! }; ! try { ! ResourcesPlugin.getWorkspace().run(wr, null, 0, null); ! } catch (CoreException e) { ! PydevDebugPlugin.errorDialog("An exception occurred while saving breakpoint properties.", e); //$NON-NLS-1$ ! PydevDebugPlugin.log(IStatus.ERROR,e.getLocalizedMessage(),e); ! } ! return super.performOk(); ! } ! ! /** ! * Check to see if the breakpoint should be deleted. ! */ ! public boolean performCancel() { ! try { ! if (getBreakpoint().getMarker().getAttribute(ATTR_DELETE_ON_CANCEL) != null) { ! // if this breakpoint is being created, delete on cancel ! getBreakpoint().delete(); ! } ! } catch (CoreException e) { ! PydevDebugPlugin.errorDialog("Unable to cancel breakpoint creation", e); //$NON-NLS-1$ ! } ! return super.performCancel(); ! } ! ! /** ! * Stores the values configured in this page. This method ! * should be called from within a workspace runnable to ! * reduce the number of resource deltas. ! */ ! protected void doStore() throws CoreException { ! PyBreakpoint breakpoint= getBreakpoint(); ! storeEnabled(breakpoint); ! ! ! if (fConditionEditor != null) { ! boolean enableCondition= fEnableConditionButton.getSelection(); ! String condition = fConditionEditor.getCondition(); ! //boolean suspendOnTrue= fConditionIsTrue.getSelection(); ! boolean suspendOnTrue= true; ! if (breakpoint.isConditionEnabled() != enableCondition) { ! breakpoint.setConditionEnabled(enableCondition); ! } ! if (!condition.equals(breakpoint.getCondition())) { ! breakpoint.setCondition(condition); ! } ! } ! } ! ! /** ! * Stores the value of the enabled state in the breakpoint. ! * @param breakpoint the breakpoint to update ! * @throws CoreException if an exception occurs while setting ! * the enabled state ! */ ! private void storeEnabled(PyBreakpoint breakpoint) throws CoreException { ! boolean enabled= fEnabledButton.getSelection(); ! breakpoint.setEnabled(enabled); ! } ! ! /** ! * Creates the controls that allow the user to specify the breakpoint's ! * condition ! * @param parent the composite in which the condition editor should be created ! * @throws CoreException if an exception occurs accessing the breakpoint ! */ ! private void createConditionEditor(Composite parent) throws CoreException { ! PyBreakpoint breakpoint = (PyBreakpoint) getBreakpoint(); ! String label = null; ! ICommandManager commandManager= PlatformUI.getWorkbench().getCommandSupport().getCommandManager(); ! ICommand command = commandManager.getCommand("org.eclipse.ui.edit.text.contentAssist.proposals"); //$NON-NLS-1$ ! if (command != null) { ! List keyBindings = command.getKeySequenceBindings(); ! if (keyBindings != null && keyBindings.size() > 0) { ! IKeySequenceBinding binding = (IKeySequenceBinding)keyBindings.get(0); ! label = MessageFormat.format("E&nable Condition", new String[] {binding.getKeySequence().format()}); //$NON-NLS-1$ ! } ! } ! if (label == null) { ! label = "E&nable Condition (code assist not available)"; //$NON-NLS-1$ ! } ! Composite conditionComposite= new Group(parent, SWT.NONE); ! conditionComposite.setFont(parent.getFont()); ! conditionComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); ! conditionComposite.setLayout(new GridLayout()); ! fEnableConditionButton= createCheckButton(conditionComposite, label); ! fEnableConditionButton.setSelection(breakpoint.isConditionEnabled()); ! fEnableConditionButton.addSelectionListener(new SelectionAdapter() { ! public void widgetSelected(SelectionEvent e) { ! setConditionEnabled(fEnableConditionButton.getSelection()); ! } ! }); ! ! fConditionEditor = new BreakpointConditionEditor(conditionComposite, this); //$NON-NLS-1$ ! ! //fSuspendWhenLabel= createLabel(conditionComposite, "Suspend when:"); ! //fConditionIsTrue= createRadioButton(conditionComposite, "condition is \'tr&ue\'"); ! //fConditionIsTrue= createLabel(conditionComposite, "condition is \'tr&ue\'"); ! //fConditionHasChanged= createRadioButton(conditionComposite, "value of condition ch&anges"); ! // if (breakpoint.isConditionSuspendOnTrue()) { ! // fConditionIsTrue.setSelection(true); ! // } else { ! // fConditionHasChanged.setSelection(true); ! // } ! setConditionEnabled(fEnableConditionButton.getSelection()); ! } ! ! /** ! * Sets the enabled state of the condition editing controls. ! * @param enabled ! */ ! private void setConditionEnabled(boolean enabled) { ! fConditionEditor.setEnabled(enabled); ! // fSuspendWhenLabel.setEnabled(enabled); ! // fConditionIsTrue.setEnabled(enabled); ! //fConditionHasChanged.setEnabled(enabled); ! } ! ! /** ! * Overridden here to increase visibility ! * @see org.eclipse.jface.dialogs.DialogPage#convertHeightInCharsToPixels(int) ! */ ! public int convertHeightInCharsToPixels(int chars) { ! return super.convertHeightInCharsToPixels(chars); ! } ! ! /** ! * Overridden here to increase visibility ! * @see org.eclipse.jface.dialogs.DialogPage#convertWidthInCharsToPixels(int) ! */ ! public int convertWidthInCharsToPixels(int chars) { ! return super.convertWidthInCharsToPixels(chars); ! } ! ! /** ! * Adds the given error message to the errors currently displayed on this page. ! * The page displays the most recently added error message. ! * Clients should retain messages that are passed into this method as the ! * message should later be passed into removeErrorMessage(String) to clear the error. ! * This method should be used instead of setErrorMessage(String). ! * @param message the error message to display on this page. ! */ ! public void addErrorMessage(String message) { ! if (message == null) { ! return; ! } ! fErrorMessages.remove(message); ! fErrorMessages.add(message); ! setErrorMessage(message); ! setValid(false); ! } ! ! /** ! * Removes the given error message from the errors currently displayed on this page. ! * When an error message is removed, the page displays the error that was added ! * before the given message. This is akin to popping the message from a stack. ! * Clients should call this method instead of setErrorMessage(null). ! * @param message the error message to clear ! */ ! public void removeErrorMessage(String message) { ! fErrorMessages.remove(message); ! if (fErrorMessages.isEmpty()) { ! setErrorMessage(null); ! setValid(true); ! } else { ! setErrorMessage((String) fErrorMessages.get(fErrorMessages.size() - 1)); ! } ! } ! ! /** ! * Creates a fully configured radio button with the given text. ! * @param parent the parent composite ! * @param text the label of the returned radio button ! * @return a fully configured radio button ! */ ! protected Button createRadioButton(Composite parent, String text) { ! Button button= new Button(parent, SWT.RADIO | SWT.LEFT); ! button.setText(text); ! button.setFont(parent.getFont()); ! button.setLayoutData(new GridData()); ! return button; ! } } Index: BreakpointConditionEditor.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/ui/propertypages/BreakpointConditionEditor.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** BreakpointConditionEditor.java 7 Dec 2007 00:49:24 -0000 1.4 --- BreakpointConditionEditor.java 27 Sep 2008 19:59:09 -0000 1.5 *************** *** 37,96 **** public class BreakpointConditionEditor { ! private boolean fIsValid; ! ! private String fOldValue; ! private String fErrorMessage; ! ! private HandlerSubmission submission; private IDocumentListener fDocumentListener; ! private PythonBreakpointPage fPage; ! private PyBreakpoint fBreakpoint; ! private PythonSourceViewer fViewer; ! public BreakpointConditionEditor(Composite parent, PythonBreakpointPage page) { ! fPage = page; ! fBreakpoint= (PyBreakpoint) fPage.getBreakpoint(); ! String condition; ! try { ! condition= fBreakpoint.getCondition(); ! } catch (DebugException e) { ! PydevDebugPlugin.log(IStatus.ERROR, "Can't read conditions", e); ! return; ! } ! fErrorMessage= "Enter a condition"; //$NON-NLS-1$ ! fOldValue= ""; //$NON-NLS-1$ ! ! // the source viewer ! fViewer= new PythonSourceViewer(parent, null, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); ! fViewer.setInput(parent); ! ! IDocument document= new Document(); ! IDocumentPartitioner partitioner= new PyPartitioner(new PyPartitionScanner(), IPythonPartitions.types); ! document.setDocumentPartitioner(partitioner); ! partitioner.connect(document); ! /* ! fViewer.configure(new DisplayViewerConfiguration() { ! public IContentAssistProcessor getContentAssistantProcessor() { ! return getCompletionProcessor(); ! } ! });*/ ! fViewer.setEditable(true); ! fViewer.setDocument(document); ! final IUndoManager undoManager= new TextViewerUndoManager(100); ! fViewer.setUndoManager(undoManager); ! undoManager.connect(fViewer); ! ! fViewer.getTextWidget().setFont(JFaceResources.getTextFont()); ! ! Control control= fViewer.getControl(); ! GridData gd = new GridData(GridData.FILL_BOTH); ! control.setLayoutData(gd); ! ! // listener for check the value ! fDocumentListener= new IDocumentListener() { public void documentAboutToBeChanged(DocumentEvent event) { } --- 37,96 ---- public class BreakpointConditionEditor { ! private boolean fIsValid; ! ! private String fOldValue; ! private String fErrorMessage; ! ! private HandlerSubmission submission; private IDocumentListener fDocumentListener; ! private PythonBreakpointPage fPage; ! private PyBreakpoint fBreakpoint; ! private PythonSourceViewer fViewer; ! public BreakpointConditionEditor(Composite parent, PythonBreakpointPage page) { ! fPage = page; ! fBreakpoint= (PyBreakpoint) fPage.getBreakpoint(); ! String condition; ! try { ! condition= fBreakpoint.getCondition(); ! } catch (DebugException e) { ! PydevDebugPlugin.log(IStatus.ERROR, "Can't read conditions", e); ! return; ! } ! fErrorMessage= "Enter a condition"; //$NON-NLS-1$ ! fOldValue= ""; //$NON-NLS-1$ ! ! // the source viewer ! fViewer= new PythonSourceViewer(parent, null, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); ! fViewer.setInput(parent); ! ! IDocument document= new Document(); ! IDocumentPartitioner partitioner= new PyPartitioner(new PyPartitionScanner(), IPythonPartitions.types); ! document.setDocumentPartitioner(partitioner); ! partitioner.connect(document); ! /* ! fViewer.configure(new DisplayViewerConfiguration() { ! public IContentAssistProcessor getContentAssistantProcessor() { ! return getCompletionProcessor(); ! } ! });*/ ! fViewer.setEditable(true); ! fViewer.setDocument(document); ! final IUndoManager undoManager= new TextViewerUndoManager(100); ! fViewer.setUndoManager(undoManager); ! undoManager.connect(fViewer); ! ! fViewer.getTextWidget().setFont(JFaceResources.getTextFont()); ! ! Control control= fViewer.getControl(); ! GridData gd = new GridData(GridData.FILL_BOTH); ! control.setLayoutData(gd); ! ! // listener for check the value ! fDocumentListener= new IDocumentListener() { public void documentAboutToBeChanged(DocumentEvent event) { } *************** *** 99,224 **** } }; ! fViewer.getDocument().addDocumentListener(fDocumentListener); ! ! // we can only do code assist if there is an associated type ! /* ! try { ! //getCompletionProcessor().setType(type); ! String source= null; ! ICompilationUnit compilationUnit= type.getCompilationUnit(); ! if (compilationUnit != null) { ! source= compilationUnit.getSource(); ! } else { ! IClassFile classFile= type.getClassFile(); ! if (classFile != null) { ! source= classFile.getSource(); ! } ! } ! int lineNumber= fBreakpoint.getMarker().getAttribute(IMarker.LINE_NUMBER, -1); ! int position= -1; ! if (source != null && lineNumber != -1) { ! try { ! position= new Document(source).getLineOffset(lineNumber - 1); ! } catch (BadLocationException e) { ! } ! } ! //getCompletionProcessor().setPosition(position); ! } catch (CoreException e) { ! }*/ ! ! gd= (GridData)fViewer.getControl().getLayoutData(); ! gd.heightHint= fPage.convertHeightInCharsToPixels(10); ! gd.widthHint= fPage.convertWidthInCharsToPixels(40); ! document.set(condition); ! valueChanged(); ! ! IHandler handler = new AbstractHandler() { ! public Object execute(Map parameter) throws ExecutionException { ! fViewer.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS); ! return null; ! } ! }; ! submission = new HandlerSubmission(null, parent.getShell(), null, ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS, handler, Priority.MEDIUM); //$NON-NLS-1$ ! } ! /** ! * Returns the condition defined in the source viewer. ! * @return the contents of this condition editor ! */ ! public String getCondition() { ! return fViewer.getDocument().get(); ! } ! /** ! * @see org.eclipse.jface.preference.FieldEditor#refreshValidState() ! */ ! protected void refreshValidState() { ! // the value is valid if the field is not editable, or if the value is not empty ! if (!fViewer.isEditable()) { ! fPage.removeErrorMessage(fErrorMessage); ! fIsValid= true; ! } else { ! String text= fViewer.getDocument().get(); ! fIsValid= text != null && text.trim().length() > 0; ! if (!fIsValid) { ! fPage.addErrorMessage(fErrorMessage); ! } else { ! fPage.removeErrorMessage(fErrorMessage); ! } ! } ! } ! ! /** ! * Return the completion processor associated with this viewer. ! * @return BreakPointConditionCompletionProcessor ! *//* ! protected BreakpointConditionCompletionProcessor getCompletionProcessor() { ! if (fCompletionProcessor == null) { ! fCompletionProcessor= new BreakpointConditionCompletionProcessor(null); ! } ! return fCompletionProcessor; ! }*/ ! /** ! * @see org.eclipse.jface.preference.FieldEditor#setEnabled(boolean, org.eclipse.swt.widgets.Composite) ! */ ! public void setEnabled(boolean enabled) { ! fViewer.setEditable(enabled); ! fViewer.getTextWidget().setEnabled(enabled); ! if (enabled) { ! fViewer.updateViewerColors(); ! fViewer.getTextWidget().setFocus(); ! ! IWorkbench workbench = PlatformUI.getWorkbench(); ! IWorkbenchCommandSupport commandSupport = workbench.getCommandSupport(); ! commandSupport.addHandlerSubmission(submission); ! } else { ! Color color= fViewer.getControl().getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND); ! fViewer.getTextWidget().setBackground(color); ! IWorkbench workbench = PlatformUI.getWorkbench(); ! IWorkbenchCommandSupport commandSupport = workbench.getCommandSupport(); ! commandSupport.removeHandlerSubmission(submission); ! } ! valueChanged(); ! } ! ! protected void valueChanged() { ! refreshValidState(); ! ! String newValue = fViewer.getDocument().get(); ! if (!newValue.equals(fOldValue)) { ! fOldValue = newValue; ! } ! } ! ! public void dispose() { ! if (fViewer.isEditable()) { ! IWorkbench workbench = PlatformUI.getWorkbench(); ! IWorkbenchCommandSupport commandSupport = workbench.getCommandSupport(); ! commandSupport.removeHandlerSubmission(submission); ! } ! fViewer.getDocument().removeDocumentListener(fDocumentListener); ! fViewer.dispose(); ! } ! } --- 99,224 ---- } }; ! fViewer.getDocument().addDocumentListener(fDocumentListener); ! ! // we can only do code assist if there is an associated type ! /* ! try { ! //getCompletionProcessor().setType(type); ! String source= null; ! ICompilationUnit compilationUnit= type.getCompilationUnit(); ! if (compilationUnit != null) { ! source= compilationUnit.getSource(); ! } else { ! IClassFile classFile= type.getClassFile(); ! if (classFile != null) { ! source= classFile.getSource(); ! } ! } ! int lineNumber= fBreakpoint.getMarker().getAttribute(IMarker.LINE_NUMBER, -1); ! int position= -1; ! if (source != null && lineNumber != -1) { ! try { ! position= new Document(source).getLineOffset(lineNumber - 1); ! } catch (BadLocationException e) { ! } ! } ! //getCompletionProcessor().setPosition(position); ! } catch (CoreException e) { ! }*/ ! ! gd= (GridData)fViewer.getControl().getLayoutData(); ! gd.heightHint= fPage.convertHeightInCharsToPixels(10); ! gd.widthHint= fPage.convertWidthInCharsToPixels(40); ! document.set(condition); ! valueChanged(); ! ! IHandler handler = new AbstractHandler() { ! public Object execute(Map parameter) throws ExecutionException { ! fViewer.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS); ! return null; ! } ! }; ! submission = new HandlerSubmission(null, parent.getShell(), null, ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS, handler, Priority.MEDIUM); //$NON-NLS-1$ ! } ! /** ! * Returns the condition defined in the source viewer. ! * @return the contents of this condition editor ! */ ! public String getCondition() { ! return fViewer.getDocument().get(); ! } ! /** ! * @see org.eclipse.jface.preference.FieldEditor#refreshValidState() ! */ ! protected void refreshValidState() { ! // the value is valid if the field is not editable, or if the value is not empty ! if (!fViewer.isEditable()) { ! fPage.removeErrorMessage(fErrorMessage); ! fIsValid= true; ! } else { ! String text= fViewer.getDocument().get(); ! fIsValid= text != null && text.trim().length() > 0; ! if (!fIsValid) { ! fPage.addErrorMessage(fErrorMessage); ! } else { ! fPage.removeErrorMessage(fErrorMessage); ! } ! } ! } ! ! /** ! * Return the completion processor associated with this viewer. ! * @return BreakPointConditionCompletionProcessor ! *//* ! protected BreakpointConditionCompletionProcessor getCompletionProcessor() { ! if (fCompletionProcessor == null) { ! fCompletionProcessor= new BreakpointConditionCompletionProcessor(null); ! } ! return fCompletionProcessor; ! }*/ ! /** ! * @see org.eclipse.jface.preference.FieldEditor#setEnabled(boolean, org.eclipse.swt.widgets.Composite) ! */ ! public void setEnabled(boolean enabled) { ! fViewer.setEditable(enabled); ! fViewer.getTextWidget().setEnabled(enabled); ! if (enabled) { ! fViewer.updateViewerColors(); ! fViewer.getTextWidget().setFocus(); ! ! IWorkbench workbench = PlatformUI.getWorkbench(); ! IWorkbenchCommandSupport commandSupport = workbench.getCommandSupport(); ! commandSupport.addHandlerSubmission(submission); ! } else { ! Color color= fViewer.getControl().getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND); ! fViewer.getTextWidget().setBackground(color); ! IWorkbench workbench = PlatformUI.getWorkbench(); ! IWorkbenchCommandSupport commandSupport = workbench.getCommandSupport(); ! commandSupport.removeHandlerSubmission(submission); ! } ! valueChanged(); ! } ! ! protected void valueChanged() { ! refreshValidState(); ! ! String newValue = fViewer.getDocument().get(); ! if (!newValue.equals(fOldValue)) { ! fOldValue = newValue; ! } ! } ! ! public void dispose() { ! if (fViewer.isEditable()) { ! IWorkbench workbench = PlatformUI.getWorkbench(); ! IWorkbenchCommandSupport commandSupport = workbench.getCommandSupport(); ! commandSupport.removeHandlerSubmission(submission); ! } ! fViewer.getDocument().removeDocumentListener(fDocumentListener); ! fViewer.dispose(); ! } ! } |
From: Fabio Z. <fa...@us...> - 2008-09-27 20:03:45
|
Update of /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/ui/launching In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv20604/src/org/python/pydev/debug/ui/launching Modified Files: AbstractLaunchShortcut.java PythonRunnerConfig.java PythonRunner.java Log Message: Synching to latest changes: Pydev <ul> <li><strong>Editor</strong>: Cursor settings no longer overridden</li> <li><strong>Code-completion</strong>: If __all__ is defined with runtime elements (and not only in a single assign statement), it's ignored for code-completion purposes</li> <li><strong>Debugger</strong>: Pythonpath the same in debug and regular modes (sys.path[0] is the same directory as the file run)</li> <li><strong>Debugger</strong>: Persist choices done in the debugger when files from the debugger are not found</li> <li><strong>Interpreter config</strong>: "email" automatically added to the "forced builtins"</li> <li><strong>Parser</strong>: Correctly recognizing absolute import with 3 or more levels</li> <li><strong>Syntax check</strong>: Option to do only on active editor</li> </ul> Also: tabs changed for spaces Index: PythonRunner.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/ui/launching/PythonRunner.java,v retrieving revision 1.38 retrieving revision 1.39 diff -C2 -d -r1.38 -r1.39 *** PythonRunner.java 17 Aug 2008 00:26:56 -0000 1.38 --- PythonRunner.java 27 Sep 2008 19:59:08 -0000 1.39 *************** *** 65,74 **** ! /** ! * Launches the configuration * * The code is modeled after Ant launching example. ! */ ! public static void run(final PythonRunnerConfig config, ILaunch launch, IProgressMonitor monitor) throws CoreException, IOException { //let's check if the interpreter is valid. final IInterpreterManager interpreterManager = PythonNature.getPythonNature(config.project).getRelatedInterpreterManager(); --- 65,74 ---- ! /** ! * Launches the configuration * * The code is modeled after Ant launching example. ! */ ! public static void run(final PythonRunnerConfig config, ILaunch launch, IProgressMonitor monitor) throws CoreException, IOException { //let's check if the interpreter is valid. final IInterpreterManager interpreterManager = PythonNature.getPythonNature(config.project).getRelatedInterpreterManager(); *************** *** 93,105 **** try{ ! if (config.isDebug) { ! runDebug(config, launch, monitor); ! }else if (config.isUnittest()) { ! runUnitTest(config, launch, monitor); ! }else { //default - just configured by command line (the others need special attention) ! doIt(config, monitor, config.envp, config.getCommandLine(true), config.workingDirectory, launch); ! } }catch (final JDTNotAvailableException e) { PydevPlugin.log(e); --- 93,105 ---- try{ ! if (config.isDebug) { ! runDebug(config, launch, monitor); ! }else if (config.isUnittest()) { ! runUnitTest(config, launch, monitor); ! }else { //default - just configured by command line (the others need special attention) ! doIt(config, monitor, config.envp, config.getCommandLine(true), config.workingDirectory, launch); ! } }catch (final JDTNotAvailableException e) { PydevPlugin.log(e); *************** *** 113,175 **** }); } ! } ! /** ! * Launches the config in the debug mode. ! * ! * Loosely modeled upon Ant launcher. ! * @throws JDTNotAvailableException ! */ ! private static void runDebug(PythonRunnerConfig config, ILaunch launch, IProgressMonitor monitor) throws CoreException, IOException, JDTNotAvailableException { ! if (monitor == null) ! monitor = new NullProgressMonitor(); ! IProgressMonitor subMonitor = new SubProgressMonitor(monitor, 5); ! subMonitor.beginTask("Launching python", 1); ! ! // Launch & connect to the debugger ! RemoteDebugger debugger = new RemoteDebugger(config); ! debugger.startConnect(subMonitor); ! subMonitor.subTask("Constructing command_line..."); ! String[] cmdLine = config.getCommandLine(true); ! Process p = createProcess(launch, config.envp, cmdLine, config.workingDirectory); ! checkProcess(p); ! ! IProcess process = registerWithDebugPlugin(config, launch, p); checkProcess(p, process); ! subMonitor.subTask("Waiting for connection..."); ! try { ! boolean userCanceled = debugger.waitForConnect(subMonitor, p, process); ! if (userCanceled) { ! debugger.dispose(); ! return; ! } ! } ! catch (Exception ex) { ! process.terminate(); ! p.destroy(); ! String message = "Unexpected error setting up the debugger"; ! if (ex instanceof SocketTimeoutException) ! message = "Timed out after " + Float.toString(config.acceptTimeout/1000) + " seconds while waiting for python script to connect."; ! throw new CoreException(PydevDebugPlugin.makeStatus(IStatus.ERROR, message, ex)); ! } ! subMonitor.subTask("Done"); ! // hook up debug model, and we are off & running ! PyDebugTarget t = new PyDebugTarget(launch, process, config.resource, debugger); ! launch.setSourceLocator(new PySourceLocator()); ! debugger.startTransmission(); // this starts reading/writing from sockets ! t.initialize(); ! t.addConsoleInputListener(); ! } private static IProcess doIt(PythonRunnerConfig config, IProgressMonitor monitor, String [] envp, String[] cmdLine, File workingDirectory, ILaunch launch) throws CoreException{ if (monitor == null) ! monitor = new NullProgressMonitor(); IProgressMonitor subMonitor = new SubProgressMonitor(monitor, 5); subMonitor.beginTask("Launching python", 1); ! // Launch & connect to the debugger subMonitor.subTask("Constructing command_line..."); String commandLineAsString = SimpleRunner.getArgumentsAsStr(cmdLine); --- 113,175 ---- }); } ! } ! /** ! * Launches the config in the debug mode. ! * ! * Loosely modeled upon Ant launcher. ! * @throws JDTNotAvailableException ! */ ! private static void runDebug(PythonRunnerConfig config, ILaunch launch, IProgressMonitor monitor) throws CoreException, IOException, JDTNotAvailableException { ! if (monitor == null) ! monitor = new NullProgressMonitor(); ! IProgressMonitor subMonitor = new SubProgressMonitor(monitor, 5); ! subMonitor.beginTask("Launching python", 1); ! ! // Launch & connect to the debugger ! RemoteDebugger debugger = new RemoteDebugger(config); ! debugger.startConnect(subMonitor); ! subMonitor.subTask("Constructing command_line..."); ! String[] cmdLine = config.getCommandLine(true); ! Process p = createProcess(launch, config.envp, cmdLine, config.workingDirectory); ! checkProcess(p); ! ! IProcess process = registerWithDebugPlugin(config, launch, p); checkProcess(p, process); ! subMonitor.subTask("Waiting for connection..."); ! try { ! boolean userCanceled = debugger.waitForConnect(subMonitor, p, process); ! if (userCanceled) { ! debugger.dispose(); ! return; ! } ! } ! catch (Exception ex) { ! process.terminate(); ! p.destroy(); ! String message = "Unexpected error setting up the debugger"; ! if (ex instanceof SocketTimeoutException) ! message = "Timed out after " + Float.toString(config.acceptTimeout/1000) + " seconds while waiting for python script to connect."; ! throw new CoreException(PydevDebugPlugin.makeStatus(IStatus.ERROR, message, ex)); ! } ! subMonitor.subTask("Done"); ! // hook up debug model, and we are off & running ! PyDebugTarget t = new PyDebugTarget(launch, process, config.resource, debugger); ! launch.setSourceLocator(new PySourceLocator()); ! debugger.startTransmission(); // this starts reading/writing from sockets ! t.initialize(); ! t.addConsoleInputListener(); ! } private static IProcess doIt(PythonRunnerConfig config, IProgressMonitor monitor, String [] envp, String[] cmdLine, File workingDirectory, ILaunch launch) throws CoreException{ if (monitor == null) ! monitor = new NullProgressMonitor(); IProgressMonitor subMonitor = new SubProgressMonitor(monitor, 5); subMonitor.beginTask("Launching python", 1); ! // Launch & connect to the debugger subMonitor.subTask("Constructing command_line..."); String commandLineAsString = SimpleRunner.getArgumentsAsStr(cmdLine); *************** *** 182,186 **** //it was dying before register, so, I made this faster to see if this fixes it ! Process p = createProcess(launch, envp, cmdLine, workingDirectory); checkProcess(p); --- 182,186 ---- //it was dying before register, so, I made this faster to see if this fixes it ! Process p = createProcess(launch, envp, cmdLine, workingDirectory); checkProcess(p); *************** *** 189,193 **** if(config.isJython()) { if(config.isInteractive){ ! throw new RuntimeException("Interactive not supported here!"); } process = registerWithDebugPluginForProcessType(label, launch, p, processAttributes, "java"); --- 189,193 ---- if(config.isJython()) { if(config.isInteractive){ ! throw new RuntimeException("Interactive not supported here!"); } process = registerWithDebugPluginForProcessType(label, launch, p, processAttributes, "java"); *************** *** 197,201 **** //in the debug plugin (the communication is all done through xml-rpc). if(config.isInteractive){ ! throw new RuntimeException("Interactive not supported here!"); } process = registerWithDebugPlugin(label, launch, p, processAttributes); --- 197,201 ---- //in the debug plugin (the communication is all done through xml-rpc). if(config.isInteractive){ ! throw new RuntimeException("Interactive not supported here!"); } process = registerWithDebugPlugin(label, launch, p, processAttributes); *************** *** 212,216 **** */ private static Process createProcess(ILaunch launch, String[] envp, String[] cmdLine, File workingDirectory) throws CoreException { ! //Not using DebugPlugin.ATTR_CONSOLE_ENCODING to provide backward compatibility for eclipse 3.2 String encoding = launch.getAttribute(IDebugUIConstants.ATTR_CONSOLE_ENCODING); if(encoding != null && encoding.trim().length() > 0){ --- 212,216 ---- */ private static Process createProcess(ILaunch launch, String[] envp, String[] cmdLine, File workingDirectory) throws CoreException { ! //Not using DebugPlugin.ATTR_CONSOLE_ENCODING to provide backward compatibility for eclipse 3.2 String encoding = launch.getAttribute(IDebugUIConstants.ATTR_CONSOLE_ENCODING); if(encoding != null && encoding.trim().length() > 0){ *************** *** 225,241 **** private static void runUnitTest(PythonRunnerConfig config, ILaunch launch, IProgressMonitor monitor) throws CoreException, JDTNotAvailableException{ ! doIt(config, monitor, config.envp, config.getCommandLine(true), config.workingDirectory, launch); } /** ! * The debug plugin needs to be notified about our process. ! * It'll then display the appropriate UI. * @throws JDTNotAvailableException ! */ ! private static IProcess registerWithDebugPlugin(PythonRunnerConfig config, ILaunch launch, Process p) throws JDTNotAvailableException { ! HashMap<Object, Object> processAttributes = new HashMap<Object, Object>(); ! processAttributes.put(IProcess.ATTR_CMDLINE, config.getCommandLineAsString()); ! return registerWithDebugPlugin(config.getRunningName(), launch,p, processAttributes); ! } --- 225,241 ---- private static void runUnitTest(PythonRunnerConfig config, ILaunch launch, IProgressMonitor monitor) throws CoreException, JDTNotAvailableException{ ! doIt(config, monitor, config.envp, config.getCommandLine(true), config.workingDirectory, launch); } /** ! * The debug plugin needs to be notified about our process. ! * It'll then display the appropriate UI. * @throws JDTNotAvailableException ! */ ! private static IProcess registerWithDebugPlugin(PythonRunnerConfig config, ILaunch launch, Process p) throws JDTNotAvailableException { ! HashMap<Object, Object> processAttributes = new HashMap<Object, Object>(); ! processAttributes.put(IProcess.ATTR_CMDLINE, config.getCommandLineAsString()); ! return registerWithDebugPlugin(config.getRunningName(), launch,p, processAttributes); ! } *************** *** 247,263 **** return registerWithDebugPluginForProcessType(label, launch, p, processAttributes, Constants.PROCESS_TYPE); } ! ! /** ! * The debug plugin needs to be notified about our process. ! * It'll then display the appropriate UI. ! */ private static IProcess registerWithDebugPluginForProcessType(String label, ILaunch launch, Process p, Map<Object, Object> processAttributes, String processType) { ! processAttributes.put(IProcess.ATTR_PROCESS_TYPE, processType); ! processAttributes.put(IProcess.ATTR_PROCESS_LABEL, label); processAttributes.put(DebugPlugin.ATTR_CAPTURE_OUTPUT, "true"); ! return DebugPlugin.newProcess(launch,p, label, processAttributes); ! } } --- 247,263 ---- return registerWithDebugPluginForProcessType(label, launch, p, processAttributes, Constants.PROCESS_TYPE); } ! ! /** ! * The debug plugin needs to be notified about our process. ! * It'll then display the appropriate UI. ! */ private static IProcess registerWithDebugPluginForProcessType(String label, ILaunch launch, Process p, Map<Object, Object> processAttributes, String processType) { ! processAttributes.put(IProcess.ATTR_PROCESS_TYPE, processType); ! processAttributes.put(IProcess.ATTR_PROCESS_LABEL, label); processAttributes.put(DebugPlugin.ATTR_CAPTURE_OUTPUT, "true"); ! return DebugPlugin.newProcess(launch,p, label, processAttributes); ! } } Index: PythonRunnerConfig.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/ui/launching/PythonRunnerConfig.java,v retrieving revision 1.67 retrieving revision 1.68 diff -C2 -d -r1.67 -r1.68 *** PythonRunnerConfig.java 17 Aug 2008 00:26:56 -0000 1.67 --- PythonRunnerConfig.java 27 Sep 2008 19:59:08 -0000 1.68 *************** *** 59,78 **** public static final String RUN_JYTHON = "jython regular run"; ! public IProject project; ! public IPath[] resource; ! public IPath interpreter; ! public String interpreterLocation; ! private String arguments; ! public File workingDirectory; ! public String pythonpathUsed; ! // debugging ! public boolean isDebug; ! public boolean isInteractive; ! private int debugPort = 0; // use getDebugPort ! public int acceptTimeout = 5000; // miliseconds ! public String[] envp = null; ! private String run; ! private ILaunchConfiguration configuration; public boolean isCoverage(){ --- 59,81 ---- public static final String RUN_JYTHON = "jython regular run"; ! public final IProject project; ! public final IPath[] resource; ! public final IPath interpreter; ! public final String interpreterLocation; ! private final String arguments; ! public final File workingDirectory; ! public String pythonpathUsed; ! // debugging ! public final boolean isDebug; ! public final boolean isInteractive; ! private int debugPort = 0; // use getDebugPort ! public int acceptTimeout = 5000; // miliseconds ! public String[] envp = null; ! private final boolean useUnittestWrapper; ! ! /** One of RUN_ enums */ ! private final String run; ! private final ILaunchConfiguration configuration; public boolean isCoverage(){ *************** *** 94,129 **** ! /** ! * Expands and returns the location attribute of the given launch ! * configuration. The location is ! * verified to point to an existing file, in the local file system. * * @param configuration launch configuration ! * @return an absolute path to a file in the local file system ! * @throws CoreException if unable to retrieve the associated launch ! * configuration attribute, if unable to resolve any variables, or if the ! * resolved location does not point to an existing file in the local file ! * system */ public static IPath[] getLocation(ILaunchConfiguration configuration) throws CoreException { ! String locationsStr = configuration.getAttribute(Constants.ATTR_LOCATION, (String) null); ! if (locationsStr == null) { throw new CoreException(PydevDebugPlugin.makeStatus(IStatus.ERROR, "Unable to get location for run", null)); - } else { - String[] locations = StringUtils.split(locationsStr, '|'); - Path[] ret = new Path[locations.length]; - int i=0; - for(String location:locations){ - String expandedLocation = getStringVariableManager().performStringSubstitution(location); - if (expandedLocation == null || expandedLocation.length() == 0) { - throw new CoreException(PydevDebugPlugin.makeStatus(IStatus.ERROR, "Unable to get expanded location for run", null)); - } else { - ret[i] = new Path(expandedLocation); - } - i++; - } - return ret; } } --- 97,134 ---- ! /* ! * Expands and returns the location attribute of the given launch configuration. The location is verified to point ! * to an existing file, in the local file system. * * @param configuration launch configuration ! * ! * @return an absolute path to a file in the local file system ! * ! * @throws CoreException if unable to retrieve the associated launch configuration attribute, if unable to resolve ! * any variables, or if the resolved location does not point to an existing file in the local file system */ public static IPath[] getLocation(ILaunchConfiguration configuration) throws CoreException { ! String locationsStr = configuration.getAttribute(Constants.ATTR_ALTERNATE_LOCATION, (String) null); ! if (locationsStr == null) { ! locationsStr = configuration.getAttribute(Constants.ATTR_LOCATION, (String) null); ! } if (locationsStr == null) { throw new CoreException(PydevDebugPlugin.makeStatus(IStatus.ERROR, "Unable to get location for run", null)); } + + String[] locations = StringUtils.split(locationsStr, '|'); + Path[] ret = new Path[locations.length]; + int i = 0; + for (String location : locations) { + String expandedLocation = getStringVariableManager().performStringSubstitution(location); + if (expandedLocation == null || expandedLocation.length() == 0) { + throw new CoreException(PydevDebugPlugin.makeStatus(IStatus.ERROR, + "Unable to get expanded location for run", null)); + } else { + ret[i] = new Path(expandedLocation); + } + i++; + } + return ret; } *************** *** 141,146 **** String arguments = configuration.getAttribute(Constants.ATTR_PROGRAM_ARGUMENTS, ""); if(makeArgumentsVariableSubstitution){ ! return VariablesPlugin.getDefault().getStringVariableManager() ! .performStringSubstitution(arguments); }else{ return arguments; --- 146,151 ---- String arguments = configuration.getAttribute(Constants.ATTR_PROGRAM_ARGUMENTS, ""); if(makeArgumentsVariableSubstitution){ ! return VariablesPlugin.getDefault().getStringVariableManager() ! .performStringSubstitution(arguments); }else{ return arguments; *************** *** 207,227 **** */ public static String getInterpreterLocation(ILaunchConfiguration conf, IPythonNature nature) throws InvalidRunException, CoreException { ! IInterpreterManager interpreterManager = PydevPlugin.getInterpreterManager(nature); String location = conf.getAttribute(Constants.ATTR_INTERPRETER, Constants.ATTR_INTERPRETER_DEFAULT); ! if (location != null && location.equals(Constants.ATTR_INTERPRETER_DEFAULT)){ ! location = interpreterManager.getDefaultInterpreter(); ! }else if(interpreterManager.hasInfoOnInterpreter(location) == false){ ! File file = new File(location); ! if(!file.exists()){ ! throw new InvalidRunException("Error. The interprer: "+location+" does not exist"); ! ! }else{ ! throw new InvalidRunException("Error. The interprer: "+location+" is not configured in the pydev preferences as a valid '"+nature.getVersion()+"' interpreter."); ! } } ! return location; ! } --- 212,232 ---- */ public static String getInterpreterLocation(ILaunchConfiguration conf, IPythonNature nature) throws InvalidRunException, CoreException { ! IInterpreterManager interpreterManager = PydevPlugin.getInterpreterManager(nature); String location = conf.getAttribute(Constants.ATTR_INTERPRETER, Constants.ATTR_INTERPRETER_DEFAULT); ! if (location != null && location.equals(Constants.ATTR_INTERPRETER_DEFAULT)){ ! location = interpreterManager.getDefaultInterpreter(); ! }else if(interpreterManager.hasInfoOnInterpreter(location) == false){ ! File file = new File(location); ! if(!file.exists()){ ! throw new InvalidRunException("Error. The interprer: "+location+" does not exist"); ! ! }else{ ! throw new InvalidRunException("Error. The interprer: "+location+" is not configured in the pydev preferences as a valid '"+nature.getVersion()+"' interpreter."); ! } } ! return location; ! } *************** *** 295,310 **** } ! /** ! * Sets defaults. ! * @throws InvalidRunException ! */ ! @SuppressWarnings("unchecked") public PythonRunnerConfig(ILaunchConfiguration conf, String mode, String run, boolean makeArgumentsVariableSubstitution) throws CoreException, InvalidRunException { ! //1st thing, see if this is a valid run. project = getProjectFromConfiguration(conf); if(project == null){ //Ok, we could not find it out ! CoreException e = PydevPlugin.log("Could not get project for resource: "+resource); ! throw e; } --- 300,314 ---- } ! /** ! * Sets defaults. ! * @throws InvalidRunException ! */ ! @SuppressWarnings("unchecked") public PythonRunnerConfig(ILaunchConfiguration conf, String mode, String run, boolean makeArgumentsVariableSubstitution) throws CoreException, InvalidRunException { ! //1st thing, see if this is a valid run. project = getProjectFromConfiguration(conf); if(project == null){ //Ok, we could not find it out ! throw PydevPlugin.log("Could not get project for configuration: " + conf); } *************** *** 316,321 **** } - - if(pythonNature.isJython()){ if(!run.equals(RUN_JYTHON) && !run.equals(RUN_JYTHON_UNITTEST)){ --- 320,323 ---- *************** *** 334,356 **** } ! ! ! //now, go on configuring other things ! this.configuration = conf; this.run = run; ! isDebug = mode.equals(ILaunchManager.DEBUG_MODE); ! isInteractive = mode.equals("interactive"); ! resource = getLocation(conf); ! arguments = getArguments(conf, makeArgumentsVariableSubstitution); ! IPath workingPath = getWorkingDirectory(conf); ! workingDirectory = workingPath == null ? null : workingPath.toFile(); ! acceptTimeout = PydevPrefs.getPreferences().getInt(PydevPrefs.CONNECT_TIMEOUT); interpreterLocation = getInterpreterLocation(conf, pythonNature); ! interpreter = getInterpreter(conf, pythonNature); //make the environment ! ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager(); envp = launchManager.getEnvironment(conf); --- 336,360 ---- } ! ! ! //now, go on configuring other things ! this.configuration = conf; this.run = run; ! isDebug = mode.equals(ILaunchManager.DEBUG_MODE); ! isInteractive = mode.equals("interactive"); ! useUnittestWrapper = !run.equals(RUN_UNITTEST) || ! !conf.getAttribute(Constants.ATTR_NO_UNITTEST_WRAPPER, false); ! resource = getLocation(conf); ! arguments = getArguments(conf, makeArgumentsVariableSubstitution); ! IPath workingPath = getWorkingDirectory(conf); ! workingDirectory = workingPath == null ? null : workingPath.toFile(); ! acceptTimeout = PydevPrefs.getPreferences().getInt(PydevPrefs.CONNECT_TIMEOUT); interpreterLocation = getInterpreterLocation(conf, pythonNature); ! interpreter = getInterpreter(conf, pythonNature); //make the environment ! ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager(); envp = launchManager.getEnvironment(conf); *************** *** 361,476 **** pythonpathUsed = SimpleRunner.makePythonPathEnvString(pythonNature, interpreterLocation); }else{ ! boolean win32= Platform.getOS().equals(org.eclipse.osgi.service.environment.Constants.OS_WIN32); ! //ok, the user has done something to configure it, so, just add the pythonpath to the //current env (if he still didn't do so) ! Map envMap = conf.getAttribute(ILaunchManager.ATTR_ENVIRONMENT_VARIABLES, (Map)null); ! if(!specifiedPythonpath(envMap)){ ! ! String pythonpath = SimpleRunner.makePythonPathEnvString(pythonNature, interpreterLocation); pythonpathUsed = pythonpath; ! //override it if it was the ambient pythonpath ! for (int i = 0; i < envp.length; i++) { ! if(win32){ //case insensitive ! if(envp[i].toUpperCase().startsWith("PYTHONPATH")){ ! //OK, finish it. ! envp[i] = "PYTHONPATH="+pythonpath; ! return; ! } ! }else{ ! if(envp[i].startsWith("PYTHONPATH")){ ! //OK, finish it. ! envp[i] = "PYTHONPATH="+pythonpath; ! return; ! } ! } ! ! } ! ! //there was no pythonpath, let's set it ! String[] s = new String[envp.length+1]; ! System.arraycopy(envp, 0, s, 0, envp.length); ! s[s.length-1] = "PYTHONPATH="+pythonpath; ! envp = s; ! ! } } ! } ! /** ! * @param envMap ! * @return */ private boolean specifiedPythonpath(Map<String, String> envMap) { ! if(envMap == null){ return false; ! ! }else{ ! boolean win32= Platform.getOS().equals(org.eclipse.osgi.service.environment.Constants.OS_WIN32); ! ! for (Iterator<String> iter = envMap.keySet().iterator(); iter.hasNext();) { ! String s = iter.next(); ! if(win32){ ! if(s.toUpperCase().equals("PYTHONPATH")){ ! return true; ! } ! }else{ ! if(s.equals("PYTHONPATH")){ ! return true; ! } ! } ! } } - return false; } public int getDebugPort() throws CoreException { ! if (debugPort == 0) { ! debugPort= SocketUtil.findUnusedLocalPort(); ! if (debugPort == -1) ! throw new CoreException(PydevDebugPlugin.makeStatus(IStatus.ERROR, "Could not find a free socket for debugger", null)); ! } ! return debugPort; ! } public static String getRunningName(IPath[] paths) { ! FastStringBuffer buf = new FastStringBuffer(20*paths.length); ! for(IPath p:paths){ ! if(buf.length() > 0){ ! buf.append(" - "); ! } ! buf.append(p.lastSegment()); ! } ! return buf.toString(); ! } ! public String getRunningName() { ! return getRunningName(resource); ! } ! /** ! * @throws CoreException if arguments are inconsistent ! */ ! public void verify() throws CoreException { ! if (resource == null || interpreter == null){ ! throw new CoreException(PydevDebugPlugin.makeStatus(IStatus.ERROR, "Invalid PythonRunnerConfig",null)); } ! if (isDebug && ( acceptTimeout < 0|| debugPort < 0) ){ ! throw new CoreException(PydevDebugPlugin.makeStatus(IStatus.ERROR, "Invalid PythonRunnerConfig",null)); } ! } ! /** * @return ! * @throws CoreException */ public static String getCoverageScript() throws CoreException { --- 365,476 ---- pythonpathUsed = SimpleRunner.makePythonPathEnvString(pythonNature, interpreterLocation); }else{ ! boolean win32= Platform.getOS().equals(org.eclipse.osgi.service.environment.Constants.OS_WIN32); ! //ok, the user has done something to configure it, so, just add the pythonpath to the //current env (if he still didn't do so) ! Map envMap = conf.getAttribute(ILaunchManager.ATTR_ENVIRONMENT_VARIABLES, (Map)null); ! if(!specifiedPythonpath(envMap)){ ! ! String pythonpath = SimpleRunner.makePythonPathEnvString(pythonNature, interpreterLocation); pythonpathUsed = pythonpath; ! //override it if it was the ambient pythonpath ! for (int i = 0; i < envp.length; i++) { ! if(win32){ //case insensitive ! if(envp[i].toUpperCase().startsWith("PYTHONPATH")){ ! //OK, finish it. ! envp[i] = "PYTHONPATH="+pythonpath; ! return; ! } ! }else{ ! if(envp[i].startsWith("PYTHONPATH")){ ! //OK, finish it. ! envp[i] = "PYTHONPATH="+pythonpath; ! return; ! } ! } ! ! } ! ! //there was no pythonpath, let's set it ! String[] s = new String[envp.length+1]; ! System.arraycopy(envp, 0, s, 0, envp.length); ! s[s.length-1] = "PYTHONPATH="+pythonpath; ! envp = s; ! ! } } ! } ! /** ! * Check if map contains PYTHONPATH key. ! * ! * Variables names are considered not case sensitive on Windows. ! * ! * @param envMap mapping of env variables and their values ! * @return {@code true} if passed map contain PYTHONPATH key. */ private boolean specifiedPythonpath(Map<String, String> envMap) { ! if (envMap == null) { return false; ! } ! boolean win32 = Platform.getOS().equals(org.eclipse.osgi.service.environment.Constants.OS_WIN32); ! if (!win32) { ! return envMap.containsKey("PYTHONPATH"); ! } ! for (Iterator<String> iter = envMap.keySet().iterator(); iter.hasNext();) { ! String s = iter.next(); ! if (s.toUpperCase().equals("PYTHONPATH")) { ! return true; } } return false; } public int getDebugPort() throws CoreException { ! if (debugPort == 0) { ! debugPort= SocketUtil.findUnusedLocalPort(); ! if (debugPort == -1) ! throw new CoreException(PydevDebugPlugin.makeStatus(IStatus.ERROR, "Could not find a free socket for debugger", null)); ! } ! return debugPort; ! } public static String getRunningName(IPath[] paths) { ! FastStringBuffer buf = new FastStringBuffer(20*paths.length); ! for(IPath p:paths){ ! if(buf.length() > 0){ ! buf.append(" - "); ! } ! buf.append(p.lastSegment()); ! } ! return buf.toString(); ! } ! public String getRunningName() { ! return getRunningName(resource); ! } ! /** ! * @throws CoreException if arguments are inconsistent ! */ ! public void verify() throws CoreException { ! if (resource == null || interpreter == null){ ! throw new CoreException(PydevDebugPlugin.makeStatus(IStatus.ERROR, "Invalid PythonRunnerConfig",null)); } ! if (isDebug && ( acceptTimeout < 0|| debugPort < 0) ){ ! throw new CoreException(PydevDebugPlugin.makeStatus(IStatus.ERROR, "Invalid PythonRunnerConfig",null)); } ! } ! /** * @return ! * @throws CoreException */ public static String getCoverageScript() throws CoreException { *************** *** 478,505 **** } - public static String getUnitTestScript() throws CoreException { - return REF.getFileAbsolutePath(PydevDebugPlugin.getScriptWithinPySrc("SocketTestRunner.py")); - } - /** ! * gets location of jpydaemon.py ! */ ! public static String getDebugScript() throws CoreException { ! return REF.getFileAbsolutePath(PydevDebugPlugin.getScriptWithinPySrc("pydevd.py")); ! } ! private String getRunFilesScript() throws CoreException { return REF.getFileAbsolutePath(PydevDebugPlugin.getScriptWithinPySrc("runfiles.py")); } ! /** ! * Create a command line for launching. ! * @return command line ready to be exec'd ! * @throws CoreException ! * @throws JDTNotAvailableException ! */ ! public String[] getCommandLine(boolean makeVariableSubstitution) throws CoreException, JDTNotAvailableException { ! List<String> cmdArgs = new ArrayList<String>(); if(isJython()){ --- 478,501 ---- } /** ! * gets location of jpydaemon.py ! */ ! public static String getDebugScript() throws CoreException { ! return REF.getFileAbsolutePath(PydevDebugPlugin.getScriptWithinPySrc("pydevd.py")); ! } ! public static String getRunFilesScript() throws CoreException { return REF.getFileAbsolutePath(PydevDebugPlugin.getScriptWithinPySrc("runfiles.py")); } ! /** ! * Create a command line for launching. ! * @return command line ready to be exec'd ! * @throws CoreException ! * @throws JDTNotAvailableException ! */ ! public String[] getCommandLine(boolean makeVariableSubstitution) throws CoreException, JDTNotAvailableException { ! List<String> cmdArgs = new ArrayList<String>(); if(isJython()){ *************** *** 519,608 **** // if (project.getNature(Constants.JAVA_NATURE) != null){ ! // cpath = getClasspath(JavaCore.create(project)); // } else { ! cpath = interpreter + SimpleRunner.getPythonPathSeparator() + pythonpathUsed; // } cmdArgs.add(cpath); cmdArgs.add("-Dpython.path="+pythonpathUsed); //will be added to the env variables in the run (check if this works on all platforms...) ! addVmArgs(cmdArgs); ! if (isDebug) { ! cmdArgs.add("-Dpython.security.respectJavaAccessibility=false"); //TODO: the user should configure this -- we use it so that ! //we can access the variables during debugging. ! cmdArgs.add("org.python.util.jython"); ! ! cmdArgs.add(getDebugScript()); ! cmdArgs.add("--vm_type"); ! cmdArgs.add("jython"); ! cmdArgs.add("--client"); ! cmdArgs.add("localhost"); ! cmdArgs.add("--port"); ! cmdArgs.add(Integer.toString(debugPort)); ! cmdArgs.add("--file"); ! }else{ ! cmdArgs.add("org.python.util.jython"); ! } ! ! if(isUnittest()){ ! cmdArgs.add(getRunFilesScript()); ! cmdArgs.add("--verbosity"); ! cmdArgs.add( PydevPrefs.getPreferences().getString(PyunitPrefsPage.PYUNIT_VERBOSITY) ); ! ! String filter = PydevPrefs.getPreferences().getString(PyunitPrefsPage.PYUNIT_TEST_FILTER); ! if (filter.length() > 0) { ! cmdArgs.add("--filter"); ! cmdArgs.add( filter ); ! } ! } }else{ ! cmdArgs.add(interpreter.toOSString()); ! // Next option is for unbuffered stdout, otherwise Eclipse will not see any output until done cmdArgs.add("-u"); addVmArgs(cmdArgs); ! if (isDebug) { ! cmdArgs.add(getDebugScript()); ! cmdArgs.add("--vm_type"); ! cmdArgs.add("python"); ! cmdArgs.add("--client"); ! cmdArgs.add("localhost"); ! cmdArgs.add("--port"); ! cmdArgs.add(Integer.toString(debugPort)); ! cmdArgs.add("--file"); ! } ! ! if(isCoverage()){ ! cmdArgs.add(getCoverageScript()); ! String coverageFileLocation = PyCoverage.getCoverageFileLocation(); cmdArgs.add(coverageFileLocation); ! cmdArgs.add("-x"); ! if (!isFile()){ ! //run all testcases cmdArgs.add(getRunFilesScript()); } ! } ! if(isUnittest()){ ! cmdArgs.add(getRunFilesScript()); ! cmdArgs.add("--verbosity"); ! cmdArgs.add( PydevPrefs.getPreferences().getString(PyunitPrefsPage.PYUNIT_VERBOSITY) ); ! ! String filter = PydevPrefs.getPreferences().getString(PyunitPrefsPage.PYUNIT_TEST_FILTER); ! if (filter.length() > 0) { ! cmdArgs.add("--filter"); ! cmdArgs.add( filter ); ! } ! } } for(IPath p:resource){ ! cmdArgs.add(p.toOSString()); } --- 515,564 ---- // if (project.getNature(Constants.JAVA_NATURE) != null){ ! // cpath = getClasspath(JavaCore.create(project)); // } else { ! cpath = interpreter + SimpleRunner.getPythonPathSeparator() + pythonpathUsed; // } cmdArgs.add(cpath); cmdArgs.add("-Dpython.path="+pythonpathUsed); //will be added to the env variables in the run (check if this works on all platforms...) ! addVmArgs(cmdArgs); ! if (isDebug) { ! cmdArgs.add("-Dpython.security.respectJavaAccessibility=false"); //TODO: the user should configure this -- we use it so that ! //we can access the variables during debugging. ! cmdArgs.add("org.python.util.jython"); ! addDebugArgs(cmdArgs, "jython"); }else{ ! cmdArgs.add("org.python.util.jython"); } ! addUnittestArgs(cmdArgs); }else{ ! cmdArgs.add(interpreter.toOSString()); ! // Next option is for unbuffered stdout, otherwise Eclipse will not see any output until done cmdArgs.add("-u"); addVmArgs(cmdArgs); ! addDebugArgs(cmdArgs, "python"); ! ! if(isCoverage()){ ! cmdArgs.add(getCoverageScript()); ! String coverageFileLocation = PyCoverage.getCoverageFileLocation(); cmdArgs.add(coverageFileLocation); ! cmdArgs.add("-x"); ! if (!isFile()){ ! //run all testcases cmdArgs.add(getRunFilesScript()); } ! } ! addUnittestArgs(cmdArgs); } for(IPath p:resource){ ! cmdArgs.add(p.toOSString()); } *************** *** 617,624 **** } ! String[] retVal = new String[cmdArgs.size()]; ! cmdArgs.toArray(retVal); ! return retVal; ! } /** --- 573,613 ---- } ! String[] retVal = new String[cmdArgs.size()]; ! cmdArgs.toArray(retVal); ! return retVal; ! } ! ! /** ! * Adds a set of arguments used to wrap executed file with unittest runner. ! */ ! private void addUnittestArgs(List<String> cmdArgs) throws CoreException { ! if (isUnittest() && useUnittestWrapper) { ! cmdArgs.add(getRunFilesScript()); ! cmdArgs.add("--verbosity"); ! cmdArgs.add(PydevPrefs.getPreferences().getString(PyunitPrefsPage.PYUNIT_VERBOSITY)); ! ! String filter = PydevPrefs.getPreferences().getString(PyunitPrefsPage.PYUNIT_TEST_FILTER); ! if (filter.length() > 0) { ! cmdArgs.add("--filter"); ! cmdArgs.add(filter); ! } ! } ! } ! ! /** ! * Adds a set of arguments needed for debugging. ! */ ! private void addDebugArgs(List<String> cmdArgs, String vmType) throws CoreException { ! if (isDebug) { ! cmdArgs.add(getDebugScript()); ! cmdArgs.add("--vm_type"); ! cmdArgs.add(vmType); ! cmdArgs.add("--client"); ! cmdArgs.add("localhost"); ! cmdArgs.add("--port"); ! cmdArgs.add(Integer.toString(debugPort)); ! cmdArgs.add("--file"); ! } ! } /** *************** *** 630,645 **** if(vmArguments != null){ for (int i = 0; i < vmArguments.length; i++){ ! cmdArgs.add(vmArguments[i]); } } } ! ! /** ! * @return an array with the vm arguments in the given configuration. ! * @throws CoreException ! */ private String[] getVMArguments(ILaunchConfiguration configuration) throws CoreException { ! String args = configuration.getAttribute(Constants.ATTR_VM_ARGUMENTS, (String) null); if (args != null && args.trim().length() > 0) { String expanded = getStringVariableManager().performStringSubstitution(args); --- 619,634 ---- if(vmArguments != null){ for (int i = 0; i < vmArguments.length; i++){ ! cmdArgs.add(vmArguments[i]); } } } ! ! /** ! * @return an array with the vm arguments in the given configuration. ! * @throws CoreException ! */ private String[] getVMArguments(ILaunchConfiguration configuration) throws CoreException { ! String args = configuration.getAttribute(Constants.ATTR_VM_ARGUMENTS, (String) null); if (args != null && args.trim().length() > 0) { String expanded = getStringVariableManager().performStringSubstitution(args); *************** *** 647,651 **** } return null; ! } /** --- 636,640 ---- } return null; ! } /** *************** *** 654,659 **** * @throws JDTNotAvailableException */ ! public String getCommandLineAsString() throws JDTNotAvailableException { ! String[] args; try { args = getCommandLine(false); --- 643,648 ---- * @throws JDTNotAvailableException */ ! public String getCommandLineAsString() throws JDTNotAvailableException { ! String[] args; try { args = getCommandLine(false); *************** *** 662,666 **** throw new RuntimeException(e); } ! } } --- 651,655 ---- throw new RuntimeException(e); } ! } } Index: AbstractLaunchShortcut.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/ui/launching/AbstractLaunchShortcut.java,v retrieving revision 1.18 retrieving revision 1.19 diff -C2 -d -r1.18 -r1.19 *** AbstractLaunchShortcut.java 17 Aug 2008 00:26:56 -0000 1.18 --- AbstractLaunchShortcut.java 27 Sep 2008 19:59:08 -0000 1.19 *************** *** 224,229 **** } return buffer.toString(); ! // E3 IStringVariableManager varManager = VariablesPlugin.getDefault().getStringVariableManager(); ! // E3 return varManager.generateVariableExpression("workspace_loc", file.getFullPath().toString()); } --- 224,229 ---- } return buffer.toString(); ! // E3 IStringVariableManager varManager = VariablesPlugin.getDefault().getStringVariableManager(); ! // E3 return varManager.generateVariableExpression("workspace_loc", file.getFullPath().toString()); } *************** *** 342,351 **** FastStringBuffer moduleFile = new FastStringBuffer(80*resource.length); for(IResource r:resource){ ! String m = r.getFullPath().makeRelative().toString(); ! m = varManager.generateVariableExpression("workspace_loc", m); ! if(moduleFile.length() > 0){ ! moduleFile.append("|"); ! } ! moduleFile.append(m); } return moduleFile.toString(); --- 342,351 ---- FastStringBuffer moduleFile = new FastStringBuffer(80*resource.length); for(IResource r:resource){ ! String m = r.getFullPath().makeRelative().toString(); ! m = varManager.generateVariableExpression("workspace_loc", m); ! if(moduleFile.length() > 0){ ! moduleFile.append("|"); ! } ! moduleFile.append(m); } return moduleFile.toString(); |
Update of /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/model/remote In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv20604/src/org/python/pydev/debug/model/remote Modified Files: DebuggerWriter.java ThreadKillCommand.java StepCommand.java ChangeVariableCommand.java AbstractDebuggerCommand.java ThreadRunCommand.java RunCommand.java RemoveBreakpointCommand.java AbstractRemoteDebugger.java DebuggerReader.java EvaluateExpressionCommand.java RemoteDebugger.java ThreadListCommand.java VersionCommand.java ThreadSuspendCommand.java AbstractListenConnector.java GetFrameCommand.java GetVariableCommand.java ICommandResponseListener.java SetBreakpointCommand.java ListenConnector.java Log Message: Synching to latest changes: Pydev <ul> <li><strong>Editor</strong>: Cursor settings no longer overridden</li> <li><strong>Code-completion</strong>: If __all__ is defined with runtime elements (and not only in a single assign statement), it's ignored for code-completion purposes</li> <li><strong>Debugger</strong>: Pythonpath the same in debug and regular modes (sys.path[0] is the same directory as the file run)</li> <li><strong>Debugger</strong>: Persist choices done in the debugger when files from the debugger are not found</li> <li><strong>Interpreter config</strong>: "email" automatically added to the "forced builtins"</li> <li><strong>Parser</strong>: Correctly recognizing absolute import with 3 or more levels</li> <li><strong>Syntax check</strong>: Option to do only on active editor</li> </ul> Also: tabs changed for spaces Index: RemoteDebugger.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/model/remote/RemoteDebugger.java,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** RemoteDebugger.java 17 Apr 2006 02:06:17 -0000 1.11 --- RemoteDebugger.java 27 Sep 2008 19:59:06 -0000 1.12 *************** *** 20,135 **** * Network interface to the remote debugger. */ ! public class RemoteDebugger extends AbstractRemoteDebugger { ! private ListenConnector connector; // Runnable that connects to the debugger ! private Thread connectThread; // ! private PythonRunnerConfig config; ! public RemoteDebugger(PythonRunnerConfig config) { ! this.config = config; ! } ! public void startConnect(IProgressMonitor monitor) throws IOException, CoreException { ! monitor.subTask("Finding free socket..."); ! connector = new ListenConnector(config.getDebugPort(), config.acceptTimeout); ! connectThread = new Thread(connector, "pydevd.connect"); ! connectThread.start(); ! } ! ! /** ! * Wait for the connection to the debugger to complete. ! * ! * If this method returns without an exception, we've connected. ! * @return true if operation was cancelled by user ! */ ! public boolean waitForConnect(IProgressMonitor monitor, Process p, IProcess ip) throws Exception { ! // Launch the debug listener on a thread, and wait until it completes ! while (connectThread.isAlive()) { ! if (monitor.isCanceled()) { ! connector.stopListening(); ! p.destroy(); ! return true; ! } ! try { ! p.exitValue(); // throws exception if process has terminated ! // process has terminated - stop waiting for a connection ! connector.stopListening(); ! String errorMessage= ip.getStreamsProxy().getErrorStreamMonitor().getContents(); ! if (errorMessage.length() != 0){ ! // not sure if this is really an error ! throw new CoreException(PydevDebugPlugin.makeStatus(IStatus.ERROR, "Something got printed in the error stream", null)); } ! } catch (IllegalThreadStateException e) { ! // expected while process is alive ! } ! try { ! Thread.sleep(100); ! } catch (InterruptedException e) { ! } ! } ! if (connector.getException() != null){ ! throw connector.getException(); ! } ! connected(connector.getSocket()); ! return false; ! } ! ! /** ! * Remote debugger has connected ! */ ! private void connected(Socket socket) throws IOException { ! this.socket = socket; ! } ! ! public void disconnect() { ! if (socket != null) { ! try { ! socket.shutdownInput(); // trying to make my pydevd notice that the socket is gone ! } catch (Exception e) { ! // ok, ignore ! } ! try { ! socket.shutdownOutput(); ! } catch (Exception e) { ! // ok, ignore ! } ! try { ! socket.close(); ! } catch (Exception e) { ! // ok, ignore ! } ! } ! socket = null; ! if (target != null){ ! target.debuggerDisconnected(); } - } - - /** - * Dispose must be called to clean up. - * Because we call this from PyDebugTarget.terminate, we can be called multiple times - * But, once dispose() is called, no other calls will be made. - */ - public void dispose() { - if (connector != null) { - connector.stopListening(); - connector = null; - } - if (writer != null) { - writer.done(); - writer = null; - } - if (reader != null) { - reader.done(); - reader = null; - } try { ! if(target != null){ ! target.terminate(); ! } } catch (DebugException e) { throw new RuntimeException(e); } ! target = null; ! } } --- 20,135 ---- * Network interface to the remote debugger. */ ! public class RemoteDebugger extends AbstractRemoteDebugger { ! private ListenConnector connector; // Runnable that connects to the debugger ! private Thread connectThread; // ! private PythonRunnerConfig config; ! public RemoteDebugger(PythonRunnerConfig config) { ! this.config = config; ! } ! public void startConnect(IProgressMonitor monitor) throws IOException, CoreException { ! monitor.subTask("Finding free socket..."); ! connector = new ListenConnector(config.getDebugPort(), config.acceptTimeout); ! connectThread = new Thread(connector, "pydevd.connect"); ! connectThread.start(); ! } ! ! /** ! * Wait for the connection to the debugger to complete. ! * ! * If this method returns without an exception, we've connected. ! * @return true if operation was cancelled by user ! */ ! public boolean waitForConnect(IProgressMonitor monitor, Process p, IProcess ip) throws Exception { ! // Launch the debug listener on a thread, and wait until it completes ! while (connectThread.isAlive()) { ! if (monitor.isCanceled()) { ! connector.stopListening(); ! p.destroy(); ! return true; ! } ! try { ! p.exitValue(); // throws exception if process has terminated ! // process has terminated - stop waiting for a connection ! connector.stopListening(); ! String errorMessage= ip.getStreamsProxy().getErrorStreamMonitor().getContents(); ! if (errorMessage.length() != 0){ ! // not sure if this is really an error ! throw new CoreException(PydevDebugPlugin.makeStatus(IStatus.ERROR, "Something got printed in the error stream", null)); } ! } catch (IllegalThreadStateException e) { ! // expected while process is alive ! } ! try { ! Thread.sleep(100); ! } catch (InterruptedException e) { ! } ! } ! if (connector.getException() != null){ ! throw connector.getException(); ! } ! connected(connector.getSocket()); ! return false; ! } ! ! /** ! * Remote debugger has connected ! */ ! private void connected(Socket socket) throws IOException { ! this.socket = socket; ! } ! ! public void disconnect() { ! if (socket != null) { ! try { ! socket.shutdownInput(); // trying to make my pydevd notice that the socket is gone ! } catch (Exception e) { ! // ok, ignore ! } ! try { ! socket.shutdownOutput(); ! } catch (Exception e) { ! // ok, ignore ! } ! try { ! socket.close(); ! } catch (Exception e) { ! // ok, ignore ! } ! } ! socket = null; ! if (target != null){ ! target.debuggerDisconnected(); ! } ! } ! ! /** ! * Dispose must be called to clean up. ! * Because we call this from PyDebugTarget.terminate, we can be called multiple times ! * But, once dispose() is called, no other calls will be made. ! */ ! public void dispose() { ! if (connector != null) { ! connector.stopListening(); ! connector = null; ! } ! if (writer != null) { ! writer.done(); ! writer = null; ! } ! if (reader != null) { ! reader.done(); ! reader = null; } try { ! if(target != null){ ! target.terminate(); ! } } catch (DebugException e) { throw new RuntimeException(e); } ! target = null; ! } } Index: GetVariableCommand.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/model/remote/GetVariableCommand.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** GetVariableCommand.java 20 Jan 2006 13:24:42 -0000 1.4 --- GetVariableCommand.java 27 Sep 2008 19:59:06 -0000 1.5 *************** *** 18,68 **** public class GetVariableCommand extends AbstractDebuggerCommand { ! String locator; ! boolean isError = false; ! int responseCode; ! String payload; ! public GetVariableCommand(AbstractRemoteDebugger debugger, String locator) { ! super(debugger); ! this.locator = locator; ! } ! public String getOutgoing() { ! return makeCommand(getCommandId(), sequence, locator); ! } ! public boolean needResponse() { ! return true; ! } ! public void processOKResponse(int cmdCode, String payload) { ! responseCode = cmdCode; ! if (cmdCode == getCommandId()) ! this.payload = payload; ! else { ! isError = true; ! PydevDebugPlugin.log(IStatus.ERROR, "Unexpected response to "+this.getClass(), null); ! } ! } ! protected int getCommandId() { ! return CMD_GET_VARIABLE; ! } ! ! public void processErrorResponse(int cmdCode, String payload) { ! responseCode = cmdCode; ! this.payload = payload; ! isError = true; ! } ! ! public String getResponse() throws CoreException { ! if (isError) ! throw new CoreException( ! PydevDebugPlugin.makeStatus(IStatus.ERROR, ! "pydevd error:" + payload , ! null)); ! else ! return payload; ! } } --- 18,68 ---- public class GetVariableCommand extends AbstractDebuggerCommand { ! String locator; ! boolean isError = false; ! int responseCode; ! String payload; ! public GetVariableCommand(AbstractRemoteDebugger debugger, String locator) { ! super(debugger); ! this.locator = locator; ! } ! public String getOutgoing() { ! return makeCommand(getCommandId(), sequence, locator); ! } ! public boolean needResponse() { ! return true; ! } ! public void processOKResponse(int cmdCode, String payload) { ! responseCode = cmdCode; ! if (cmdCode == getCommandId()) ! this.payload = payload; ! else { ! isError = true; ! PydevDebugPlugin.log(IStatus.ERROR, "Unexpected response to "+this.getClass(), null); ! } ! } ! protected int getCommandId() { ! return CMD_GET_VARIABLE; ! } ! ! public void processErrorResponse(int cmdCode, String payload) { ! responseCode = cmdCode; ! this.payload = payload; ! isError = true; ! } ! ! public String getResponse() throws CoreException { ! if (isError) ! throw new CoreException( ! PydevDebugPlugin.makeStatus(IStatus.ERROR, ! "pydevd error:" + payload , ! null)); ! else ! return payload; ! } } Index: DebuggerReader.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/model/remote/DebuggerReader.java,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** DebuggerReader.java 17 Apr 2006 02:06:17 -0000 1.6 --- DebuggerReader.java 27 Sep 2008 19:59:06 -0000 1.7 *************** *** 7,10 **** --- 7,11 ---- import java.net.Socket; import java.net.URLDecoder; + import java.util.Dictionary; import java.util.Hashtable; *************** *** 18,24 **** */ public class DebuggerReader implements Runnable { ! /** * can be specified to debug this class ! */ private static final boolean DEBUG = false; --- 19,25 ---- */ public class DebuggerReader implements Runnable { ! /** * can be specified to debug this class ! */ private static final boolean DEBUG = false; *************** *** 29,51 **** /** ! * means that we are done */ ! private boolean done = false; /** * commands waiting for response. Their keys are the sequence ids */ ! private Hashtable responseQueue = new Hashtable(); /** * we read from this */ ! private BufferedReader in; /** * that's the debugger that made us... we have to finish it when we are done */ ! private AbstractRemoteDebugger remote; ! /** * Create it --- 30,57 ---- /** ! * Volatile, as multiple threads may ask it to be 'done' */ ! private volatile boolean done = false; ! ! /** ! * Lock object for sleeping. ! */ ! private Object lock = new Object(); /** * commands waiting for response. Their keys are the sequence ids */ ! private Dictionary<Integer, AbstractDebuggerCommand> responseQueue = new Hashtable<Integer, AbstractDebuggerCommand>(); /** * we read from this */ ! private BufferedReader in; /** * that's the debugger that made us... we have to finish it when we are done */ ! private AbstractRemoteDebugger remote; ! /** * Create it *************** *** 56,87 **** * @throws IOException */ ! public DebuggerReader(Socket s, AbstractRemoteDebugger r ) throws IOException { ! remote = r; ! socket = s; ! InputStream sin = socket.getInputStream(); ! in = new BufferedReader(new InputStreamReader(sin)); ! } ! /** * mark things as done */ ! public void done() { ! this.done = true; ! } /** * @param cmd */ ! public void addToResponseQueue(AbstractDebuggerCommand cmd) { ! int sequence = cmd.getSequence(); ! responseQueue.put(new Integer(sequence), cmd); ! } ! ! /** ! * Parses & dispatches the command ! */ ! private void processCommand(String cmdLine) { ! try { ! String[] cmdParsed = cmdLine.split("\t", 3); int cmdCode = Integer.parseInt(cmdParsed[0]); int seqCode = Integer.parseInt(cmdParsed[1]); --- 62,95 ---- * @throws IOException */ ! public DebuggerReader(Socket s, AbstractRemoteDebugger r ) throws IOException { ! remote = r; ! socket = s; ! InputStream sin = socket.getInputStream(); ! in = new BufferedReader(new InputStreamReader(sin)); ! } ! /** * mark things as done */ ! public void done() { ! this.done = true; ! } /** * @param cmd */ ! public void addToResponseQueue(AbstractDebuggerCommand cmd) { ! int sequence = cmd.getSequence(); ! synchronized (responseQueue) { ! responseQueue.put(new Integer(sequence), cmd); ! } ! } ! ! /** ! * Parses & dispatches the command ! */ ! private void processCommand(String cmdLine) { ! try { ! String[] cmdParsed = cmdLine.split("\t", 3); int cmdCode = Integer.parseInt(cmdParsed[0]); int seqCode = Integer.parseInt(cmdParsed[1]); *************** *** 90,94 **** // is there a response waiting ! AbstractDebuggerCommand cmd = (AbstractDebuggerCommand) responseQueue.remove(new Integer(seqCode)); if (cmd == null){ --- 98,105 ---- // is there a response waiting ! AbstractDebuggerCommand cmd; ! synchronized (responseQueue) { ! cmd = (AbstractDebuggerCommand) responseQueue.remove(new Integer(seqCode)); ! } if (cmd == null){ *************** *** 102,109 **** } } catch (Exception e) { ! PydevPlugin.log(e); throw new RuntimeException(e); } ! } /** --- 113,120 ---- } } catch (Exception e) { ! PydevPlugin.log(e); throw new RuntimeException(e); } ! } /** *************** *** 112,127 **** * * @see java.lang.Runnable#run() ! */ ! public void run() { ! while (!done) { ! try { ! String cmdLine = in.readLine(); ! if(cmdLine != null){ ! processCommand(cmdLine); ! } ! synchronized (this) { ! Thread.sleep(50); ! } ! } catch (Exception e1) { done = true; //that's ok, it means that the client finished --- 123,138 ---- * * @see java.lang.Runnable#run() ! */ ! public void run() { ! while (!done) { ! try { ! String cmdLine = in.readLine(); ! if(cmdLine != null){ ! processCommand(cmdLine); ! } ! synchronized(lock) { ! Thread.sleep(50); ! } ! } catch (Exception e1) { done = true; //that's ok, it means that the client finished *************** *** 129,144 **** e1.printStackTrace(); } ! } ! if ((socket == null) || !socket.isConnected() ) { ! AbstractDebugTarget target = remote.getTarget(); if ( target != null) { ! target.debuggerDisconnected(); ! } ! done = true; ! } ! } remote.dispose(); ! } } --- 140,155 ---- e1.printStackTrace(); } ! } ! if ((socket == null) || !socket.isConnected() ) { ! AbstractDebugTarget target = remote.getTarget(); if ( target != null) { ! target.debuggerDisconnected(); ! } ! done = true; ! } ! } remote.dispose(); ! } } Index: ThreadKillCommand.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/model/remote/ThreadKillCommand.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** ThreadKillCommand.java 7 May 2004 02:03:08 -0000 1.2 --- ThreadKillCommand.java 27 Sep 2008 19:59:06 -0000 1.3 *************** *** 12,25 **** public class ThreadKillCommand extends AbstractDebuggerCommand { ! String thread_id; ! ! public ThreadKillCommand(RemoteDebugger debugger, String thread_id) { ! super(debugger); ! this.thread_id = thread_id; ! } ! ! public String getOutgoing() { ! return makeCommand(CMD_THREAD_KILL, sequence, thread_id); ! } } --- 12,25 ---- public class ThreadKillCommand extends AbstractDebuggerCommand { ! String thread_id; ! ! public ThreadKillCommand(RemoteDebugger debugger, String thread_id) { ! super(debugger); ! this.thread_id = thread_id; ! } ! ! public String getOutgoing() { ! return makeCommand(CMD_THREAD_KILL, sequence, thread_id); ! } } Index: ThreadListCommand.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/model/remote/ThreadListCommand.java,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** ThreadListCommand.java 24 Jun 2006 01:45:53 -0000 1.6 --- ThreadListCommand.java 27 Sep 2008 19:59:06 -0000 1.7 *************** *** 21,77 **** public class ThreadListCommand extends AbstractDebuggerCommand { ! boolean done; ! AbstractDebugTarget target; ! PyThread[] threads; ! ! public ThreadListCommand(AbstractRemoteDebugger debugger, AbstractDebugTarget target) { ! super(debugger); ! this.target = target; ! done = false; ! } ! public void waitUntilDone(int timeout) throws InterruptedException { ! while (!done && timeout > 0) { ! timeout -= 100; ! synchronized (this) { ! Thread.sleep(100); ! } ! } ! if (timeout < 0) ! throw new InterruptedException(); ! } ! ! public PyThread[] getThreads() { ! return threads; ! } ! ! public String getOutgoing() { ! return makeCommand(CMD_LIST_THREADS, sequence, ""); ! } ! ! public boolean needResponse() { ! return true; ! } ! ! /** ! * The response is a list of threads ! */ ! public void processOKResponse(int cmdCode, String payload) { ! if (cmdCode != 102) { ! PydevDebugPlugin.log(IStatus.ERROR, "Unexpected response to LIST THREADS" + payload, null); ! return; ! } ! try { ! threads = XMLUtils.ThreadsFromXML(target, payload); ! } catch (CoreException e) { ! PydevDebugPlugin.log(IStatus.ERROR, "LIST THREADS got an unexpected response " + payload, null); ! e.printStackTrace(); ! } ! done = true; ! } ! ! public void processErrorResponse(int cmdCode, String payload) { ! PydevDebugPlugin.log(IStatus.ERROR, "LIST THREADS got an error " + payload, null); ! } } --- 21,77 ---- public class ThreadListCommand extends AbstractDebuggerCommand { ! boolean done; ! AbstractDebugTarget target; ! PyThread[] threads; ! ! public ThreadListCommand(AbstractRemoteDebugger debugger, AbstractDebugTarget target) { ! super(debugger); ! this.target = target; ! done = false; ! } ! public void waitUntilDone(int timeout) throws InterruptedException { ! while (!done && timeout > 0) { ! timeout -= 100; ! synchronized (this) { ! Thread.sleep(100); ! } ! } ! if (timeout < 0) ! throw new InterruptedException(); ! } ! ! public PyThread[] getThreads() { ! return threads; ! } ! ! public String getOutgoing() { ! return makeCommand(CMD_LIST_THREADS, sequence, ""); ! } ! ! public boolean needResponse() { ! return true; ! } ! ! /** ! * The response is a list of threads ! */ ! public void processOKResponse(int cmdCode, String payload) { ! if (cmdCode != 102) { ! PydevDebugPlugin.log(IStatus.ERROR, "Unexpected response to LIST THREADS" + payload, null); ! return; ! } ! try { ! threads = XMLUtils.ThreadsFromXML(target, payload); ! } catch (CoreException e) { ! PydevDebugPlugin.log(IStatus.ERROR, "LIST THREADS got an unexpected response " + payload, null); ! e.printStackTrace(); ! } ! done = true; ! } ! ! public void processErrorResponse(int cmdCode, String payload) { ! PydevDebugPlugin.log(IStatus.ERROR, "LIST THREADS got an error " + payload, null); ! } } Index: ThreadSuspendCommand.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/model/remote/ThreadSuspendCommand.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** ThreadSuspendCommand.java 15 Sep 2005 16:11:06 -0000 1.3 --- ThreadSuspendCommand.java 27 Sep 2008 19:59:06 -0000 1.4 *************** *** 13,25 **** public class ThreadSuspendCommand extends AbstractDebuggerCommand { ! String thread; ! ! public ThreadSuspendCommand(AbstractRemoteDebugger debugger, String thread) { ! super(debugger); ! this.thread = thread; ! } ! public String getOutgoing() { ! return makeCommand(CMD_THREAD_SUSPEND, sequence, thread); ! } } --- 13,25 ---- public class ThreadSuspendCommand extends AbstractDebuggerCommand { ! String thread; ! ! public ThreadSuspendCommand(AbstractRemoteDebugger debugger, String thread) { ! super(debugger); ! this.thread = thread; ! } ! public String getOutgoing() { ! return makeCommand(CMD_THREAD_SUSPEND, sequence, thread); ! } } Index: RunCommand.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/model/remote/RunCommand.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** RunCommand.java 15 Sep 2005 16:11:45 -0000 1.2 --- RunCommand.java 27 Sep 2008 19:59:06 -0000 1.3 *************** *** 11,20 **** public class RunCommand extends AbstractDebuggerCommand { ! public RunCommand(AbstractRemoteDebugger debugger) { ! super(debugger); ! } ! public String getOutgoing() { ! return makeCommand(CMD_RUN, sequence, ""); ! } } --- 11,20 ---- public class RunCommand extends AbstractDebuggerCommand { ! public RunCommand(AbstractRemoteDebugger debugger) { ! super(debugger); ! } ! public String getOutgoing() { ! return makeCommand(CMD_RUN, sequence, ""); ! } } Index: ICommandResponseListener.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/model/remote/ICommandResponseListener.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** ICommandResponseListener.java 5 May 2004 02:02:01 -0000 1.1 --- ICommandResponseListener.java 27 Sep 2008 19:59:06 -0000 1.2 *************** *** 12,15 **** */ public interface ICommandResponseListener { ! public void commandComplete(AbstractDebuggerCommand cmd); } --- 12,15 ---- */ public interface ICommandResponseListener { ! public void commandComplete(AbstractDebuggerCommand cmd); } Index: StepCommand.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/model/remote/StepCommand.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** StepCommand.java 15 Sep 2005 16:11:23 -0000 1.3 --- StepCommand.java 27 Sep 2008 19:59:06 -0000 1.4 *************** *** 11,30 **** public class StepCommand extends AbstractDebuggerCommand { ! int command_id; ! String thread_id; ! ! /** ! * ! * @param command_id CMD_STEP_INTO CMD_STEP_OVER CMD_STEP_RETURN ! */ ! public StepCommand(AbstractRemoteDebugger debugger, int command_id, String thread_id) { ! super(debugger); ! this.command_id = command_id; ! this.thread_id = thread_id; ! } ! public String getOutgoing() { ! return makeCommand(command_id, sequence, thread_id); ! } } --- 11,30 ---- public class StepCommand extends AbstractDebuggerCommand { ! int command_id; ! String thread_id; ! ! /** ! * ! * @param command_id CMD_STEP_INTO CMD_STEP_OVER CMD_STEP_RETURN ! */ ! public StepCommand(AbstractRemoteDebugger debugger, int command_id, String thread_id) { ! super(debugger); ! this.command_id = command_id; ! this.thread_id = thread_id; ! } ! public String getOutgoing() { ! return makeCommand(command_id, sequence, thread_id); ! } } Index: AbstractRemoteDebugger.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/model/remote/AbstractRemoteDebugger.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** AbstractRemoteDebugger.java 20 May 2006 14:09:54 -0000 1.4 --- AbstractRemoteDebugger.java 27 Sep 2008 19:59:06 -0000 1.5 *************** *** 12,38 **** * connection socket */ ! protected Socket socket; /** * reading thread */ ! protected DebuggerReader reader; /** * writing thread */ ! protected DebuggerWriter writer; /** * sequence seed for command numbers */ ! protected int sequence = -1; - protected AbstractDebugTarget target = null; - /** * debugger should finish when this is called */ ! public abstract void dispose(); /** --- 12,38 ---- * connection socket */ ! protected Socket socket; /** * reading thread */ ! protected DebuggerReader reader; /** * writing thread */ ! protected DebuggerWriter writer; /** * sequence seed for command numbers */ ! protected int sequence = -1; ! ! protected AbstractDebugTarget target = null; /** * debugger should finish when this is called */ ! public abstract void dispose(); /** *************** *** 41,81 **** * @throws DebugException */ ! public abstract void disconnect() throws DebugException; ! public AbstractDebugTarget getTarget() { ! return target; ! } ! public void setTarget(AbstractDebugTarget target) { ! this.target = target; ! } ! ! /** ! * @return next available debugger command sequence number ! */ ! public int getNextSequence() { ! sequence += 2; ! return sequence; ! } ! ! public void addToResponseQueue(AbstractDebuggerCommand cmd) { ! reader.addToResponseQueue(cmd); ! } ! ! public void postCommand(AbstractDebuggerCommand cmd) { ! if( writer!=null ) { ! writer.postCommand(cmd); ! } ! } ! ! public void startTransmission() throws IOException { ! //socket = connector.getSocket(); ! this.reader = new DebuggerReader( socket, this ); ! this.writer = new DebuggerWriter(socket); ! Thread t = new Thread(reader, "pydevd.reader"); ! t.start(); ! t = new Thread(writer, "pydevd.writer"); ! t.start(); ! } ! } --- 41,81 ---- * @throws DebugException */ ! public abstract void disconnect() throws DebugException; ! public AbstractDebugTarget getTarget() { ! return target; ! } ! public void setTarget(AbstractDebugTarget target) { ! this.target = target; ! } ! ! /** ! * @return next available debugger command sequence number ! */ ! public int getNextSequence() { ! sequence += 2; ! return sequence; ! } ! ! public void addToResponseQueue(AbstractDebuggerCommand cmd) { ! reader.addToResponseQueue(cmd); ! } ! ! public void postCommand(AbstractDebuggerCommand cmd) { ! if( writer!=null ) { ! writer.postCommand(cmd); ! } ! } ! ! public void startTransmission() throws IOException { ! //socket = connector.getSocket(); ! this.reader = new DebuggerReader( socket, this ); ! this.writer = new DebuggerWriter(socket); ! Thread t = new Thread(reader, "pydevd.reader"); ! t.start(); ! t = new Thread(writer, "pydevd.writer"); ! t.start(); ! } ! } Index: AbstractListenConnector.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/model/remote/AbstractListenConnector.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** AbstractListenConnector.java 17 Apr 2006 02:06:17 -0000 1.3 --- AbstractListenConnector.java 27 Sep 2008 19:59:06 -0000 1.4 *************** *** 7,14 **** protected int port; ! protected int timeout; ! protected ServerSocket serverSocket; ! protected Socket socket; // what got accepted ! protected Exception e; ! } --- 7,14 ---- protected int port; ! protected int timeout; ! protected ServerSocket serverSocket; ! protected Socket socket; // what got accepted ! protected Exception e; ! } Index: VersionCommand.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/model/remote/VersionCommand.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** VersionCommand.java 15 Sep 2005 16:09:32 -0000 1.3 --- VersionCommand.java 27 Sep 2008 19:59:06 -0000 1.4 *************** *** 13,37 **** public class VersionCommand extends AbstractDebuggerCommand { ! static final String VERSION = "1.0"; ! ! /** ! * @param debugger ! */ ! public VersionCommand(AbstractRemoteDebugger debugger) { ! super(debugger); ! } ! public String getOutgoing() { ! return makeCommand(CMD_VERSION, sequence, VERSION); ! } ! public boolean needResponse() { ! return true; ! } ! ! public void processOKResponse(int cmdCode, String payload) { ! // System.err.println("The version is " + payload); // not checking for versioning in 1.0, might come in useful later ! } } --- 13,37 ---- public class VersionCommand extends AbstractDebuggerCommand { ! static final String VERSION = "1.0"; ! ! /** ! * @param debugger ! */ ! public VersionCommand(AbstractRemoteDebugger debugger) { ! super(debugger); ! } ! public String getOutgoing() { ! return makeCommand(CMD_VERSION, sequence, VERSION); ! } ! public boolean needResponse() { ! return true; ! } ! ! public void processOKResponse(int cmdCode, String payload) { ! // System.err.println("The version is " + payload); // not checking for versioning in 1.0, might come in useful later ! } } Index: ThreadRunCommand.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/model/remote/ThreadRunCommand.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** ThreadRunCommand.java 15 Sep 2005 16:11:06 -0000 1.3 --- ThreadRunCommand.java 27 Sep 2008 19:59:06 -0000 1.4 *************** *** 11,23 **** public class ThreadRunCommand extends AbstractDebuggerCommand { ! String thread; ! ! public ThreadRunCommand(AbstractRemoteDebugger debugger, String thread) { ! super(debugger); ! this.thread = thread; ! } ! public String getOutgoing() { ! return makeCommand(CMD_THREAD_RUN, sequence, thread); ! } } --- 11,23 ---- public class ThreadRunCommand extends AbstractDebuggerCommand { ! String thread; ! ! public ThreadRunCommand(AbstractRemoteDebugger debugger, String thread) { ! super(debugger); ! this.thread = thread; ! } ! public String getOutgoing() { ! return makeCommand(CMD_THREAD_RUN, sequence, thread); ! } } Index: GetFrameCommand.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/model/remote/GetFrameCommand.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** GetFrameCommand.java 20 Jan 2006 13:24:42 -0000 1.1 --- GetFrameCommand.java 27 Sep 2008 19:59:06 -0000 1.2 *************** *** 3,14 **** public class GetFrameCommand extends GetVariableCommand{ ! public GetFrameCommand(AbstractRemoteDebugger debugger, String locator) { ! super(debugger, locator); ! } ! ! @Override ! protected int getCommandId() { ! return CMD_GET_FRAME; ! } --- 3,14 ---- public class GetFrameCommand extends GetVariableCommand{ ! public GetFrameCommand(AbstractRemoteDebugger debugger, String locator) { ! super(debugger, locator); ! } ! ! @Override ! protected int getCommandId() { ! return CMD_GET_FRAME; ! } Index: DebuggerWriter.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/model/remote/DebuggerWriter.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** DebuggerWriter.java 7 Feb 2007 00:46:14 -0000 1.5 --- DebuggerWriter.java 27 Sep 2008 19:59:06 -0000 1.6 *************** *** 5,8 **** --- 5,9 ---- import java.net.Socket; import java.util.ArrayList; + import java.util.List; /** *************** *** 20,29 **** * a list of RemoteDebuggerCommands */ ! private ArrayList cmdQueue = new ArrayList(); private OutputStreamWriter out; ! private boolean done = false; public DebuggerWriter(Socket s) throws IOException { socket = s; --- 21,39 ---- * a list of RemoteDebuggerCommands */ ! private List<AbstractDebuggerCommand> cmdQueue = new ArrayList<AbstractDebuggerCommand>(); private OutputStreamWriter out; ! /** ! * Volatile, as multiple threads may ask it to be 'done' ! */ ! private volatile boolean done = false; + /** + * Lock object for sleeping. + */ + private Object lock = new Object(); + + public DebuggerWriter(Socket s) throws IOException { socket = s; *************** *** 51,56 **** AbstractDebuggerCommand cmd = null; synchronized (cmdQueue) { ! if (cmdQueue.size() > 0) cmd = (AbstractDebuggerCommand) cmdQueue.remove(0); } try { --- 61,67 ---- AbstractDebuggerCommand cmd = null; synchronized (cmdQueue) { ! if (cmdQueue.size() > 0){ cmd = (AbstractDebuggerCommand) cmdQueue.remove(0); + } } try { *************** *** 61,65 **** out.flush(); } ! synchronized (this) { Thread.sleep(100); } --- 72,76 ---- out.flush(); } ! synchronized (lock) { Thread.sleep(100); } Index: RemoveBreakpointCommand.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/model/remote/RemoveBreakpointCommand.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** RemoveBreakpointCommand.java 15 Sep 2005 16:12:05 -0000 1.2 --- RemoveBreakpointCommand.java 27 Sep 2008 19:59:06 -0000 1.3 *************** *** 11,25 **** public class RemoveBreakpointCommand extends AbstractDebuggerCommand { ! public String file; ! public Object line; ! ! public RemoveBreakpointCommand(AbstractRemoteDebugger debugger, String file, Object line) { ! super(debugger); ! this.file = file; ! this.line = line; ! } ! public String getOutgoing() { ! return makeCommand(CMD_REMOVE_BREAK, sequence, file + "\t" + line.toString()); ! } } --- 11,25 ---- public class RemoveBreakpointCommand extends AbstractDebuggerCommand { ! public String file; ! public Object line; ! ! public RemoveBreakpointCommand(AbstractRemoteDebugger debugger, String file, Object line) { ! super(debugger); ! this.file = file; ! this.line = line; ! } ! public String getOutgoing() { ! return makeCommand(CMD_REMOVE_BREAK, sequence, file + "\t" + line.toString()); ! } } Index: AbstractDebuggerCommand.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/model/remote/AbstractDebuggerCommand.java,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** AbstractDebuggerCommand.java 7 Feb 2007 00:46:14 -0000 1.9 --- AbstractDebuggerCommand.java 27 Sep 2008 19:59:06 -0000 1.10 *************** *** 17,142 **** * Command lifecycle: * cmd = new Command() // creation ! * cmd.getSequence() // get the sequence number of the command ! * cmd.getOutgoing() // asks command for outgoing message ! * cmd.aboutToSend() // called right before we go on wire ! * // by default, if command needs response ! * // it gets posted to in the response queue ! * if (cmd.needsResponse()) ! * post the command to response queue, otherwise we are done * when response arrives: * if response is an error ! * cmd.processResponse() ! * else ! * cmd.processErrorResponse() * */ public abstract class AbstractDebuggerCommand { ! ! static public final int CMD_RUN = 101; ! static public final int CMD_LIST_THREADS = 102; ! static public final int CMD_THREAD_CREATED = 103; ! static public final int CMD_THREAD_KILL = 104; ! static public final int CMD_THREAD_SUSPEND = 105; ! static public final int CMD_THREAD_RUN = 106; ! static public final int CMD_STEP_INTO = 107; ! static public final int CMD_STEP_OVER = 108; ! static public final int CMD_STEP_RETURN = 109; ! static public final int CMD_GET_VARIABLE = 110; ! static public final int CMD_SET_BREAK = 111; ! static public final int CMD_REMOVE_BREAK = 112; ! static public final int CMD_EVALUATE_EXPRESSION = 113; ! static public final int CMD_GET_FRAME = 114; ! static public final int CMD_EXEC_EXPRESSION = 115; ! static public final int CMD_WRITE_TO_CONSOLE = 116; ! static public final int CMD_CHANGE_VARIABLE = 117; ! static public final int CMD_ERROR = 901; ! static public final int CMD_VERSION = 501; ! static public final int CMD_RETURN = 502; ! ! protected AbstractRemoteDebugger debugger; ! protected ICommandResponseListener responseListener; ! int sequence; ! ! public AbstractDebuggerCommand(AbstractRemoteDebugger debugger) { ! this.debugger = debugger; ! this.responseListener = null; ! sequence = debugger.getNextSequence(); ! } ! public void setCompletionListener(ICommandResponseListener listener) { ! this.responseListener = listener; ! } ! ! /** ! * @return outgoing message ! */ ! public abstract String getOutgoing(); ! ! /** ! * Notification right before the command is sent. ! * If subclassed, call super() ! */ ! public void aboutToSend() { ! // if we need a response, put me on the waiting queue ! if (needResponse()){ ! debugger.addToResponseQueue(this); } ! } ! /** ! * Does this command require a response? * * This is meant to be overriden by subclasses if they need a response. ! */ ! public boolean needResponse() { ! return false; ! } ! ! /** ! * returns Sequence # ! */ ! public final int getSequence() { ! return sequence; ! } ! ! /** ! * Called when command completes, if needResponse was true ! */ ! public final void processResponse(int cmdCode, String payload) { ! if (cmdCode / 100 == 9){ ! processErrorResponse(cmdCode, payload); }else{ ! processOKResponse(cmdCode, payload); } ! if (responseListener != null){ ! responseListener.commandComplete(this); } ! } ! ! /** ! * notification of the response to the command. ! * You'll get either processResponse or processErrorResponse ! */ ! public void processOKResponse(int cmdCode, String payload) { ! PydevDebugPlugin.log(IStatus.ERROR, "Debugger command ignored response " + getClass().toString() + payload, null); ! } ! ! /** ! * notification of the response to the command. ! * You'll get either processResponse or processErrorResponse ! */ ! public void processErrorResponse(int cmdCode, String payload) { ! PydevDebugPlugin.log(IStatus.ERROR, "Debugger command ignored error response " + getClass().toString() + payload, null); ! } ! ! public static String makeCommand(int code, int sequence, String payload) { ! StringBuffer s = new StringBuffer(); ! s.append(code); ! s.append("\t"); ! s.append(sequence); ! s.append("\t"); ! s.append(payload); ! return s.toString(); ! } } --- 17,142 ---- * Command lifecycle: * cmd = new Command() // creation ! * cmd.getSequence() // get the sequence number of the command ! * cmd.getOutgoing() // asks command for outgoing message ! * cmd.aboutToSend() // called right before we go on wire ! * // by default, if command needs response ! * // it gets posted to in the response queue ! * if (cmd.needsResponse()) ! * post the command to response queue, otherwise we are done * when response arrives: * if response is an error ! * cmd.processResponse() ! * else ! * cmd.processErrorResponse() * */ public abstract class AbstractDebuggerCommand { ! ! static public final int CMD_RUN = 101; ! static public final int CMD_LIST_THREADS = 102; ! static public final int CMD_THREAD_CREATED = 103; ! static public final int CMD_THREAD_KILL = 104; ! static public final int CMD_THREAD_SUSPEND = 105; ! static public final int CMD_THREAD_RUN = 106; ! static public final int CMD_STEP_INTO = 107; ! static public final int CMD_STEP_OVER = 108; ! static public final int CMD_STEP_RETURN = 109; ! static public final int CMD_GET_VARIABLE = 110; ! static public final int CMD_SET_BREAK = 111; ! static public final int CMD_REMOVE_BREAK = 112; ! static public final int CMD_EVALUATE_EXPRESSION = 113; ! static public final int CMD_GET_FRAME = 114; ! static public final int CMD_EXEC_EXPRESSION = 115; ! static public final int CMD_WRITE_TO_CONSOLE = 116; ! static public final int CMD_CHANGE_VARIABLE = 117; ! static public final int CMD_ERROR = 901; ! static public final int CMD_VERSION = 501; ! static public final int CMD_RETURN = 502; ! ! protected AbstractRemoteDebugger debugger; ! protected ICommandResponseListener responseListener; ! int sequence; ! ! public AbstractDebuggerCommand(AbstractRemoteDebugger debugger) { ! this.debugger = debugger; ! this.responseListener = null; ! sequence = debugger.getNextSequence(); ! } ! public void setCompletionListener(ICommandResponseListener listener) { ! this.responseListener = listener; ! } ! ! /** ! * @return outgoing message ! */ ! public abstract String getOutgoing(); ! ! /** ! * Notification right before the command is sent. ! * If subclassed, call super() ! */ ! public void aboutToSend() { ! // if we need a response, put me on the waiting queue ! if (needResponse()){ ! debugger.addToResponseQueue(this); } ! } ! /** ! * Does this command require a response? * * This is meant to be overriden by subclasses if they need a response. ! */ ! public boolean needResponse() { ! return false; ! } ! ! /** ! * returns Sequence # ! */ ! public final int getSequence() { ! return sequence; ! } ! ! /** ! * Called when command completes, if needResponse was true ! */ ! public final void processResponse(int cmdCode, String payload) { ! if (cmdCode / 100 == 9){ ! processErrorResponse(cmdCode, payload); }else{ ! processOKResponse(cmdCode, payload); } ! if (responseListener != null){ ! responseListener.commandComplete(this); } ! } ! ! /** ! * notification of the response to the command. ! * You'll get either processResponse or processErrorResponse ! */ ! public void processOKResponse(int cmdCode, String payload) { ! PydevDebugPlugin.log(IStatus.ERROR, "Debugger command ignored response " + getClass().toString() + payload, null); ! } ! ! /** ! * notification of the response to the command. ! * You'll get either processResponse or processErrorResponse ! */ ! public void processErrorResponse(int cmdCode, String payload) { ! PydevDebugPlugin.log(IStatus.ERROR, "Debugger command ignored error response " + getClass().toString() + payload, null); ! } ! ! public static String makeCommand(int code, int sequence, String payload) { ! StringBuffer s = new StringBuffer(); ! s.append(code); ! s.append("\t"); ! s.append(sequence); ! s.append("\t"); ! s.append(payload); ! return s.toString(); ! } } Index: EvaluateExpressionCommand.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/model/remote/EvaluateExpressionCommand.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** EvaluateExpressionCommand.java 9 Feb 2006 18:52:29 -0000 1.4 --- EvaluateExpressionCommand.java 27 Sep 2008 19:59:06 -0000 1.5 *************** *** 18,74 **** public class EvaluateExpressionCommand extends AbstractDebuggerCommand { ! String locator; ! String expression; ! ! boolean isError = false; ! int responseCode; ! String payload; ! private boolean doExec; ! ! public EvaluateExpressionCommand(AbstractRemoteDebugger debugger, String expression, String locator, boolean doExec) { ! super(debugger); ! this.doExec = doExec; ! this.locator = locator; ! this.expression = expression.replaceAll("\r","").replaceAll("\n",""); ! } ! public String getOutgoing() { ! int cmd = CMD_EVALUATE_EXPRESSION; ! if(doExec){ ! cmd = CMD_EXEC_EXPRESSION; ! } ! return makeCommand(cmd, sequence, locator + "\t" + expression); ! } ! public boolean needResponse() { ! return true; ! } ! public void processOKResponse(int cmdCode, String payload) { ! responseCode = cmdCode; ! if (cmdCode == CMD_EVALUATE_EXPRESSION || cmdCode == CMD_EXEC_EXPRESSION) ! this.payload = payload; ! else { ! isError = true; ! PydevDebugPlugin.log(IStatus.ERROR, "Unexpected response to EvaluateExpressionCommand", null); ! } ! } ! ! public void processErrorResponse(int cmdCode, String payload) { ! responseCode = cmdCode; ! this.payload = payload; ! isError = true; ! } ! ! public String getResponse() throws CoreException { ! if (isError) ! throw new CoreException( ! PydevDebugPlugin.makeStatus(IStatus.ERROR, ! "pydevd error:" + payload , ! null)); ! else ! return payload; ! } } --- 18,74 ---- public class EvaluateExpressionCommand extends AbstractDebuggerCommand { ! String locator; ! String expression; ! ! boolean isError = false; ! int responseCode; ! String payload; ! private boolean doExec; ! ! public EvaluateExpressionCommand(AbstractRemoteDebugger debugger, String expression, String locator, boolean doExec) { ! super(debugger); ! this.doExec = doExec; ! this.locator = locator; ! this.expression = expression.replaceAll("\r","").replaceAll("\n",""); ! } ! public String getOutgoing() { ! int cmd = CMD_EVALUATE_EXPRESSION; ! if(doExec){ ! cmd = CMD_EXEC_EXPRESSION; ! } ! return makeCommand(cmd, sequence, locator + "\t" + expression); ! } ! public boolean needResponse() { ! return true; ! } ! public void processOKResponse(int cmdCode, String payload) { ! responseCode = cmdCode; ! if (cmdCode == CMD_EVALUATE_EXPRESSION || cmdCode == CMD_EXEC_EXPRESSION) ! this.payload = payload; ! else { ! isError = true; ! PydevDebugPlugin.log(IStatus.ERROR, "Unexpected response to EvaluateExpressionCommand", null); ! } ! } ! ! public void processErrorResponse(int cmdCode, String payload) { ! responseCode = cmdCode; ! this.payload = payload; ! isError = true; ! } ! ! public String getResponse() throws CoreException { ! if (isError) ! throw new CoreException( ! PydevDebugPlugin.makeStatus(IStatus.ERROR, ! "pydevd error:" + payload , ! null)); ! else ! return payload; ! } } Index: SetBreakpointCommand.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/model/remote/SetBreakpointCommand.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** SetBreakpointCommand.java 11 May 2007 01:57:54 -0000 1.4 --- SetBreakpointCommand.java 27 Sep 2008 19:59:06 -0000 1.5 *************** *** 13,34 **** public class SetBreakpointCommand extends AbstractDebuggerCommand { ! public String file; ! public Object line; ! public String condition; private String functionName; ! public SetBreakpointCommand(AbstractRemoteDebugger debugger, String file, Object line, String condition, String functionName) { ! super(debugger); ! this.file = file; ! this.line = line; ! if (condition == null){ ! this.condition = "None"; }else{ ! this.condition = condition; } this.functionName = functionName; ! } ! public String getOutgoing() { StringBuffer cmd = new StringBuffer(). append(file).append("\t").append(line); --- 13,34 ---- public class SetBreakpointCommand extends AbstractDebuggerCommand { ! public String file; ! public Object line; ! public String condition; private String functionName; ! public SetBreakpointCommand(AbstractRemoteDebugger debugger, String file, Object line, String condition, String functionName) { ! super(debugger); ! this.file = file; ! this.line = line; ! if (condition == null){ ! this.condition = "None"; }else{ ! this.condition = condition; } this.functionName = functionName; ! } ! public String getOutgoing() { StringBuffer cmd = new StringBuffer(). append(file).append("\t").append(line); Index: ListenConnector.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/model/remote/ListenConnector.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** ListenConnector.java 17 Apr 2006 02:06:17 -0000 1.3 --- ListenConnector.java 27 Sep 2008 19:59:06 -0000 1.4 *************** *** 9,46 **** public class ListenConnector extends AbstractListenConnector { ! boolean terminated; ! ! public ListenConnector(int port, int timeout) throws IOException { ! this.port = port; ! this.timeout = timeout; ! serverSocket = new ServerSocket(port); ! } ! ! Exception getException() { ! return e; ! } ! public Socket getSocket() { ! return socket; ! } ! public void stopListening() { ! if (serverSocket != null) ! try { ! serverSocket.close(); ! } catch (IOException e) { ! PydevDebugPlugin.log(IStatus.WARNING, "Error closing pydevd socket", e); ! } ! terminated = true; ! } ! public void run() { ! try { ! serverSocket.setSoTimeout(timeout); ! socket = serverSocket.accept(); ! } ! catch (IOException e) { ! this.e = e; ! } ! } } --- 9,46 ---- public class ListenConnector extends AbstractListenConnector { ! boolean terminated; ! ! public ListenConnector(int port, int timeout) throws IOException { ! this.port = port; ! this.timeout = timeout; ! serverSocket = new ServerSocket(port); ! } ! ! Exception getException() { ! return e; ! } ! public Socket getSocket() { ! return socket; ! } ! public void stopListening() { ! if (serverSocket != null) ! try { ! serverSocket.close(); ! } catch (IOException e) { ! PydevDebugPlugin.log(IStatus.WARNING, "Error closing pydevd socket", e); ! } ! terminated = true; ! } ! public void run() { ! try { ! serverSocket.setSoTimeout(timeout); ! socket = serverSocket.accept(); ! } ! catch (IOException e) { ! this.e = e; ! } ! } } Index: ChangeVariableCommand.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/model/remote/ChangeVariableCommand.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** ChangeVariableCommand.java 7 Feb 2007 00:46:14 -0000 1.1 --- ChangeVariableCommand.java 27 Sep 2008 19:59:06 -0000 1.2 *************** *** 14,41 **** public class ChangeVariableCommand extends AbstractDebuggerCommand { ! String locator; ! boolean isError = false; ! int responseCode; ! String payload; String expression; ! public ChangeVariableCommand(AbstractRemoteDebugger debugger, String locator, String expression) { ! super(debugger); ! this.locator = locator; this.expression = expression; ! } ! public String getOutgoing() { ! return makeCommand(getCommandId(), sequence, locator+"\t"+expression); ! } ! public boolean needResponse() { ! return false; ! } ! protected int getCommandId() { ! return CMD_CHANGE_VARIABLE; ! } ! } --- 14,41 ---- public class ChangeVariableCommand extends AbstractDebuggerCommand { ! String locator; ! boolean isError = false; ! int responseCode; ! String payload; String expression; ! public ChangeVariableCommand(AbstractRemoteDebugger debugger, String locator, String expression) { ! super(debugger); ! this.locator = locator; this.expression = expression; ! } ! public String getOutgoing() { ! return makeCommand(getCommandId(), sequence, locator+"\t"+expression); ! } ! public boolean needResponse() { ! return false; ! } ! protected int getCommandId() { ! return CMD_CHANGE_VARIABLE; ! } ! } |
From: Fabio Z. <fa...@us...> - 2008-09-27 20:03:34
|
Update of /cvsroot/pydev/org.python.pydev.refactoring/tests/org/python/pydev/refactoring/tests/core In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv21605/tests/org/python/pydev/refactoring/tests/core Modified Files: IInputOutputTestCase.java AllTests.java LexerTestCase.java IOTestCaseLexer.java AbstractIOTestCase.java AbstractIOTestSuite.java AbstractRewriterTestCase.java Log Message: Synching to latest changes: Pydev <ul> <li><strong>Editor</strong>: Cursor settings no longer overridden</li> <li><strong>Code-completion</strong>: If __all__ is defined with runtime elements (and not only in a single assign statement), it's ignored for code-completion purposes</li> <li><strong>Debugger</strong>: Pythonpath the same in debug and regular modes (sys.path[0] is the same directory as the file run)</li> <li><strong>Debugger</strong>: Persist choices done in the debugger when files from the debugger are not found</li> <li><strong>Interpreter config</strong>: "email" automatically added to the "forced builtins"</li> <li><strong>Parser</strong>: Correctly recognizing absolute import with 3 or more levels</li> <li><strong>Syntax check</strong>: Option to do only on active editor</li> </ul> Also: tabs changed for spaces Index: AbstractIOTestSuite.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/tests/org/python/pydev/refactoring/tests/core/AbstractIOTestSuite.java,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** AbstractIOTestSuite.java 14 Mar 2008 01:30:11 -0000 1.10 --- AbstractIOTestSuite.java 27 Sep 2008 20:00:47 -0000 1.11 *************** *** 16,79 **** public abstract class AbstractIOTestSuite extends TestSuite { ! protected static String TESTDIR = "tests" + File.separator + "python" + File.separator + "rewriter"; ! // can be used to choose which test we want to run ! public static String FILE_FILTER = "^test.+\\.py$"; ! static{ ! // FILE_FILTER = "testExtractMethod12.py"; ! // FILE_FILTER = "testBoolOp.py"; ! // FILE_FILTER = "testDoubleAssign.py"; ! // FILE_FILTER = "testOverrideMethodsBuiltins.py"; ! // FILE_FILTER = "testDecorators2.py"; ! } ! protected void createTests() { ! File[] testFiles = getTestFiles(System.getProperty("testDir", TESTDIR)); ! if (testFiles == null) ! return; ! for (File testFile : testFiles) { ! this.addTest(createTest(testFile)); ! } ! } ! private IInputOutputTestCase createTest(File file) { ! String filename = file.getName(); ! String testCaseName = filename.substring(0, filename.length() - 3); ! IInputOutputTestCase testCase = createTestCase(testCaseName); ! IOTestCaseLexer lexer; ! try { ! lexer = new IOTestCaseLexer(new FileReader(file)); ! lexer.scan(); ! testCase.setFile(file); ! testCase.setSource(lexer.getSource()); ! testCase.setResult(lexer.getResult()); ! testCase.setConfig(lexer.getConfig()); ! } catch (Throwable e) { ! e.printStackTrace(); ! } ! return testCase; ! } ! protected abstract IInputOutputTestCase createTestCase(String testCaseName); ! private File[] getTestFiles(String path) { ! File dir = new File(path); ! File[] testFiles = dir.listFiles(new TestFilenameFilter()); ! return testFiles; ! } ! protected class TestFilenameFilter implements FilenameFilter { ! public boolean accept(File dir, String name) { ! return name.matches(System.getProperty("filter", FILE_FILTER)); ! } ! } } --- 16,79 ---- public abstract class AbstractIOTestSuite extends TestSuite { ! protected static String TESTDIR = "tests" + File.separator + "python" + File.separator + "rewriter"; ! // can be used to choose which test we want to run ! public static String FILE_FILTER = "^test.+\\.py$"; ! static{ ! // FILE_FILTER = "testExtractMethod12.py"; ! // FILE_FILTER = "testBoolOp.py"; ! // FILE_FILTER = "testDoubleAssign.py"; ! // FILE_FILTER = "testOverrideMethodsBuiltins.py"; ! // FILE_FILTER = "testDecorators2.py"; ! } ! protected void createTests() { ! File[] testFiles = getTestFiles(System.getProperty("testDir", TESTDIR)); ! if (testFiles == null) ! return; ! for (File testFile : testFiles) { ! this.addTest(createTest(testFile)); ! } ! } ! private IInputOutputTestCase createTest(File file) { ! String filename = file.getName(); ! String testCaseName = filename.substring(0, filename.length() - 3); ! IInputOutputTestCase testCase = createTestCase(testCaseName); ! IOTestCaseLexer lexer; ! try { ! lexer = new IOTestCaseLexer(new FileReader(file)); ! lexer.scan(); ! testCase.setFile(file); ! testCase.setSource(lexer.getSource()); ! testCase.setResult(lexer.getResult()); ! testCase.setConfig(lexer.getConfig()); ! } catch (Throwable e) { ! e.printStackTrace(); ! } ! return testCase; ! } ! protected abstract IInputOutputTestCase createTestCase(String testCaseName); ! private File[] getTestFiles(String path) { ! File dir = new File(path); ! File[] testFiles = dir.listFiles(new TestFilenameFilter()); ! return testFiles; ! } ! protected class TestFilenameFilter implements FilenameFilter { ! public boolean accept(File dir, String name) { ! return name.matches(System.getProperty("filter", FILE_FILTER)); ! } ! } } Index: AbstractRewriterTestCase.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/tests/org/python/pydev/refactoring/tests/core/AbstractRewriterTestCase.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** AbstractRewriterTestCase.java 20 Oct 2007 19:31:03 -0000 1.5 --- AbstractRewriterTestCase.java 27 Sep 2008 20:00:47 -0000 1.6 *************** *** 9,23 **** public abstract class AbstractRewriterTestCase extends AbstractIOTestCase { ! public AbstractRewriterTestCase(String name) { ! this(name, false); ! } ! public AbstractRewriterTestCase(String name, boolean ignoreEmptyLines) { ! super(name, ignoreEmptyLines); ! } ! protected void runRewriter() throws Throwable { ! setTestGenerated(RewriterVisitor.reparsed(getSource(), "\n")); ! } } --- 9,23 ---- public abstract class AbstractRewriterTestCase extends AbstractIOTestCase { ! public AbstractRewriterTestCase(String name) { ! this(name, false); ! } ! public AbstractRewriterTestCase(String name, boolean ignoreEmptyLines) { ! super(name, ignoreEmptyLines); ! } ! protected void runRewriter() throws Throwable { ! setTestGenerated(RewriterVisitor.reparsed(getSource(), "\n")); ! } } Index: LexerTestCase.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/tests/org/python/pydev/refactoring/tests/core/LexerTestCase.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** LexerTestCase.java 20 Oct 2007 17:18:32 -0000 1.3 --- LexerTestCase.java 27 Sep 2008 20:00:47 -0000 1.4 *************** *** 7,38 **** public class LexerTestCase extends TestCase { ! private IOTestCaseLexer scanner; ! @Override ! protected void setUp() throws Exception { ! this.scanner = new IOTestCaseLexer(new java.io.FileReader(TestDependent.TEST_PYDEV_REFACTORING_PLUGIN_LOC+"tests/python/core/testIOTestCaseLexer.py")); ! this.scanner.scan(); ! } ! public void testSource() { ! String text = scanner.getSource(); ! assertTrue(text.length() > 0); ! assertFalse(text.contains("##r")); ! assertFalse(text.contains("##c")); ! } ! public void testResult() { ! String text = scanner.getResult(); ! assertTrue(text.length() > 0); ! assertFalse(text.contains("##s")); ! assertFalse(text.contains("##c")); ! } ! public void testConfig() { ! String text = scanner.getConfig(); ! assertTrue(text.length() > 0); ! assertFalse(text.contains("'''")); ! assertFalse(text.contains("##s")); ! assertFalse(text.contains("##c")); ! } } --- 7,38 ---- public class LexerTestCase extends TestCase { ! private IOTestCaseLexer scanner; ! @Override ! protected void setUp() throws Exception { ! this.scanner = new IOTestCaseLexer(new java.io.FileReader(TestDependent.TEST_PYDEV_REFACTORING_PLUGIN_LOC+"tests/python/core/testIOTestCaseLexer.py")); ! this.scanner.scan(); ! } ! public void testSource() { ! String text = scanner.getSource(); ! assertTrue(text.length() > 0); ! assertFalse(text.contains("##r")); ! assertFalse(text.contains("##c")); ! } ! public void testResult() { ! String text = scanner.getResult(); ! assertTrue(text.length() > 0); ! assertFalse(text.contains("##s")); ! assertFalse(text.contains("##c")); ! } ! public void testConfig() { ! String text = scanner.getConfig(); ! assertTrue(text.length() > 0); ! assertFalse(text.contains("'''")); ! assertFalse(text.contains("##s")); ! assertFalse(text.contains("##c")); ! } } Index: IInputOutputTestCase.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/tests/org/python/pydev/refactoring/tests/core/IInputOutputTestCase.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** IInputOutputTestCase.java 20 Oct 2007 19:31:03 -0000 1.4 --- IInputOutputTestCase.java 27 Sep 2008 20:00:47 -0000 1.5 *************** *** 14,31 **** public interface IInputOutputTestCase extends Test { ! void setSource(String line); ! void setResult(String line); ! void setConfig(String line); ! String getSource(); ! String getResult(); ! void setTestGenerated(String string); ! void setFile(File file); ! File getFile(); } --- 14,31 ---- public interface IInputOutputTestCase extends Test { ! void setSource(String line); ! void setResult(String line); ! void setConfig(String line); ! String getSource(); ! String getResult(); ! void setTestGenerated(String string); ! void setFile(File file); ! File getFile(); } Index: AbstractIOTestCase.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/tests/org/python/pydev/refactoring/tests/core/AbstractIOTestCase.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** AbstractIOTestCase.java 20 Oct 2007 19:31:03 -0000 1.5 --- AbstractIOTestCase.java 27 Sep 2008 20:00:47 -0000 1.6 *************** *** 16,102 **** public abstract class AbstractIOTestCase extends TestCase implements IInputOutputTestCase { ! private static final String EMPTY = ""; ! private StringBuffer sourceLines = null; ! private StringBuffer resultLines = null; ! private StringBuffer configLines; ! private String generated; ! ! private File file; ! public AbstractIOTestCase(String name) { ! this(name, false); ! } ! @Override ! protected void setUp() throws Exception { ! PythonModuleManager.TESTING = true; ! } ! ! @Override ! protected void tearDown() throws Exception { ! PythonModuleManager.TESTING = false; ! } ! ! public AbstractIOTestCase(String name, boolean ignoreEmptyLines) { ! super(name); ! sourceLines = new StringBuffer(); ! resultLines = new StringBuffer(); ! configLines = new StringBuffer(); ! } ! public String getExpected() { ! return EMPTY.equals(getResult()) ? getSource() : getResult(); ! } ! public String getResult() { ! return getResultLines().toString().trim(); ! } ! public String getSource() { ! return getSourceLines().toString().trim(); ! } ! public void setSource(String line) { ! sourceLines.append(line); ! } ! public void setResult(String line) { ! resultLines.append(line); ! } ! public void setConfig(String line) { ! configLines.append(line); ! } ! private StringBuffer getResultLines() { ! return resultLines; ! } ! protected String getGenerated() { ! return generated.trim(); ! } ! protected String getConfig() { ! return configLines.toString().trim(); ! } ! private StringBuffer getSourceLines() { ! return sourceLines; ! } ! public void setTestGenerated(String source) { ! this.generated = source; ! } ! public void setFile(File file) { ! this.file = file; ! } ! public File getFile() { ! return file; ! } } --- 16,102 ---- public abstract class AbstractIOTestCase extends TestCase implements IInputOutputTestCase { ! private static final String EMPTY = ""; ! private StringBuffer sourceLines = null; ! private StringBuffer resultLines = null; ! private StringBuffer configLines; ! private String generated; ! ! private File file; ! public AbstractIOTestCase(String name) { ! this(name, false); ! } ! @Override ! protected void setUp() throws Exception { ! PythonModuleManager.TESTING = true; ! } ! ! @Override ! protected void tearDown() throws Exception { ! PythonModuleManager.TESTING = false; ! } ! ! public AbstractIOTestCase(String name, boolean ignoreEmptyLines) { ! super(name); ! sourceLines = new StringBuffer(); ! resultLines = new StringBuffer(); ! configLines = new StringBuffer(); ! } ! public String getExpected() { ! return EMPTY.equals(getResult()) ? getSource() : getResult(); ! } ! public String getResult() { ! return getResultLines().toString().trim(); ! } ! public String getSource() { ! return getSourceLines().toString().trim(); ! } ! public void setSource(String line) { ! sourceLines.append(line); ! } ! public void setResult(String line) { ! resultLines.append(line); ! } ! public void setConfig(String line) { ! configLines.append(line); ! } ! private StringBuffer getResultLines() { ! return resultLines; ! } ! protected String getGenerated() { ! return generated.trim(); ! } ! protected String getConfig() { ! return configLines.toString().trim(); ! } ! private StringBuffer getSourceLines() { ! return sourceLines; ! } ! public void setTestGenerated(String source) { ! this.generated = source; ! } ! public void setFile(File file) { ! this.file = file; ! } ! public File getFile() { ! return file; ! } } Index: IOTestCaseLexer.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/tests/org/python/pydev/refactoring/tests/core/IOTestCaseLexer.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** IOTestCaseLexer.java 20 Oct 2007 19:31:03 -0000 1.3 --- IOTestCaseLexer.java 27 Sep 2008 20:00:47 -0000 1.4 *************** *** 15,626 **** class IOTestCaseLexer { ! /** This character denotes the end of file */ ! public static final int YYEOF = -1; ! /** initial size of the lookahead buffer */ ! private static final int ZZ_BUFFERSIZE = 16384; ! /** lexical states */ ! public static final int CONFIG = 2; [...1195 lines suppressed...] ! for (String arg : argv) { ! IOTestCaseLexer scanner = null; ! try { ! scanner = new IOTestCaseLexer(new java.io.FileReader(arg)); ! while (!scanner.zzAtEOF) ! scanner.yylex(); ! } catch (java.io.FileNotFoundException e) { ! System.out.println("File not found : \"" + arg + "\""); ! } catch (java.io.IOException e) { ! System.out.println("IO error scanning file \"" + arg + "\""); ! System.out.println(e); ! } catch (Exception e) { ! System.out.println("Unexpected exception:"); ! e.printStackTrace(); ! } ! } ! } ! } } Index: AllTests.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/tests/org/python/pydev/refactoring/tests/core/AllTests.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** AllTests.java 20 Oct 2007 19:31:03 -0000 1.3 --- AllTests.java 27 Sep 2008 20:00:47 -0000 1.4 *************** *** 10,20 **** public class AllTests { ! public static Test suite() { ! TestSuite suite = new TestSuite("Test for org.python.pydev.refactoring.tests.core"); ! // $JUnit-BEGIN$ ! suite.addTestSuite(LexerTestCase.class); ! // $JUnit-END$ ! return suite; ! } } --- 10,20 ---- public class AllTests { ! public static Test suite() { ! TestSuite suite = new TestSuite("Test for org.python.pydev.refactoring.tests.core"); ! // $JUnit-BEGIN$ ! suite.addTestSuite(LexerTestCase.class); ! // $JUnit-END$ ! return suite; ! } } |
Update of /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/ui/pages/listener In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv21605/src/org/python/pydev/refactoring/ui/pages/listener Modified Files: IValidationPage.java FunctionSignatureListener.java TableCellEditorListener.java ButtonActivationListener.java Log Message: Synching to latest changes: Pydev <ul> <li><strong>Editor</strong>: Cursor settings no longer overridden</li> <li><strong>Code-completion</strong>: If __all__ is defined with runtime elements (and not only in a single assign statement), it's ignored for code-completion purposes</li> <li><strong>Debugger</strong>: Pythonpath the same in debug and regular modes (sys.path[0] is the same directory as the file run)</li> <li><strong>Debugger</strong>: Persist choices done in the debugger when files from the debugger are not found</li> <li><strong>Interpreter config</strong>: "email" automatically added to the "forced builtins"</li> <li><strong>Parser</strong>: Correctly recognizing absolute import with 3 or more levels</li> <li><strong>Syntax check</strong>: Option to do only on active editor</li> </ul> Also: tabs changed for spaces Index: ButtonActivationListener.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/ui/pages/listener/ButtonActivationListener.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** ButtonActivationListener.java 20 Oct 2007 19:31:02 -0000 1.3 --- ButtonActivationListener.java 27 Sep 2008 20:00:49 -0000 1.4 *************** *** 15,53 **** public class ButtonActivationListener implements Listener { ! private Table table; ! private Button upButton; ! private Button downButton; ! private Button editButton; ! public ButtonActivationListener(Table table, Button upButton, Button downButton, Button editButton) { ! this.table = table; ! this.upButton = upButton; ! this.downButton = downButton; ! this.editButton = editButton; ! } ! public void handleEvent(Event event) { ! updateButtonState(); ! } ! private void updateButtonState() { ! editButton.setEnabled(false); ! upButton.setEnabled(true); ! downButton.setEnabled(true); ! if (table.getSelectionCount() == 1) { ! editButton.setEnabled(true); ! if (table.getSelectionIndex() == table.getItemCount() - 1) { ! downButton.setEnabled(false); ! } ! if (table.getSelectionIndex() == 0) { ! upButton.setEnabled(false); ! } ! } ! } } --- 15,53 ---- public class ButtonActivationListener implements Listener { ! private Table table; ! private Button upButton; ! private Button downButton; ! private Button editButton; ! public ButtonActivationListener(Table table, Button upButton, Button downButton, Button editButton) { ! this.table = table; ! this.upButton = upButton; ! this.downButton = downButton; ! this.editButton = editButton; ! } ! public void handleEvent(Event event) { ! updateButtonState(); ! } ! private void updateButtonState() { ! editButton.setEnabled(false); ! upButton.setEnabled(true); ! downButton.setEnabled(true); ! if (table.getSelectionCount() == 1) { ! editButton.setEnabled(true); ! if (table.getSelectionIndex() == table.getItemCount() - 1) { ! downButton.setEnabled(false); ! } ! if (table.getSelectionIndex() == 0) { ! upButton.setEnabled(false); ! } ! } ! } } Index: IValidationPage.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/ui/pages/listener/IValidationPage.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** IValidationPage.java 20 Oct 2007 19:31:02 -0000 1.2 --- IValidationPage.java 27 Sep 2008 20:00:49 -0000 1.3 *************** *** 13,18 **** public interface IValidationPage extends IWizardPage, Listener { ! public void setErrorMessage(String error); ! public void validate(); } --- 13,18 ---- public interface IValidationPage extends IWizardPage, Listener { ! public void setErrorMessage(String error); ! public void validate(); } Index: FunctionSignatureListener.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/ui/pages/listener/FunctionSignatureListener.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** FunctionSignatureListener.java 20 Oct 2007 19:31:02 -0000 1.3 --- FunctionSignatureListener.java 27 Sep 2008 20:00:49 -0000 1.4 *************** *** 22,82 **** public class FunctionSignatureListener implements Listener { ! private final String METHODDEF = "def "; ! private final String OPENBRACKET = "("; ! private final String CLOSEBRACKET = ")"; ! private Table argumentTable; ! private Label signatureLabel; ! private LabeledEdit functionNameEdit; ! private IValidationPage page; ! public FunctionSignatureListener(IValidationPage page, Label signature, LabeledEdit functionNameEdit, Table argumentTable) { ! this.page = page; ! this.signatureLabel = signature; ! this.functionNameEdit = functionNameEdit; ! this.argumentTable = argumentTable; ! } ! private void updateSignature() { ! if (functionNameEdit.getEdit().getText().length() == 0) { ! return; ! } ! StringBuilder signature = new StringBuilder(); ! signature.append(METHODDEF); ! signature.append(this.functionNameEdit.getEdit().getText()); ! signature.append(OPENBRACKET); ! initArguments(signature); ! signature.append(CLOSEBRACKET); ! signatureLabel.setText(signature.toString()); ! } ! private void initArguments(StringBuilder signature) { ! if (this.argumentTable != null) { ! List<TableItem> items = Arrays.asList(argumentTable.getItems()); ! Iterator<TableItem> iter = items.iterator(); ! while (iter.hasNext()) { ! TableItem item = iter.next(); ! if (item instanceof SimpleTableItem) { ! signature.append(item.getText()); ! if (iter.hasNext()) ! signature.append(", "); ! } ! } ! } ! } ! public void handleEvent(Event event) { ! if (page.isPageComplete()) { ! updateSignature(); ! } ! } } --- 22,82 ---- public class FunctionSignatureListener implements Listener { ! private final String METHODDEF = "def "; ! private final String OPENBRACKET = "("; ! private final String CLOSEBRACKET = ")"; ! private Table argumentTable; ! private Label signatureLabel; ! private LabeledEdit functionNameEdit; ! private IValidationPage page; ! public FunctionSignatureListener(IValidationPage page, Label signature, LabeledEdit functionNameEdit, Table argumentTable) { ! this.page = page; ! this.signatureLabel = signature; ! this.functionNameEdit = functionNameEdit; ! this.argumentTable = argumentTable; ! } ! private void updateSignature() { ! if (functionNameEdit.getEdit().getText().length() == 0) { ! return; ! } ! StringBuilder signature = new StringBuilder(); ! signature.append(METHODDEF); ! signature.append(this.functionNameEdit.getEdit().getText()); ! signature.append(OPENBRACKET); ! initArguments(signature); ! signature.append(CLOSEBRACKET); ! signatureLabel.setText(signature.toString()); ! } ! private void initArguments(StringBuilder signature) { ! if (this.argumentTable != null) { ! List<TableItem> items = Arrays.asList(argumentTable.getItems()); ! Iterator<TableItem> iter = items.iterator(); ! while (iter.hasNext()) { ! TableItem item = iter.next(); ! if (item instanceof SimpleTableItem) { ! signature.append(item.getText()); ! if (iter.hasNext()) ! signature.append(", "); ! } ! } ! } ! } ! public void handleEvent(Event event) { ! if (page.isPageComplete()) { ! updateSignature(); ! } ! } } Index: TableCellEditorListener.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/ui/pages/listener/TableCellEditorListener.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** TableCellEditorListener.java 20 Oct 2007 19:31:02 -0000 1.3 --- TableCellEditorListener.java 27 Sep 2008 20:00:49 -0000 1.4 *************** *** 22,106 **** public class TableCellEditorListener extends Observable implements Listener { ! private final Table table; ! private IValidationPage wizard; ! public TableCellEditorListener(IValidationPage wizard, Table parametersTable) { ! this.wizard = wizard; ! this.table = parametersTable; ! } ! /** ! * http://www.eclipse.org/swt/snippets/ ! */ ! public void handleEvent(Event event) { ! final TableEditor editor = new TableEditor(table); ! editor.horizontalAlignment = SWT.LEFT; ! editor.grabHorizontal = true; ! Rectangle clientArea = table.getClientArea(); ! if (table.getSelection().length != 1) ! return; ! Rectangle bounds = table.getSelection()[0].getBounds(); ! Point pt = new Point(bounds.x, bounds.y); ! int index = table.getTopIndex(); ! while (index < table.getItemCount()) { ! boolean visible = false; ! final SimpleTableItem item = (SimpleTableItem) table.getItem(index); ! for (int i = 0; i < table.getColumnCount(); i++) { ! Rectangle rect = item.getBounds(i); ! if (rect.contains(pt)) { ! final Text text = new Text(table, SWT.NONE); ! Listener textListener = new TextListener(item, text); ! text.addListener(SWT.FocusOut, textListener); ! text.addListener(SWT.Traverse, textListener); ! text.addListener(SWT.FocusOut, wizard); ! editor.setEditor(text, item, i); ! text.setText(item.getText(i)); ! text.selectAll(); ! text.setFocus(); ! return; ! } ! if (!visible && rect.intersects(clientArea)) { ! visible = true; ! } ! } ! if (!visible) { ! return; ! } ! index++; ! } ! } ! private final class TextListener implements Listener { ! private SimpleTableItem tableItem; ! private final Text text; ! private TextListener(SimpleTableItem item, Text text) { ! this.tableItem = item; ! this.text = text; ! } ! public void handleEvent(final Event e) { ! if (e.type == SWT.FocusOut) { ! tableItem.setText(text.getText()); ! text.dispose(); ! table.setFocus(); ! } else if (e.type == SWT.Traverse) { ! if (e.detail == SWT.TRAVERSE_RETURN) { ! tableItem.setText(text.getText()); ! e.doit = true; ! } ! if (e.detail == SWT.TRAVERSE_RETURN || e.detail == SWT.TRAVERSE_ESCAPE) { ! text.dispose(); ! if (e.detail == SWT.TRAVERSE_ESCAPE) ! e.doit = false; ! } ! } ! } ! } } --- 22,106 ---- public class TableCellEditorListener extends Observable implements Listener { ! private final Table table; ! private IValidationPage wizard; ! public TableCellEditorListener(IValidationPage wizard, Table parametersTable) { ! this.wizard = wizard; ! this.table = parametersTable; ! } ! /** ! * http://www.eclipse.org/swt/snippets/ ! */ ! public void handleEvent(Event event) { ! final TableEditor editor = new TableEditor(table); ! editor.horizontalAlignment = SWT.LEFT; ! editor.grabHorizontal = true; ! Rectangle clientArea = table.getClientArea(); ! if (table.getSelection().length != 1) ! return; ! Rectangle bounds = table.getSelection()[0].getBounds(); ! Point pt = new Point(bounds.x, bounds.y); ! int index = table.getTopIndex(); ! while (index < table.getItemCount()) { ! boolean visible = false; ! final SimpleTableItem item = (SimpleTableItem) table.getItem(index); ! for (int i = 0; i < table.getColumnCount(); i++) { ! Rectangle rect = item.getBounds(i); ! if (rect.contains(pt)) { ! final Text text = new Text(table, SWT.NONE); ! Listener textListener = new TextListener(item, text); ! text.addListener(SWT.FocusOut, textListener); ! text.addListener(SWT.Traverse, textListener); ! text.addListener(SWT.FocusOut, wizard); ! editor.setEditor(text, item, i); ! text.setText(item.getText(i)); ! text.selectAll(); ! text.setFocus(); ! return; ! } ! if (!visible && rect.intersects(clientArea)) { ! visible = true; ! } ! } ! if (!visible) { ! return; ! } ! index++; ! } ! } ! private final class TextListener implements Listener { ! private SimpleTableItem tableItem; ! private final Text text; ! private TextListener(SimpleTableItem item, Text text) { ! this.tableItem = item; ! this.text = text; ! } ! public void handleEvent(final Event e) { ! if (e.type == SWT.FocusOut) { ! tableItem.setText(text.getText()); ! text.dispose(); ! table.setFocus(); ! } else if (e.type == SWT.Traverse) { ! if (e.detail == SWT.TRAVERSE_RETURN) { ! tableItem.setText(text.getText()); ! e.doit = true; ! } ! if (e.detail == SWT.TRAVERSE_RETURN || e.detail == SWT.TRAVERSE_ESCAPE) { ! text.dispose(); ! if (e.detail == SWT.TRAVERSE_ESCAPE) ! e.doit = false; ! } ! } ! } ! } } |
Update of /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/coderefactoring/extractmethod In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv21605/src/org/python/pydev/refactoring/coderefactoring/extractmethod Modified Files: ExtractMethodRequestProcessor.java ExtractMethodRefactoring.java ExtractMethodChangeProcessor.java Log Message: Synching to latest changes: Pydev <ul> <li><strong>Editor</strong>: Cursor settings no longer overridden</li> <li><strong>Code-completion</strong>: If __all__ is defined with runtime elements (and not only in a single assign statement), it's ignored for code-completion purposes</li> <li><strong>Debugger</strong>: Pythonpath the same in debug and regular modes (sys.path[0] is the same directory as the file run)</li> <li><strong>Debugger</strong>: Persist choices done in the debugger when files from the debugger are not found</li> <li><strong>Interpreter config</strong>: "email" automatically added to the "forced builtins"</li> <li><strong>Parser</strong>: Correctly recognizing absolute import with 3 or more levels</li> <li><strong>Syntax check</strong>: Option to do only on active editor</li> </ul> Also: tabs changed for spaces Index: ExtractMethodRefactoring.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/coderefactoring/extractmethod/ExtractMethodRefactoring.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** ExtractMethodRefactoring.java 20 Oct 2007 19:31:04 -0000 1.5 --- ExtractMethodRefactoring.java 27 Sep 2008 20:00:49 -0000 1.6 *************** *** 29,132 **** public class ExtractMethodRefactoring extends AbstractPythonRefactoring { ! private ExtractMethodRequestProcessor requestProcessor; ! private IChangeProcessor changeProcessor; ! private ModuleAdapter parsedExtendedSelection; ! private ModuleAdapter parsedUserSelection; ! private ModuleAdapter module; ! public ExtractMethodRefactoring(RefactoringInfo req) { ! super(req); ! this.parsedExtendedSelection = null; ! this.parsedUserSelection = req.getParsedUserSelection(); ! this.parsedExtendedSelection = req.getParsedExtendedSelection(); ! this.module = req.getModule(); ! validateSelections(); ! try { ! initWizard(); ! } catch (Throwable e) { ! status.addInfo(Messages.infoFixCode); ! } ! } ! private void initWizard() throws Throwable { ! ITextSelection standardSelection = info.getUserSelection(); ! ModuleAdapter standardModule = this.parsedUserSelection; ! if (standardModule == null) { ! standardSelection = info.getExtendedSelection(); ! standardModule = this.parsedExtendedSelection; ! } ! this.requestProcessor = new ExtractMethodRequestProcessor(info.getScopeAdapter(), standardModule, this.getModule(), standardSelection); ! this.pages.add(new ExtractMethodPage(getName(), this.requestProcessor)); ! } ! @Override ! protected List<IChangeProcessor> getChangeProcessors() { ! List<IChangeProcessor> processors = new ArrayList<IChangeProcessor>(); ! this.changeProcessor = new ExtractMethodChangeProcessor(getName(), this.info, this.requestProcessor); ! processors.add(changeProcessor); ! return processors; ! } ! @Override ! public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException, OperationCanceledException { ! if (this.requestProcessor.getScopeAdapter() == null || this.requestProcessor.getScopeAdapter() instanceof IClassDefAdapter) { ! status.addFatalError(Messages.extractMethodScopeInvalid); ! return status; ! } ! if (status.getEntries().length > 0) ! return status; ! if (parsedExtendedSelection == null && parsedUserSelection == null) { ! status.addFatalError(Messages.extractMethodIncompleteSelection); ! return status; ! } ! return status; ! } ! private void validateSelections() { ! try { ! if (parsedUserSelection != null) { ! VisitorFactory.validateSelection(parsedUserSelection); ! } ! } catch (SelectionException e) { ! this.parsedUserSelection = null; ! if (parsedExtendedSelection == null) { ! status.addFatalError(e.getMessage()); ! return; ! } ! } ! try { ! if (parsedExtendedSelection != null) { ! VisitorFactory.validateSelection(parsedExtendedSelection); ! } ! } catch (SelectionException e) { ! this.parsedExtendedSelection = null; ! if (parsedUserSelection == null) { ! status.addFatalError(e.getMessage()); ! return; ! } ! } ! } ! public void setModule(ModuleAdapter module) { ! this.module = module; ! } ! public ModuleAdapter getModule() { ! return module; ! } ! @Override ! public String getName() { ! return Messages.extractMethodLabel; ! } } --- 29,132 ---- public class ExtractMethodRefactoring extends AbstractPythonRefactoring { ! private ExtractMethodRequestProcessor requestProcessor; ! private IChangeProcessor changeProcessor; ! private ModuleAdapter parsedExtendedSelection; ! private ModuleAdapter parsedUserSelection; ! private ModuleAdapter module; ! public ExtractMethodRefactoring(RefactoringInfo req) { ! super(req); ! this.parsedExtendedSelection = null; ! this.parsedUserSelection = req.getParsedUserSelection(); ! this.parsedExtendedSelection = req.getParsedExtendedSelection(); ! this.module = req.getModule(); ! validateSelections(); ! try { ! initWizard(); ! } catch (Throwable e) { ! status.addInfo(Messages.infoFixCode); ! } ! } ! private void initWizard() throws Throwable { ! ITextSelection standardSelection = info.getUserSelection(); ! ModuleAdapter standardModule = this.parsedUserSelection; ! if (standardModule == null) { ! standardSelection = info.getExtendedSelection(); ! standardModule = this.parsedExtendedSelection; ! } ! this.requestProcessor = new ExtractMethodRequestProcessor(info.getScopeAdapter(), standardModule, this.getModule(), standardSelection); ! this.pages.add(new ExtractMethodPage(getName(), this.requestProcessor)); ! } ! @Override ! protected List<IChangeProcessor> getChangeProcessors() { ! List<IChangeProcessor> processors = new ArrayList<IChangeProcessor>(); ! this.changeProcessor = new ExtractMethodChangeProcessor(getName(), this.info, this.requestProcessor); ! processors.add(changeProcessor); ! return processors; ! } ! @Override ! public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException, OperationCanceledException { ! if (this.requestProcessor.getScopeAdapter() == null || this.requestProcessor.getScopeAdapter() instanceof IClassDefAdapter) { ! status.addFatalError(Messages.extractMethodScopeInvalid); ! return status; ! } ! if (status.getEntries().length > 0) ! return status; ! if (parsedExtendedSelection == null && parsedUserSelection == null) { ! status.addFatalError(Messages.extractMethodIncompleteSelection); ! return status; ! } ! return status; ! } ! private void validateSelections() { ! try { ! if (parsedUserSelection != null) { ! VisitorFactory.validateSelection(parsedUserSelection); ! } ! } catch (SelectionException e) { ! this.parsedUserSelection = null; ! if (parsedExtendedSelection == null) { ! status.addFatalError(e.getMessage()); ! return; ! } ! } ! try { ! if (parsedExtendedSelection != null) { ! VisitorFactory.validateSelection(parsedExtendedSelection); ! } ! } catch (SelectionException e) { ! this.parsedExtendedSelection = null; ! if (parsedUserSelection == null) { ! status.addFatalError(e.getMessage()); ! return; ! } ! } ! } ! public void setModule(ModuleAdapter module) { ! this.module = module; ! } ! public ModuleAdapter getModule() { ! return module; ! } ! @Override ! public String getName() { ! return Messages.extractMethodLabel; ! } } Index: ExtractMethodRequestProcessor.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/coderefactoring/extractmethod/ExtractMethodRequestProcessor.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** ExtractMethodRequestProcessor.java 20 Oct 2007 19:31:04 -0000 1.5 --- ExtractMethodRequestProcessor.java 27 Sep 2008 20:00:49 -0000 1.6 *************** *** 23,108 **** public class ExtractMethodRequestProcessor implements IRequestProcessor<ExtractMethodRequest> { ! private int offsetStrategy; ! private String methodName; ! private AbstractScopeNode<?> scopeAdapter; ! private ModuleAdapter parsedSelection; ! private ParameterReturnDeduce deducer; ! private Map<String, String> renameMap; ! private List<String> parameterOrder; ! private ITextSelection selection; private String endLineDelim; ! public ExtractMethodRequestProcessor(AbstractScopeNode<?> scopeAdapter, ModuleAdapter parsedSelection, ModuleAdapter module, ITextSelection selection) { ! initProcessor(scopeAdapter, parsedSelection, module, selection); ! } ! public void initProcessor(AbstractScopeNode<?> scopeAdapter, ModuleAdapter parsedSelection, ModuleAdapter module, ITextSelection selection) { ! this.methodName = "pepticMethod"; ! this.scopeAdapter = scopeAdapter; ! this.selection = selection; ! this.parsedSelection = parsedSelection; ! this.deducer = new ParameterReturnDeduce(this.scopeAdapter, selection, module); ! this.parameterOrder = new ArrayList<String>(); ! parameterOrder.addAll(deducer.getParameters()); ! this.renameMap = new TreeMap<String, String>(); ! initRenamedMap(); this.endLineDelim = module.getEndLineDelimiter(); ! offsetStrategy = IOffsetStrategy.AFTERINIT; ! } ! private void initRenamedMap() { ! for (String variable : deducer.getParameters()) { ! this.renameMap.put(variable, variable); ! } ! } ! public AbstractScopeNode<?> getScopeAdapter() { ! return scopeAdapter; ! } ! public String getMethodName() { ! return methodName; ! } ! public void setMethodName(String methodName) { ! this.methodName = methodName; ! } ! public int getOffsetStrategy() { ! return offsetStrategy; ! } ! public void setOffsetStrategy(int offsetStrategy) { ! this.offsetStrategy = offsetStrategy; ! } ! public List<ExtractMethodRequest> getRefactoringRequests() { ! List<ExtractMethodRequest> requests = new ArrayList<ExtractMethodRequest>(); ! requests.add(new ExtractMethodRequest(this.methodName, this.selection, this.scopeAdapter, this.parsedSelection, parameterOrder, ! deducer.getReturns(), this.renameMap, this.offsetStrategy, this.endLineDelim)); ! return requests; ! } ! public ParameterReturnDeduce getDeducer() { ! return deducer; ! } ! public void setParameterMap(Map<String, String> renameMap) { ! this.renameMap = renameMap; ! } ! public void setParameterOrder(List<String> parameterOrder) { ! this.parameterOrder = parameterOrder; ! } } --- 23,108 ---- public class ExtractMethodRequestProcessor implements IRequestProcessor<ExtractMethodRequest> { ! private int offsetStrategy; ! private String methodName; ! private AbstractScopeNode<?> scopeAdapter; ! private ModuleAdapter parsedSelection; ! private ParameterReturnDeduce deducer; ! private Map<String, String> renameMap; ! private List<String> parameterOrder; ! private ITextSelection selection; private String endLineDelim; ! public ExtractMethodRequestProcessor(AbstractScopeNode<?> scopeAdapter, ModuleAdapter parsedSelection, ModuleAdapter module, ITextSelection selection) { ! initProcessor(scopeAdapter, parsedSelection, module, selection); ! } ! public void initProcessor(AbstractScopeNode<?> scopeAdapter, ModuleAdapter parsedSelection, ModuleAdapter module, ITextSelection selection) { ! this.methodName = "pepticMethod"; ! this.scopeAdapter = scopeAdapter; ! this.selection = selection; ! this.parsedSelection = parsedSelection; ! this.deducer = new ParameterReturnDeduce(this.scopeAdapter, selection, module); ! this.parameterOrder = new ArrayList<String>(); ! parameterOrder.addAll(deducer.getParameters()); ! this.renameMap = new TreeMap<String, String>(); ! initRenamedMap(); this.endLineDelim = module.getEndLineDelimiter(); ! offsetStrategy = IOffsetStrategy.AFTERINIT; ! } ! private void initRenamedMap() { ! for (String variable : deducer.getParameters()) { ! this.renameMap.put(variable, variable); ! } ! } ! public AbstractScopeNode<?> getScopeAdapter() { ! return scopeAdapter; ! } ! public String getMethodName() { ! return methodName; ! } ! public void setMethodName(String methodName) { ! this.methodName = methodName; ! } ! public int getOffsetStrategy() { ! return offsetStrategy; ! } ! public void setOffsetStrategy(int offsetStrategy) { ! this.offsetStrategy = offsetStrategy; ! } ! public List<ExtractMethodRequest> getRefactoringRequests() { ! List<ExtractMethodRequest> requests = new ArrayList<ExtractMethodRequest>(); ! requests.add(new ExtractMethodRequest(this.methodName, this.selection, this.scopeAdapter, this.parsedSelection, parameterOrder, ! deducer.getReturns(), this.renameMap, this.offsetStrategy, this.endLineDelim)); ! return requests; ! } ! public ParameterReturnDeduce getDeducer() { ! return deducer; ! } ! public void setParameterMap(Map<String, String> renameMap) { ! this.renameMap = renameMap; ! } ! public void setParameterOrder(List<String> parameterOrder) { ! this.parameterOrder = parameterOrder; ! } } Index: ExtractMethodChangeProcessor.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/coderefactoring/extractmethod/ExtractMethodChangeProcessor.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** ExtractMethodChangeProcessor.java 20 Oct 2007 19:31:04 -0000 1.3 --- ExtractMethodChangeProcessor.java 27 Sep 2008 20:00:49 -0000 1.4 *************** *** 18,38 **** public class ExtractMethodChangeProcessor extends AbstractFileChangeProcessor<ExtractMethodRequest> { ! public ExtractMethodChangeProcessor(String name, RefactoringInfo info, IRequestProcessor<ExtractMethodRequest> requestProcessor) { ! super(name, info, requestProcessor); ! } ! @Override ! protected void processEdit() { ! for (ExtractMethodRequest req : requestProcessor.getRefactoringRequests()) { ! processExtraction(req); ! } ! } ! private void processExtraction(ExtractMethodRequest req) { ! ExtractMethodEdit extractMethodEdit = new ExtractMethodEdit(req); ! ExtractCallEdit extractCallEdit = new ExtractCallEdit(req); ! ! registerEdit(extractMethodEdit, Messages.extractMethodChangeName); ! registerEdit(extractCallEdit, Messages.extractMethodReplaceWithCall); ! } } --- 18,38 ---- public class ExtractMethodChangeProcessor extends AbstractFileChangeProcessor<ExtractMethodRequest> { ! public ExtractMethodChangeProcessor(String name, RefactoringInfo info, IRequestProcessor<ExtractMethodRequest> requestProcessor) { ! super(name, info, requestProcessor); ! } ! @Override ! protected void processEdit() { ! for (ExtractMethodRequest req : requestProcessor.getRefactoringRequests()) { ! processExtraction(req); ! } ! } ! private void processExtraction(ExtractMethodRequest req) { ! ExtractMethodEdit extractMethodEdit = new ExtractMethodEdit(req); ! ExtractCallEdit extractCallEdit = new ExtractCallEdit(req); ! ! registerEdit(extractMethodEdit, Messages.extractMethodChangeName); ! registerEdit(extractCallEdit, Messages.extractMethodReplaceWithCall); ! } } |
Update of /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/coderefactoring/extractmethod/edit In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv21605/src/org/python/pydev/refactoring/coderefactoring/extractmethod/edit Modified Files: ExtractMethodEdit.java ExtractCallEdit.java ParameterReturnDeduce.java Log Message: Synching to latest changes: Pydev <ul> <li><strong>Editor</strong>: Cursor settings no longer overridden</li> <li><strong>Code-completion</strong>: If __all__ is defined with runtime elements (and not only in a single assign statement), it's ignored for code-completion purposes</li> <li><strong>Debugger</strong>: Pythonpath the same in debug and regular modes (sys.path[0] is the same directory as the file run)</li> <li><strong>Debugger</strong>: Persist choices done in the debugger when files from the debugger are not found</li> <li><strong>Interpreter config</strong>: "email" automatically added to the "forced builtins"</li> <li><strong>Parser</strong>: Correctly recognizing absolute import with 3 or more levels</li> <li><strong>Syntax check</strong>: Option to do only on active editor</li> </ul> Also: tabs changed for spaces Index: ExtractMethodEdit.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/coderefactoring/extractmethod/edit/ExtractMethodEdit.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** ExtractMethodEdit.java 20 Oct 2007 19:31:01 -0000 1.5 --- ExtractMethodEdit.java 27 Sep 2008 20:00:46 -0000 1.6 *************** *** 34,149 **** public class ExtractMethodEdit extends AbstractInsertEdit { ! private String methodName; ! private ModuleAdapter parsedSelection; ! private int offsetStrategy; ! private AbstractScopeNode<?> scopeAdapter; ! private List<String> parameters; ! private List<String> returnVariables; ! private Map<String, String> renamedVariables; ! public ExtractMethodEdit(ExtractMethodRequest req) { ! super(req); ! this.methodName = req.getMethodName(); ! this.scopeAdapter = req.getScopeAdapter(); ! this.parsedSelection = req.getParsedSelection(); ! this.offsetStrategy = req.getOffsetStrategy(); ! this.parameters = req.getParameters(); ! this.returnVariables = req.getReturnVariables(); ! this.renamedVariables = req.getRenamedVariables(); ! } ! @Override ! protected SimpleNode getEditNode() { ! List<stmtType> body = initExtractedBody(); ! List<exprType> argsList = initExtractedMethodArguments(); ! addReturnValue(body); ! FunctionDef extractedMethod = initExtractedMethod(body, argsList); ! applyRenamedVariables(extractedMethod); ! return extractedMethod; ! } ! private FunctionDef initExtractedMethod(List<stmtType> body, List<exprType> argsList) { ! argumentsType args = new argumentsType(argsList.toArray(new exprType[0]), null, null, null); ! FunctionDef extractedMethod = new FunctionDef(new NameTok(methodName, NameTok.FunctionName), args, body.toArray(new stmtType[0]), ! null); ! return extractedMethod; ! } ! private List<exprType> initExtractedMethodArguments() { ! List<exprType> argsList = new ArrayList<exprType>(); ! if (this.scopeAdapter instanceof FunctionDefAdapter) { ! IASTNodeAdapter<? extends SimpleNode> parentScopeAdapter = scopeAdapter.getParent(); ! while (parentScopeAdapter instanceof FunctionDef) { ! parentScopeAdapter = scopeAdapter.getParent(); ! } ! if (parentScopeAdapter instanceof IClassDefAdapter) { ! argsList.add(new Name("self", Name.Load)); ! } ! } ! for (String variable : this.parameters) { ! argsList.add(new Name(variable, Name.Param)); ! } ! return argsList; ! } ! private List<stmtType> initExtractedBody() { ! stmtType[] extractBody = parsedSelection.getASTNode().body; ! List<stmtType> body = new ArrayList<stmtType>(); ! for (stmtType stmt : extractBody) { ! body.add(stmt); ! } ! return body; ! } ! private void applyRenamedVariables(FunctionDef extractedMethod) { ! if (renamedVariables.size() > 0) { ! LocalVarRenameVisitor renameVisitor = new LocalVarRenameVisitor(this.newLineDelim); ! renameVisitor.setRenameMap(renamedVariables); ! try { ! extractedMethod.accept(renameVisitor); ! } catch (Exception e) { ! } ! } ! } ! private void addReturnValue(List<stmtType> body) { ! List<exprType> returnList = new ArrayList<exprType>(); ! for (String variable : this.returnVariables) { ! returnList.add(new Name(variable, Name.Load)); ! } ! exprType returnValue = null; ! if (returnList.size() == 1) { ! returnValue = returnList.get(0); ! } else if (returnList.size() > 1) { ! returnValue = new Tuple(returnList.toArray(new exprType[0]), Tuple.Load); ! } else if (body.size() == 1) { ! // return expression as-is (note: body must be cleared) ! if (body.get(0) instanceof Expr) { ! Expr expression = (Expr) body.get(0); ! returnValue = expression.value; ! body.clear(); ! } ! } ! if (returnValue != null) { ! body.add(new Return(returnValue)); ! } ! } ! @Override ! public int getOffsetStrategy() { ! return offsetStrategy; ! } } --- 34,149 ---- public class ExtractMethodEdit extends AbstractInsertEdit { ! private String methodName; ! private ModuleAdapter parsedSelection; ! private int offsetStrategy; ! private AbstractScopeNode<?> scopeAdapter; ! private List<String> parameters; ! private List<String> returnVariables; ! private Map<String, String> renamedVariables; ! public ExtractMethodEdit(ExtractMethodRequest req) { ! super(req); ! this.methodName = req.getMethodName(); ! this.scopeAdapter = req.getScopeAdapter(); ! this.parsedSelection = req.getParsedSelection(); ! this.offsetStrategy = req.getOffsetStrategy(); ! this.parameters = req.getParameters(); ! this.returnVariables = req.getReturnVariables(); ! this.renamedVariables = req.getRenamedVariables(); ! } ! @Override ! protected SimpleNode getEditNode() { ! List<stmtType> body = initExtractedBody(); ! List<exprType> argsList = initExtractedMethodArguments(); ! addReturnValue(body); ! FunctionDef extractedMethod = initExtractedMethod(body, argsList); ! applyRenamedVariables(extractedMethod); ! return extractedMethod; ! } ! private FunctionDef initExtractedMethod(List<stmtType> body, List<exprType> argsList) { ! argumentsType args = new argumentsType(argsList.toArray(new exprType[0]), null, null, null); ! FunctionDef extractedMethod = new FunctionDef(new NameTok(methodName, NameTok.FunctionName), args, body.toArray(new stmtType[0]), ! null); ! return extractedMethod; ! } ! private List<exprType> initExtractedMethodArguments() { ! List<exprType> argsList = new ArrayList<exprType>(); ! if (this.scopeAdapter instanceof FunctionDefAdapter) { ! IASTNodeAdapter<? extends SimpleNode> parentScopeAdapter = scopeAdapter.getParent(); ! while (parentScopeAdapter instanceof FunctionDef) { ! parentScopeAdapter = scopeAdapter.getParent(); ! } ! if (parentScopeAdapter instanceof IClassDefAdapter) { ! argsList.add(new Name("self", Name.Load)); ! } ! } ! for (String variable : this.parameters) { ! argsList.add(new Name(variable, Name.Param)); ! } ! return argsList; ! } ! private List<stmtType> initExtractedBody() { ! stmtType[] extractBody = parsedSelection.getASTNode().body; ! List<stmtType> body = new ArrayList<stmtType>(); ! for (stmtType stmt : extractBody) { ! body.add(stmt); ! } ! return body; ! } ! private void applyRenamedVariables(FunctionDef extractedMethod) { ! if (renamedVariables.size() > 0) { ! LocalVarRenameVisitor renameVisitor = new LocalVarRenameVisitor(this.newLineDelim); ! renameVisitor.setRenameMap(renamedVariables); ! try { ! extractedMethod.accept(renameVisitor); ! } catch (Exception e) { ! } ! } ! } ! private void addReturnValue(List<stmtType> body) { ! List<exprType> returnList = new ArrayList<exprType>(); ! for (String variable : this.returnVariables) { ! returnList.add(new Name(variable, Name.Load)); ! } ! exprType returnValue = null; ! if (returnList.size() == 1) { ! returnValue = returnList.get(0); ! } else if (returnList.size() > 1) { ! returnValue = new Tuple(returnList.toArray(new exprType[0]), Tuple.Load); ! } else if (body.size() == 1) { ! // return expression as-is (note: body must be cleared) ! if (body.get(0) instanceof Expr) { ! Expr expression = (Expr) body.get(0); ! returnValue = expression.value; ! body.clear(); ! } ! } ! if (returnValue != null) { ! body.add(new Return(returnValue)); ! } ! } ! @Override ! public int getOffsetStrategy() { ! return offsetStrategy; ! } } Index: ParameterReturnDeduce.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/coderefactoring/extractmethod/edit/ParameterReturnDeduce.java,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** ParameterReturnDeduce.java 20 Oct 2007 19:31:01 -0000 1.6 --- ParameterReturnDeduce.java 27 Sep 2008 20:00:46 -0000 1.7 *************** *** 22,168 **** public class ParameterReturnDeduce { ! private List<String> parameters; ! private Set<String> returns; ! private AbstractScopeNode<?> scopeAdapter; ! private ITextSelection selection; ! private ModuleAdapter moduleAdapter; ! public ParameterReturnDeduce(AbstractScopeNode<?> scope, ITextSelection selection, ModuleAdapter moduleAdapter) { ! this.scopeAdapter = scope; ! this.selection = selection; ! this.parameters = new ArrayList<String>(); ! this.returns = new HashSet<String>(); ! this.moduleAdapter = moduleAdapter; ! deduce(); ! } ! private void deduce() { ! List<SimpleAdapter> before = new ArrayList<SimpleAdapter>(); ! List<SimpleAdapter> after = new ArrayList<SimpleAdapter>(); ! ModuleAdapter module = scopeAdapter.getModule(); ! List<SimpleAdapter> selected = module.getWithinSelection(this.selection, scopeAdapter.getUsedVariables()); ! extractBeforeAfterVariables(selected, before, after); ! deduceParameters(before, selected); ! deduceReturns(after, selected); ! } ! /** ! * Needed fix: only add it if it is not a global (unless it shadows a global) ! */ ! private void deduceParameters(List<SimpleAdapter> before, List<SimpleAdapter> selected) { ! Set<String> globarVarNames = new HashSet<String>(moduleAdapter.getGlobarVarNames()); ! ! for (SimpleAdapter adapter : before) { ! if (adapter.getASTNode() instanceof Name) { ! Name variable = (Name) adapter.getASTNode(); ! if(globarVarNames.contains(variable.id)){ ! continue; ! } ! if (isUsed(variable.id, selected)) { ! if (!parameters.contains(variable.id)) { ! parameters.add(variable.id); ! } ! } ! } ! } ! } ! private void deduceReturns(List<SimpleAdapter> after, List<SimpleAdapter> selected) { ! for (SimpleAdapter adapter : after) { ! if (adapter.getASTNode() instanceof Name) { ! Name variable = (Name) adapter.getASTNode(); ! if (isStored(variable.id, selected)) { ! returns.add(variable.id); ! } ! } ! } ! } ! private void extractBeforeAfterVariables(List<SimpleAdapter> selectedVariables, List<SimpleAdapter> before, List<SimpleAdapter> after) { ! List<SimpleAdapter> scopeVariables = scopeAdapter.getUsedVariables(); ! if (selectedVariables.size() < 1) ! return; ! SimpleAdapter firstSelectedVariable = selectedVariables.get(0); ! SimpleAdapter lastSelectedVariable = selectedVariables.get(selectedVariables.size() - 1); ! for (SimpleAdapter adapter : scopeVariables) { ! if (isBeforeSelectedLine(firstSelectedVariable, adapter) || isBeforeOnSameLine(firstSelectedVariable, adapter)) { ! before.add(adapter); ! ! } else if (isAfterSelectedLine(lastSelectedVariable, adapter) || isAfterOnSameLine(lastSelectedVariable, adapter)) { ! after.add(adapter); ! } ! } ! } ! private boolean isAfterOnSameLine(SimpleAdapter lastSelectedVariable, SimpleAdapter adapter) { ! return adapter.getNodeFirstLine() == lastSelectedVariable.getNodeFirstLine() ! && (adapter.getNodeIndent() > lastSelectedVariable.getNodeIndent()); ! } ! private boolean isAfterSelectedLine(SimpleAdapter lastSelectedVariable, SimpleAdapter adapter) { ! return adapter.getNodeFirstLine() > lastSelectedVariable.getNodeFirstLine(); ! } ! private boolean isBeforeOnSameLine(SimpleAdapter firstSelectedVariable, SimpleAdapter adapter) { ! return adapter.getNodeFirstLine() == firstSelectedVariable.getNodeFirstLine() ! && (adapter.getNodeIndent() < firstSelectedVariable.getNodeIndent()); ! } ! private boolean isBeforeSelectedLine(SimpleAdapter firstSelectedVariable, SimpleAdapter adapter) { ! return adapter.getNodeFirstLine() < firstSelectedVariable.getNodeFirstLine(); ! } ! /** ! * Fix (fabioz): to check if it is used, it must be in a load context ! */ ! private boolean isUsed(String var, List<SimpleAdapter> scopeVariables) { ! for (SimpleAdapter adapter : scopeVariables) { ! SimpleNode astNode = adapter.getASTNode(); ! if (astNode instanceof Name) { ! Name scopeVar = (Name) astNode; ! if ((scopeVar.ctx == Name.Load || scopeVar.ctx == Name.AugLoad) && scopeVar.id.equals(var)) { ! return true; ! } ! } ! } ! return false; ! } ! private boolean isStored(String var, List<SimpleAdapter> scopeVariables) { ! boolean isStored = false; ! // must traverse all variables, because a ! // variable may be used in other context! ! for (SimpleAdapter adapter : scopeVariables) { ! SimpleNode astNode = adapter.getASTNode(); ! if (astNode instanceof Name) { ! Name scopeVar = (Name) astNode; ! if (scopeVar.id.equals(var)) { ! isStored = (scopeVar.ctx == Name.Store || scopeVar.ctx == Name.AugStore); ! } ! } ! if (isStored) ! break; ! } ! return isStored; ! } ! public List<String> getParameters() { ! return this.parameters; ! } ! public List<String> getReturns() { ! return new ArrayList<String>(this.returns); ! } } --- 22,168 ---- public class ParameterReturnDeduce { ! private List<String> parameters; ! private Set<String> returns; ! private AbstractScopeNode<?> scopeAdapter; ! private ITextSelection selection; ! private ModuleAdapter moduleAdapter; ! public ParameterReturnDeduce(AbstractScopeNode<?> scope, ITextSelection selection, ModuleAdapter moduleAdapter) { ! this.scopeAdapter = scope; ! this.selection = selection; ! this.parameters = new ArrayList<String>(); ! this.returns = new HashSet<String>(); ! this.moduleAdapter = moduleAdapter; ! deduce(); ! } ! private void deduce() { ! List<SimpleAdapter> before = new ArrayList<SimpleAdapter>(); ! List<SimpleAdapter> after = new ArrayList<SimpleAdapter>(); ! ModuleAdapter module = scopeAdapter.getModule(); ! List<SimpleAdapter> selected = module.getWithinSelection(this.selection, scopeAdapter.getUsedVariables()); ! extractBeforeAfterVariables(selected, before, after); ! deduceParameters(before, selected); ! deduceReturns(after, selected); ! } ! /** ! * Needed fix: only add it if it is not a global (unless it shadows a global) ! */ ! private void deduceParameters(List<SimpleAdapter> before, List<SimpleAdapter> selected) { ! Set<String> globarVarNames = new HashSet<String>(moduleAdapter.getGlobarVarNames()); ! ! for (SimpleAdapter adapter : before) { ! if (adapter.getASTNode() instanceof Name) { ! Name variable = (Name) adapter.getASTNode(); ! if(globarVarNames.contains(variable.id)){ ! continue; ! } ! if (isUsed(variable.id, selected)) { ! if (!parameters.contains(variable.id)) { ! parameters.add(variable.id); ! } ! } ! } ! } ! } ! private void deduceReturns(List<SimpleAdapter> after, List<SimpleAdapter> selected) { ! for (SimpleAdapter adapter : after) { ! if (adapter.getASTNode() instanceof Name) { ! Name variable = (Name) adapter.getASTNode(); ! if (isStored(variable.id, selected)) { ! returns.add(variable.id); ! } ! } ! } ! } ! private void extractBeforeAfterVariables(List<SimpleAdapter> selectedVariables, List<SimpleAdapter> before, List<SimpleAdapter> after) { ! List<SimpleAdapter> scopeVariables = scopeAdapter.getUsedVariables(); ! if (selectedVariables.size() < 1) ! return; ! SimpleAdapter firstSelectedVariable = selectedVariables.get(0); ! SimpleAdapter lastSelectedVariable = selectedVariables.get(selectedVariables.size() - 1); ! for (SimpleAdapter adapter : scopeVariables) { ! if (isBeforeSelectedLine(firstSelectedVariable, adapter) || isBeforeOnSameLine(firstSelectedVariable, adapter)) { ! before.add(adapter); ! ! } else if (isAfterSelectedLine(lastSelectedVariable, adapter) || isAfterOnSameLine(lastSelectedVariable, adapter)) { ! after.add(adapter); ! } ! } ! } ! private boolean isAfterOnSameLine(SimpleAdapter lastSelectedVariable, SimpleAdapter adapter) { ! return adapter.getNodeFirstLine() == lastSelectedVariable.getNodeFirstLine() ! && (adapter.getNodeIndent() > lastSelectedVariable.getNodeIndent()); ! } ! private boolean isAfterSelectedLine(SimpleAdapter lastSelectedVariable, SimpleAdapter adapter) { ! return adapter.getNodeFirstLine() > lastSelectedVariable.getNodeFirstLine(); ! } ! private boolean isBeforeOnSameLine(SimpleAdapter firstSelectedVariable, SimpleAdapter adapter) { ! return adapter.getNodeFirstLine() == firstSelectedVariable.getNodeFirstLine() ! && (adapter.getNodeIndent() < firstSelectedVariable.getNodeIndent()); ! } ! private boolean isBeforeSelectedLine(SimpleAdapter firstSelectedVariable, SimpleAdapter adapter) { ! return adapter.getNodeFirstLine() < firstSelectedVariable.getNodeFirstLine(); ! } ! /** ! * Fix (fabioz): to check if it is used, it must be in a load context ! */ ! private boolean isUsed(String var, List<SimpleAdapter> scopeVariables) { ! for (SimpleAdapter adapter : scopeVariables) { ! SimpleNode astNode = adapter.getASTNode(); ! if (astNode instanceof Name) { ! Name scopeVar = (Name) astNode; ! if ((scopeVar.ctx == Name.Load || scopeVar.ctx == Name.AugLoad) && scopeVar.id.equals(var)) { ! return true; ! } ! } ! } ! return false; ! } ! private boolean isStored(String var, List<SimpleAdapter> scopeVariables) { ! boolean isStored = false; ! // must traverse all variables, because a ! // variable may be used in other context! ! for (SimpleAdapter adapter : scopeVariables) { ! SimpleNode astNode = adapter.getASTNode(); ! if (astNode instanceof Name) { ! Name scopeVar = (Name) astNode; ! if (scopeVar.id.equals(var)) { ! isStored = (scopeVar.ctx == Name.Store || scopeVar.ctx == Name.AugStore); ! } ! } ! if (isStored) ! break; ! } ! return isStored; ! } ! public List<String> getParameters() { ! return this.parameters; ! } ! public List<String> getReturns() { ! return new ArrayList<String>(this.returns); ! } } Index: ExtractCallEdit.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/coderefactoring/extractmethod/edit/ExtractCallEdit.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** ExtractCallEdit.java 20 Oct 2007 19:31:01 -0000 1.4 --- ExtractCallEdit.java 27 Sep 2008 20:00:46 -0000 1.5 *************** *** 25,105 **** public class ExtractCallEdit extends AbstractReplaceEdit { ! private String methodName; ! private int offset; ! private IASTNodeAdapter<?> offsetAdapter; ! private int replaceLength; ! private List<String> callParameters; ! private List<String> returnVariables; ! public ExtractCallEdit(ExtractMethodRequest req) { ! super(req); ! this.methodName = req.getMethodName(); ! this.offset = req.getSelection().getOffset(); ! this.replaceLength = req.getSelection().getLength(); ! this.offsetAdapter = req.getOffsetNode(); ! this.callParameters = req.getParameters(); ! this.returnVariables = req.getReturnVariables(); ! } ! @Override ! protected SimpleNode getEditNode() { ! List<exprType> argsList = initCallArguments(); ! Call methodCall = new Call(createCallAttribute(), argsList.toArray(new exprType[0]), null, null, null); ! return initSubstituteCall(methodCall); ! } ! private SimpleNode initSubstituteCall(Call methodCall) { ! if (returnVariables.size() == 0) { ! return methodCall; ! } else { ! List<exprType> returnExpr = new ArrayList<exprType>(); ! for (String returnVar : returnVariables) { ! returnExpr.add(new Name(returnVar, Name.Store)); ! } ! return new Assign(returnExpr.toArray(new exprType[0]), methodCall); ! } ! } ! private List<exprType> initCallArguments() { ! List<exprType> argsList = new ArrayList<exprType>(); ! for (String parameter : callParameters) { ! argsList.add(new Name(parameter, Name.Load)); ! } ! return argsList; ! } ! private exprType createCallAttribute() { ! if (this.offsetAdapter instanceof IClassDefAdapter) { ! return new Attribute(new Name("self", Name.Load), new NameTok(this.methodName, NameTok.Attrib), Attribute.Load); ! } else { ! return new Name(this.methodName, Name.Load); ! } ! } ! @Override ! public int getOffsetStrategy() { ! return 0; ! } ! @Override ! public int getOffset() { ! return offset; ! } ! @Override ! protected int getReplaceLength() { ! return replaceLength; ! } } --- 25,105 ---- public class ExtractCallEdit extends AbstractReplaceEdit { ! private String methodName; ! private int offset; ! private IASTNodeAdapter<?> offsetAdapter; ! private int replaceLength; ! private List<String> callParameters; ! private List<String> returnVariables; ! public ExtractCallEdit(ExtractMethodRequest req) { ! super(req); ! this.methodName = req.getMethodName(); ! this.offset = req.getSelection().getOffset(); ! this.replaceLength = req.getSelection().getLength(); ! this.offsetAdapter = req.getOffsetNode(); ! this.callParameters = req.getParameters(); ! this.returnVariables = req.getReturnVariables(); ! } ! @Override ! protected SimpleNode getEditNode() { ! List<exprType> argsList = initCallArguments(); ! Call methodCall = new Call(createCallAttribute(), argsList.toArray(new exprType[0]), null, null, null); ! return initSubstituteCall(methodCall); ! } ! private SimpleNode initSubstituteCall(Call methodCall) { ! if (returnVariables.size() == 0) { ! return methodCall; ! } else { ! List<exprType> returnExpr = new ArrayList<exprType>(); ! for (String returnVar : returnVariables) { ! returnExpr.add(new Name(returnVar, Name.Store)); ! } ! return new Assign(returnExpr.toArray(new exprType[0]), methodCall); ! } ! } ! private List<exprType> initCallArguments() { ! List<exprType> argsList = new ArrayList<exprType>(); ! for (String parameter : callParameters) { ! argsList.add(new Name(parameter, Name.Load)); ! } ! return argsList; ! } ! private exprType createCallAttribute() { ! if (this.offsetAdapter instanceof IClassDefAdapter) { ! return new Attribute(new Name("self", Name.Load), new NameTok(this.methodName, NameTok.Attrib), Attribute.Load); ! } else { ! return new Name(this.methodName, Name.Load); ! } ! } ! @Override ! public int getOffsetStrategy() { ! return 0; ! } ! @Override ! public int getOffset() { ! return offset; ! } ! @Override ! protected int getReplaceLength() { ! return replaceLength; ! } } |
From: Fabio Z. <fa...@us...> - 2008-09-27 20:03:25
|
Update of /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/core In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv21605/src/org/python/pydev/refactoring/core Modified Files: RefactoringInfo.java AbstractPythonRefactoring.java Log Message: Synching to latest changes: Pydev <ul> <li><strong>Editor</strong>: Cursor settings no longer overridden</li> <li><strong>Code-completion</strong>: If __all__ is defined with runtime elements (and not only in a single assign statement), it's ignored for code-completion purposes</li> <li><strong>Debugger</strong>: Pythonpath the same in debug and regular modes (sys.path[0] is the same directory as the file run)</li> <li><strong>Debugger</strong>: Persist choices done in the debugger when files from the debugger are not found</li> <li><strong>Interpreter config</strong>: "email" automatically added to the "forced builtins"</li> <li><strong>Parser</strong>: Correctly recognizing absolute import with 3 or more levels</li> <li><strong>Syntax check</strong>: Option to do only on active editor</li> </ul> Also: tabs changed for spaces Index: RefactoringInfo.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/core/RefactoringInfo.java,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** RefactoringInfo.java 14 Jun 2008 22:14:34 -0000 1.7 --- RefactoringInfo.java 27 Sep 2008 20:00:46 -0000 1.8 *************** *** 31,223 **** public class RefactoringInfo { ! private IFile sourceFile; ! private IDocument doc; ! private ITextSelection userSelection; ! private ITextSelection extendedSelection; ! private ModuleAdapter moduleAdapter; ! private IPythonNature nature; ! private PythonModuleManager moduleManager; ! private AbstractScopeNode<?> scopeAdapter; ! public RefactoringInfo(ITextEditor edit, IPythonNature nature) { ! this(((IFileEditorInput) edit.getEditorInput()).getFile(), edit.getDocumentProvider().getDocument(edit.getEditorInput()), ! (ITextSelection) edit.getSelectionProvider().getSelection(), nature); ! } ! public RefactoringInfo(IFile sourceFile, IDocument doc, ITextSelection selection, IPythonNature nature) { ! this.sourceFile = sourceFile; ! this.doc = doc; ! this.nature = nature; ! initInfo(selection, userSelection); ! } ! private void initInfo(ITextSelection selection, ITextSelection userSelection) { ! if (this.nature != null) { ! this.moduleManager = new PythonModuleManager(nature); ! } ! File realFile = null; ! if (sourceFile != null) { ! realFile = sourceFile.getRawLocation().toFile(); ! } ! try { ! this.moduleAdapter = VisitorFactory.createModuleAdapter(moduleManager, realFile, doc, nature); ! } catch (ParseException e) { ! throw new RuntimeException(e); ! } ! this.extendedSelection = null; ! this.userSelection = moduleAdapter.normalizeSelection(selection); ! } ! public ModuleAdapter getModule() { ! return moduleAdapter; ! } ! public List<IClassDefAdapter> getClasses() { ! return moduleAdapter.getClasses(); ! } ! public IFile getSourceFile() { ! return this.sourceFile; ! } ! public IDocument getDocument() { ! return this.doc; ! } ! public ITextSelection getExtendedSelection() { ! if (this.extendedSelection == null) { ! this.extendedSelection = new TextSelection(this.doc, this.getUserSelection().getOffset(), this.userSelection.getLength()); ! if (getScopeAdapter() != null) { ! this.extendedSelection = moduleAdapter.normalizeSelection(VisitorFactory.createSelectionExtension(getScopeAdapter(), ! this.extendedSelection)); ! } ! } ! return extendedSelection; ! } ! public ITextSelection getUserSelection() { ! return userSelection; ! } ! public ModuleAdapter getParsedExtendedSelection() { ! return getParsedExtendedSelection(getScopeAdapter()); ! } ! public ModuleAdapter getParsedUserSelection() { ! ModuleAdapter parsedAdapter = null; ! String source = normalizeSourceSelection(getScopeAdapter(), this.userSelection); ! if (this.userSelection != null && source.length() > 0) { ! try { ! parsedAdapter = VisitorFactory.createModuleAdapter(moduleManager, null, new Document(source), nature); ! } catch (ParseException e) { ! /* Parse Exception means the current selection is invalid, discard and return null */ ! } ! } ! return parsedAdapter; ! } ! private ModuleAdapter getParsedExtendedSelection(AbstractScopeNode<?> scopeNode) { ! ModuleAdapter parsedAdapter = null; ! String source = normalizeSourceSelection(scopeNode, this.getExtendedSelection()); ! if (this.getExtendedSelection() != null && source.length() > 0) { ! try { ! parsedAdapter = VisitorFactory.createModuleAdapter(moduleManager, null, new Document(source), nature); ! } catch (ParseException e) { ! /* Parse Exception means the current selection is invalid, discard and return null */ ! } ! } ! return parsedAdapter; ! } ! public String normalizeSourceSelection(AbstractScopeNode<?> scopeNode, ITextSelection selection) { ! String selectedText = ""; ! if (selection.getText() != null) { ! selectedText = selection.getText().trim(); ! } ! if (selectedText.length() == 0) { ! return ""; ! } ! try { ! return normalizeBlockIndentation(selection, selectedText); ! } catch (Throwable e) { ! /* TODO: uncommented empty exception catch all */ ! } ! return selectedText; ! } ! private String normalizeBlockIndentation(ITextSelection selection, String selectedText) throws Throwable { ! String[] lines = selectedText.split("\\n"); ! if (lines.length < 2) { ! return selectedText; ! } ! String firstLine = doc.get(doc.getLineOffset(selection.getStartLine()), doc.getLineLength(selection.getStartLine())); String lineDelimiter = TextUtilities.getDefaultLineDelimiter(doc); ! String indentation = ""; ! int bodyIndent = 0; ! while (firstLine.startsWith(" ")) { ! indentation += " "; ! firstLine = firstLine.substring(1); ! bodyIndent += 1; ! } ! if (bodyIndent > 0) { ! FastStringBuffer selectedCode = new FastStringBuffer(); ! for (String line : lines) { ! if (line.startsWith(indentation)) { ! selectedCode.append(line.substring(bodyIndent) + lineDelimiter); ! } else { ! selectedCode.append(line + lineDelimiter); ! } ! } ! selectedText = selectedCode.toString(); ! } ! return selectedText; ! } ! public IClassDefAdapter getScopeClass() { ! return moduleAdapter.getScopeClass(getUserSelection()); ! } ! public IPythonNature getNature() { ! return nature; ! } ! public List<IClassDefAdapter> getScopeClassAndBases() { ! return moduleAdapter.getClassHierarchy(getScopeClass()); ! } ! public AbstractScopeNode<?> getScopeAdapter() { ! if (scopeAdapter == null) { ! scopeAdapter = moduleAdapter.getScopeAdapter(getUserSelection()); ! } ! return scopeAdapter; ! } ! public boolean isSelectionExtensionRequired() { ! return !(this.getUserSelection().getOffset() == this.getExtendedSelection().getOffset() && this.getUserSelection().getLength() == this ! .getExtendedSelection().getLength()); ! } public String getNewLineDelim() { --- 31,223 ---- public class RefactoringInfo { ! private IFile sourceFile; ! private IDocument doc; ! private ITextSelection userSelection; ! private ITextSelection extendedSelection; ! private ModuleAdapter moduleAdapter; ! private IPythonNature nature; ! private PythonModuleManager moduleManager; ! private AbstractScopeNode<?> scopeAdapter; ! public RefactoringInfo(ITextEditor edit, IPythonNature nature) { ! this(((IFileEditorInput) edit.getEditorInput()).getFile(), edit.getDocumentProvider().getDocument(edit.getEditorInput()), ! (ITextSelection) edit.getSelectionProvider().getSelection(), nature); ! } ! public RefactoringInfo(IFile sourceFile, IDocument doc, ITextSelection selection, IPythonNature nature) { ! this.sourceFile = sourceFile; ! this.doc = doc; ! this.nature = nature; ! initInfo(selection, userSelection); ! } ! private void initInfo(ITextSelection selection, ITextSelection userSelection) { ! if (this.nature != null) { ! this.moduleManager = new PythonModuleManager(nature); ! } ! File realFile = null; ! if (sourceFile != null) { ! realFile = sourceFile.getRawLocation().toFile(); ! } ! try { ! this.moduleAdapter = VisitorFactory.createModuleAdapter(moduleManager, realFile, doc, nature); ! } catch (ParseException e) { ! throw new RuntimeException(e); ! } ! this.extendedSelection = null; ! this.userSelection = moduleAdapter.normalizeSelection(selection); ! } ! public ModuleAdapter getModule() { ! return moduleAdapter; ! } ! public List<IClassDefAdapter> getClasses() { ! return moduleAdapter.getClasses(); ! } ! public IFile getSourceFile() { ! return this.sourceFile; ! } ! public IDocument getDocument() { ! return this.doc; ! } ! public ITextSelection getExtendedSelection() { ! if (this.extendedSelection == null) { ! this.extendedSelection = new TextSelection(this.doc, this.getUserSelection().getOffset(), this.userSelection.getLength()); ! if (getScopeAdapter() != null) { ! this.extendedSelection = moduleAdapter.normalizeSelection(VisitorFactory.createSelectionExtension(getScopeAdapter(), ! this.extendedSelection)); ! } ! } ! return extendedSelection; ! } ! public ITextSelection getUserSelection() { ! return userSelection; ! } ! public ModuleAdapter getParsedExtendedSelection() { ! return getParsedExtendedSelection(getScopeAdapter()); ! } ! public ModuleAdapter getParsedUserSelection() { ! ModuleAdapter parsedAdapter = null; ! String source = normalizeSourceSelection(getScopeAdapter(), this.userSelection); ! if (this.userSelection != null && source.length() > 0) { ! try { ! parsedAdapter = VisitorFactory.createModuleAdapter(moduleManager, null, new Document(source), nature); ! } catch (ParseException e) { ! /* Parse Exception means the current selection is invalid, discard and return null */ ! } ! } ! return parsedAdapter; ! } ! private ModuleAdapter getParsedExtendedSelection(AbstractScopeNode<?> scopeNode) { ! ModuleAdapter parsedAdapter = null; ! String source = normalizeSourceSelection(scopeNode, this.getExtendedSelection()); ! if (this.getExtendedSelection() != null && source.length() > 0) { ! try { ! parsedAdapter = VisitorFactory.createModuleAdapter(moduleManager, null, new Document(source), nature); ! } catch (ParseException e) { ! /* Parse Exception means the current selection is invalid, discard and return null */ ! } ! } ! return parsedAdapter; ! } ! public String normalizeSourceSelection(AbstractScopeNode<?> scopeNode, ITextSelection selection) { ! String selectedText = ""; ! if (selection.getText() != null) { ! selectedText = selection.getText().trim(); ! } ! if (selectedText.length() == 0) { ! return ""; ! } ! try { ! return normalizeBlockIndentation(selection, selectedText); ! } catch (Throwable e) { ! /* TODO: uncommented empty exception catch all */ ! } ! return selectedText; ! } ! private String normalizeBlockIndentation(ITextSelection selection, String selectedText) throws Throwable { ! String[] lines = selectedText.split("\\n"); ! if (lines.length < 2) { ! return selectedText; ! } ! String firstLine = doc.get(doc.getLineOffset(selection.getStartLine()), doc.getLineLength(selection.getStartLine())); String lineDelimiter = TextUtilities.getDefaultLineDelimiter(doc); ! String indentation = ""; ! int bodyIndent = 0; ! while (firstLine.startsWith(" ")) { ! indentation += " "; ! firstLine = firstLine.substring(1); ! bodyIndent += 1; ! } ! if (bodyIndent > 0) { ! FastStringBuffer selectedCode = new FastStringBuffer(); ! for (String line : lines) { ! if (line.startsWith(indentation)) { ! selectedCode.append(line.substring(bodyIndent) + lineDelimiter); ! } else { ! selectedCode.append(line + lineDelimiter); ! } ! } ! selectedText = selectedCode.toString(); ! } ! return selectedText; ! } ! public IClassDefAdapter getScopeClass() { ! return moduleAdapter.getScopeClass(getUserSelection()); ! } ! public IPythonNature getNature() { ! return nature; ! } ! public List<IClassDefAdapter> getScopeClassAndBases() { ! return moduleAdapter.getClassHierarchy(getScopeClass()); ! } ! public AbstractScopeNode<?> getScopeAdapter() { ! if (scopeAdapter == null) { ! scopeAdapter = moduleAdapter.getScopeAdapter(getUserSelection()); ! } ! return scopeAdapter; ! } ! public boolean isSelectionExtensionRequired() { ! return !(this.getUserSelection().getOffset() == this.getExtendedSelection().getOffset() && this.getUserSelection().getLength() == this ! .getExtendedSelection().getLength()); ! } public String getNewLineDelim() { Index: AbstractPythonRefactoring.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/core/AbstractPythonRefactoring.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** AbstractPythonRefactoring.java 20 Oct 2007 19:31:00 -0000 1.3 --- AbstractPythonRefactoring.java 27 Sep 2008 20:00:46 -0000 1.4 *************** *** 24,59 **** public abstract class AbstractPythonRefactoring extends Refactoring { ! protected RefactoringStatus status; ! protected Collection<IWizardPage> pages; ! protected RefactoringInfo info; ! public AbstractPythonRefactoring(RefactoringInfo info) { ! status = new RefactoringStatus(); ! pages = new ArrayList<IWizardPage>(); ! this.info = info; ! } ! @Override ! public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException, OperationCanceledException { ! return status; ! } ! @Override ! public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException, OperationCanceledException { ! return status; ! } ! @Override ! public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException { ! IChangeProcessor changeProcessor = new CompositeChangeProcessor(getName(), getChangeProcessors()); ! ! return changeProcessor.createChange(); ! } ! protected abstract List<IChangeProcessor> getChangeProcessors(); ! public Collection<IWizardPage> getPages() { ! return pages; ! } } --- 24,59 ---- public abstract class AbstractPythonRefactoring extends Refactoring { ! protected RefactoringStatus status; ! protected Collection<IWizardPage> pages; ! protected RefactoringInfo info; ! public AbstractPythonRefactoring(RefactoringInfo info) { ! status = new RefactoringStatus(); ! pages = new ArrayList<IWizardPage>(); ! this.info = info; ! } ! @Override ! public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException, OperationCanceledException { ! return status; ! } ! @Override ! public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException, OperationCanceledException { ! return status; ! } ! @Override ! public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException { ! IChangeProcessor changeProcessor = new CompositeChangeProcessor(getName(), getChangeProcessors()); ! ! return changeProcessor.createChange(); ! } ! protected abstract List<IChangeProcessor> getChangeProcessors(); ! public Collection<IWizardPage> getPages() { ! return pages; ! } } |
From: Fabio Z. <fa...@us...> - 2008-09-27 20:03:13
|
Update of /cvsroot/pydev/org.python.pydev.refactoring/tests/org/python/pydev/refactoring/tests/coderefactoring/extractmethod In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv21605/tests/org/python/pydev/refactoring/tests/coderefactoring/extractmethod Modified Files: MockupExtractMethodRequestProcessor.java ExtractMethodTestSuite.java ExtractMethodTestCase.java MockupExtractMethodConfig.java Log Message: Synching to latest changes: Pydev <ul> <li><strong>Editor</strong>: Cursor settings no longer overridden</li> <li><strong>Code-completion</strong>: If __all__ is defined with runtime elements (and not only in a single assign statement), it's ignored for code-completion purposes</li> <li><strong>Debugger</strong>: Pythonpath the same in debug and regular modes (sys.path[0] is the same directory as the file run)</li> <li><strong>Debugger</strong>: Persist choices done in the debugger when files from the debugger are not found</li> <li><strong>Interpreter config</strong>: "email" automatically added to the "forced builtins"</li> <li><strong>Parser</strong>: Correctly recognizing absolute import with 3 or more levels</li> <li><strong>Syntax check</strong>: Option to do only on active editor</li> </ul> Also: tabs changed for spaces Index: ExtractMethodTestCase.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/tests/org/python/pydev/refactoring/tests/coderefactoring/extractmethod/ExtractMethodTestCase.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** ExtractMethodTestCase.java 20 Oct 2007 19:31:00 -0000 1.5 --- ExtractMethodTestCase.java 27 Sep 2008 20:00:51 -0000 1.6 *************** *** 32,116 **** public class ExtractMethodTestCase extends AbstractIOTestCase { ! public ExtractMethodTestCase(String name) { ! super(name); ! } ! @Override ! public void runTest() throws Throwable { ! REF.IN_TESTS = true; ! MockupExtractMethodConfig config = initConfig(); ! IDocument doc = new Document(getSource()); ! Module astModule = VisitorFactory.getRootNode(doc); ! String name = getFile().getName(); ! name = name.substring(0, name.length()-4); ! ModuleAdapter module = VisitorFactory.createModuleAdapter(null, new SourceModule(name, getFile(), astModule), new PythonNatureStub()); ! ITextSelection selection = new TextSelection(doc, config.getOffset(), config.getSelectionLength()); ! RefactoringInfo info = new RefactoringInfo(null, doc, selection, null); ! MockupExtractMethodRequestProcessor requestProcessor = setupRequestProcessor(config, module, info); ! IDocument refactoringDoc = applyExtractMethod(info, requestProcessor); ! this.setTestGenerated(refactoringDoc.get()); ! assertEquals(getExpected(), getGenerated()); ! REF.IN_TESTS = false; ! } ! private IDocument applyExtractMethod(RefactoringInfo info, MockupExtractMethodRequestProcessor requestProcessor) ! throws BadLocationException { ! ExtractMethodRequest req = requestProcessor.getRefactoringRequests().get(0); ! ExtractMethodEdit extractMethodEdit = new ExtractMethodEdit(req); ! ExtractCallEdit extractCallEdit = new ExtractCallEdit(req); ! MultiTextEdit edit = new MultiTextEdit(); ! edit.addChild(extractMethodEdit.getEdit()); ! edit.addChild(extractCallEdit.getEdit()); ! IDocument refactoringDoc = new Document(getSource()); ! edit.apply(refactoringDoc); ! return refactoringDoc; ! } ! private MockupExtractMethodRequestProcessor setupRequestProcessor(MockupExtractMethodConfig config, ModuleAdapter module, ! RefactoringInfo info) { ! ModuleAdapter parsedSelection = info.getParsedExtendedSelection(); ! AbstractScopeNode<?> scope = module.getScopeAdapter(info.getExtendedSelection()); ! ParameterReturnDeduce deducer = new ParameterReturnDeduce(scope, info.getExtendedSelection(), module); ! SortedMap<String, String> renameMap = new TreeMap<String, String>(); ! for (String variable : deducer.getParameters()) { ! String newName = variable; ! if (config.getRenameMap().containsKey(variable)) { ! newName = config.getRenameMap().get(variable); ! } ! renameMap.put(variable, newName); ! } ! return new MockupExtractMethodRequestProcessor(scope, info.getExtendedSelection(), parsedSelection, deducer, renameMap, config ! .getOffsetStrategy()); ! } ! private MockupExtractMethodConfig initConfig() { ! MockupExtractMethodConfig config = null; ! XStream xstream = new XStream(); ! xstream.alias("config", MockupExtractMethodConfig.class); ! if (getConfig().length() > 0) { ! config = (MockupExtractMethodConfig) xstream.fromXML(getConfig()); ! } else { ! fail("Could not unserialize configuration"); ! } ! return config; ! } ! @Override ! public String getExpected() { ! return getResult(); ! } } --- 32,116 ---- public class ExtractMethodTestCase extends AbstractIOTestCase { ! public ExtractMethodTestCase(String name) { ! super(name); ! } ! @Override ! public void runTest() throws Throwable { ! REF.IN_TESTS = true; ! MockupExtractMethodConfig config = initConfig(); ! IDocument doc = new Document(getSource()); ! Module astModule = VisitorFactory.getRootNode(doc); ! String name = getFile().getName(); ! name = name.substring(0, name.length()-4); ! ModuleAdapter module = VisitorFactory.createModuleAdapter(null, new SourceModule(name, getFile(), astModule, null), new PythonNatureStub()); ! ITextSelection selection = new TextSelection(doc, config.getOffset(), config.getSelectionLength()); ! RefactoringInfo info = new RefactoringInfo(null, doc, selection, null); ! MockupExtractMethodRequestProcessor requestProcessor = setupRequestProcessor(config, module, info); ! IDocument refactoringDoc = applyExtractMethod(info, requestProcessor); ! this.setTestGenerated(refactoringDoc.get()); ! assertEquals(getExpected(), getGenerated()); ! REF.IN_TESTS = false; ! } ! private IDocument applyExtractMethod(RefactoringInfo info, MockupExtractMethodRequestProcessor requestProcessor) ! throws BadLocationException { ! ExtractMethodRequest req = requestProcessor.getRefactoringRequests().get(0); ! ExtractMethodEdit extractMethodEdit = new ExtractMethodEdit(req); ! ExtractCallEdit extractCallEdit = new ExtractCallEdit(req); ! MultiTextEdit edit = new MultiTextEdit(); ! edit.addChild(extractMethodEdit.getEdit()); ! edit.addChild(extractCallEdit.getEdit()); ! IDocument refactoringDoc = new Document(getSource()); ! edit.apply(refactoringDoc); ! return refactoringDoc; ! } ! private MockupExtractMethodRequestProcessor setupRequestProcessor(MockupExtractMethodConfig config, ModuleAdapter module, ! RefactoringInfo info) { ! ModuleAdapter parsedSelection = info.getParsedExtendedSelection(); ! AbstractScopeNode<?> scope = module.getScopeAdapter(info.getExtendedSelection()); ! ParameterReturnDeduce deducer = new ParameterReturnDeduce(scope, info.getExtendedSelection(), module); ! SortedMap<String, String> renameMap = new TreeMap<String, String>(); ! for (String variable : deducer.getParameters()) { ! String newName = variable; ! if (config.getRenameMap().containsKey(variable)) { ! newName = config.getRenameMap().get(variable); ! } ! renameMap.put(variable, newName); ! } ! return new MockupExtractMethodRequestProcessor(scope, info.getExtendedSelection(), parsedSelection, deducer, renameMap, config ! .getOffsetStrategy()); ! } ! private MockupExtractMethodConfig initConfig() { ! MockupExtractMethodConfig config = null; ! XStream xstream = new XStream(); ! xstream.alias("config", MockupExtractMethodConfig.class); ! if (getConfig().length() > 0) { ! config = (MockupExtractMethodConfig) xstream.fromXML(getConfig()); ! } else { ! fail("Could not unserialize configuration"); ! } ! return config; ! } ! @Override ! public String getExpected() { ! return getResult(); ! } } Index: ExtractMethodTestSuite.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/tests/org/python/pydev/refactoring/tests/coderefactoring/extractmethod/ExtractMethodTestSuite.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** ExtractMethodTestSuite.java 20 Oct 2007 19:31:00 -0000 1.3 --- ExtractMethodTestSuite.java 27 Sep 2008 20:00:51 -0000 1.4 *************** *** 14,29 **** public class ExtractMethodTestSuite extends AbstractIOTestSuite { ! public static Test suite() { ! TESTDIR = "tests" + File.separator + "python" + File.separator + "coderefactoring" + File.separator + "extractmethod"; ! ExtractMethodTestSuite testSuite = new ExtractMethodTestSuite(); ! testSuite.createTests(); ! return testSuite; ! } ! @Override ! protected IInputOutputTestCase createTestCase(String testCaseName) { ! return new ExtractMethodTestCase(testCaseName); ! } } --- 14,29 ---- public class ExtractMethodTestSuite extends AbstractIOTestSuite { ! public static Test suite() { ! TESTDIR = "tests" + File.separator + "python" + File.separator + "coderefactoring" + File.separator + "extractmethod"; ! ExtractMethodTestSuite testSuite = new ExtractMethodTestSuite(); ! testSuite.createTests(); ! return testSuite; ! } ! @Override ! protected IInputOutputTestCase createTestCase(String testCaseName) { ! return new ExtractMethodTestCase(testCaseName); ! } } Index: MockupExtractMethodConfig.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/tests/org/python/pydev/refactoring/tests/coderefactoring/extractmethod/MockupExtractMethodConfig.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** MockupExtractMethodConfig.java 20 Oct 2007 19:31:00 -0000 1.3 --- MockupExtractMethodConfig.java 27 Sep 2008 20:00:51 -0000 1.4 *************** *** 12,47 **** public class MockupExtractMethodConfig { ! private int offset; ! private int selectionLength; ! private int offsetStrategy; ! private Map<String, String> renameMap; ! public MockupExtractMethodConfig() { ! this.offset = 0; ! this.selectionLength = 0; ! this.offsetStrategy = IOffsetStrategy.AFTERINIT; ! } ! public int getOffset() { ! return offset; ! } ! public int getOffsetStrategy() { ! return offsetStrategy; ! } ! public int getSelectionLength() { ! return selectionLength; ! } ! public Map<String, String> getRenameMap() { ! if (renameMap == null) { ! this.renameMap = new HashMap<String, String>(); ! } ! return renameMap; ! } } --- 12,47 ---- public class MockupExtractMethodConfig { ! private int offset; ! private int selectionLength; ! private int offsetStrategy; ! private Map<String, String> renameMap; ! public MockupExtractMethodConfig() { ! this.offset = 0; ! this.selectionLength = 0; ! this.offsetStrategy = IOffsetStrategy.AFTERINIT; ! } ! public int getOffset() { ! return offset; ! } ! public int getOffsetStrategy() { ! return offsetStrategy; ! } ! public int getSelectionLength() { ! return selectionLength; ! } ! public Map<String, String> getRenameMap() { ! if (renameMap == null) { ! this.renameMap = new HashMap<String, String>(); ! } ! return renameMap; ! } } Index: MockupExtractMethodRequestProcessor.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/tests/org/python/pydev/refactoring/tests/coderefactoring/extractmethod/MockupExtractMethodRequestProcessor.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** MockupExtractMethodRequestProcessor.java 20 Oct 2007 19:31:00 -0000 1.4 --- MockupExtractMethodRequestProcessor.java 27 Sep 2008 20:00:51 -0000 1.5 *************** *** 18,52 **** public class MockupExtractMethodRequestProcessor implements IRequestProcessor<ExtractMethodRequest> { ! private AbstractScopeNode<?> scopeAdapter; ! private int offsetStrategy; ! private ModuleAdapter parsedSelection; ! private ParameterReturnDeduce deducer; ! private Map<String, String> renameMap; ! private ITextSelection selection; ! public MockupExtractMethodRequestProcessor(AbstractScopeNode<?> scopeAdapter, ITextSelection selection, ModuleAdapter parsedSelection, ! ParameterReturnDeduce deducer, Map<String, String> renameMap, int offsetStrategy) { ! this.scopeAdapter = scopeAdapter; ! this.selection = selection; ! this.parsedSelection = parsedSelection; ! this.offsetStrategy = offsetStrategy; ! this.deducer = deducer; ! this.renameMap = renameMap; ! } ! public List<ExtractMethodRequest> getRefactoringRequests() { ! List<ExtractMethodRequest> requests = new ArrayList<ExtractMethodRequest>(); ! ExtractMethodRequest req = new ExtractMethodRequest("pepticMethod", this.selection, this.scopeAdapter, this.parsedSelection, ! deducer.getParameters(), deducer.getReturns(), this.renameMap, this.offsetStrategy, "\n"); ! requests.add(req); ! return requests; ! } } --- 18,52 ---- public class MockupExtractMethodRequestProcessor implements IRequestProcessor<ExtractMethodRequest> { ! private AbstractScopeNode<?> scopeAdapter; ! private int offsetStrategy; ! private ModuleAdapter parsedSelection; ! private ParameterReturnDeduce deducer; ! private Map<String, String> renameMap; ! private ITextSelection selection; ! public MockupExtractMethodRequestProcessor(AbstractScopeNode<?> scopeAdapter, ITextSelection selection, ModuleAdapter parsedSelection, ! ParameterReturnDeduce deducer, Map<String, String> renameMap, int offsetStrategy) { ! this.scopeAdapter = scopeAdapter; ! this.selection = selection; ! this.parsedSelection = parsedSelection; ! this.offsetStrategy = offsetStrategy; ! this.deducer = deducer; ! this.renameMap = renameMap; ! } ! public List<ExtractMethodRequest> getRefactoringRequests() { ! List<ExtractMethodRequest> requests = new ArrayList<ExtractMethodRequest>(); ! ExtractMethodRequest req = new ExtractMethodRequest("pepticMethod", this.selection, this.scopeAdapter, this.parsedSelection, ! deducer.getParameters(), deducer.getReturns(), this.renameMap, this.offsetStrategy, "\n"); ! requests.add(req); ! return requests; ! } } |
From: Fabio Z. <fa...@us...> - 2008-09-27 20:02:53
|
Update of /cvsroot/pydev/org.python.pydev.parser/src/org/python/pydev/parser In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv20472/src/org/python/pydev/parser Modified Files: ParserScheduler.java PyParserManager.java ParsingThread.java ParserPlugin.java PyParser.java CompilerAPI.java Added Files: ErrorDescription.java Log Message: Synching to latest changes: Pydev <ul> <li><strong>Editor</strong>: Cursor settings no longer overridden</li> <li><strong>Code-completion</strong>: If __all__ is defined with runtime elements (and not only in a single assign statement), it's ignored for code-completion purposes</li> <li><strong>Debugger</strong>: Pythonpath the same in debug and regular modes (sys.path[0] is the same directory as the file run)</li> <li><strong>Debugger</strong>: Persist choices done in the debugger when files from the debugger are not found</li> <li><strong>Interpreter config</strong>: "email" automatically added to the "forced builtins"</li> <li><strong>Parser</strong>: Correctly recognizing absolute import with 3 or more levels</li> <li><strong>Syntax check</strong>: Option to do only on active editor</li> </ul> Also: tabs changed for spaces Index: CompilerAPI.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.parser/src/org/python/pydev/parser/CompilerAPI.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** CompilerAPI.java 20 Mar 2006 19:37:35 -0000 1.2 --- CompilerAPI.java 27 Sep 2008 19:58:43 -0000 1.3 *************** *** 13,45 **** */ public class CompilerAPI implements IParserHost { ! public Object newInteger(int i) { ! return new java.lang.Integer(i); ! } ! public Object newLong(String s) { ! return new java.lang.Long(s); ! } ! public Object newLong(java.math.BigInteger i) { ! return i; ! } ! public Object newImaginary(double v) { ! return new java.lang.Double(v); ! } ! public static Object newFloat(float v) { ! return new java.lang.Float(v); ! } ! public Object newFloat(double v) { ! return new java.lang.Float(v); ! } ! /** ! * TODO how do I implement Unicode decoding in Java? ! */ ! public String decode_UnicodeEscape(String str, int start, int end, String errors, boolean unicode) { ! return str.substring(start, end); ! } } \ No newline at end of file --- 13,45 ---- */ public class CompilerAPI implements IParserHost { ! public Object newInteger(int i) { ! return new java.lang.Integer(i); ! } ! public Object newLong(String s) { ! return new java.lang.Long(s); ! } ! public Object newLong(java.math.BigInteger i) { ! return i; ! } ! public Object newImaginary(double v) { ! return new java.lang.Double(v); ! } ! public static Object newFloat(float v) { ! return new java.lang.Float(v); ! } ! public Object newFloat(double v) { ! return new java.lang.Float(v); ! } ! /** ! * TODO how do I implement Unicode decoding in Java? ! */ ! public String decode_UnicodeEscape(String str, int start, int end, String errors, boolean unicode) { ! return str.substring(start, end); ! } } \ No newline at end of file Index: ParserScheduler.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.parser/src/org/python/pydev/parser/ParserScheduler.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** ParserScheduler.java 3 Apr 2007 18:44:58 -0000 1.5 --- ParserScheduler.java 27 Sep 2008 19:58:43 -0000 1.6 *************** *** 12,16 **** * used to do parsings in a thread - is null when not doing parsings */ ! public ParsingThread parsingThread; /** --- 12,16 ---- * used to do parsings in a thread - is null when not doing parsings */ ! public volatile ParsingThread parsingThread; /** *************** *** 25,29 **** /** ! * indicates if a thread is currently waiting for an elapse cicle to end */ public static final int STATE_WAITING_FOR_ELAPSE = 2; --- 25,29 ---- /** ! * indicates if a thread is currently waiting for an elapse cycle to end */ public static final int STATE_WAITING_FOR_ELAPSE = 2; *************** *** 103,110 **** */ private boolean checkCreateAndStartParsingThread() { ! if(parsingThread == null){ ! parsingThread = new ParsingThread(this); ! parsingThread.setPriority(Thread.MIN_PRIORITY); //parsing is low priority ! parsingThread.start(); return true; } --- 103,112 ---- */ private boolean checkCreateAndStartParsingThread() { ! ParsingThread p = parsingThread; ! if(p == null){ ! p = new ParsingThread(this); ! p.setPriority(Thread.MIN_PRIORITY); //parsing is low priority ! p.start(); ! parsingThread = p; return true; } *************** *** 144,148 **** */ public void reparseDocument(Object ... argsToReparse) { ! parser.reparseDocument(argsToReparse); } --- 146,162 ---- */ public void reparseDocument(Object ... argsToReparse) { ! PyParser p = parser; ! if(p != null){ ! p.reparseDocument(argsToReparse); ! } ! } ! ! ! public void dispose() { ! ParsingThread p = this.parsingThread; ! if(p != null){ ! p.dispose(); ! } ! this.parser = null; } Index: PyParser.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.parser/src/org/python/pydev/parser/PyParser.java,v retrieving revision 1.51 retrieving revision 1.52 diff -C2 -d -r1.51 -r1.52 *** PyParser.java 31 Jul 2008 01:47:14 -0000 1.51 --- PyParser.java 27 Sep 2008 19:58:43 -0000 1.52 *************** *** 6,13 **** --- 6,16 ---- package org.python.pydev.parser; + import java.io.File; import java.io.StringReader; import java.util.ArrayList; + import java.util.HashMap; import java.util.HashSet; import java.util.List; + import java.util.Map; import java.util.Set; *************** *** 19,33 **** --- 22,41 ---- import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IAdaptable; + import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.DocumentEvent; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentListener; + import org.eclipse.jface.text.IRegion; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IFileEditorInput; + import org.eclipse.ui.texteditor.MarkerUtilities; import org.python.pydev.core.ExtensionHelper; + import org.python.pydev.core.ICallback; import org.python.pydev.core.IGrammarVersionProvider; import org.python.pydev.core.IPyEdit; import org.python.pydev.core.IPythonNature; import org.python.pydev.core.Tuple; + import org.python.pydev.core.Tuple3; import org.python.pydev.core.docutils.DocUtils; import org.python.pydev.core.docutils.PySelection; *************** *** 44,47 **** --- 52,56 ---- import org.python.pydev.parser.jython.ReaderCharStream; import org.python.pydev.parser.jython.SimpleNode; + import org.python.pydev.parser.jython.Token; import org.python.pydev.parser.jython.TokenMgrError; import org.python.pydev.parser.jython.ast.Module; *************** *** 115,118 **** --- 124,132 ---- private IGrammarVersionProvider grammarVersionProvider; + /** + * Identifies whether this parser is disposed. + */ + private volatile boolean disposed = false; + public static String getGrammarVersionStr(int grammarVersion){ *************** *** 146,172 **** public void documentChanged(DocumentEvent event) { String text = event.getText(); boolean parseNow = true; if (event == null || text == null ) { ! parseNow = false; } if(parseNow){ ! if(text.indexOf("\n") == -1 && text.indexOf("\r") == -1){ ! parseNow = false; ! ! } } ! if(!parseNow){ // carriage return in changed text means parse now, anything // else means parse later ! if(!useAnalysisOnlyOnDocSave){ ! scheduler.parseLater(); ! } } else { ! if(!useAnalysisOnlyOnDocSave){ ! scheduler.parseNow(); ! } } } --- 160,188 ---- public void documentChanged(DocumentEvent event) { + if(useAnalysisOnlyOnDocSave){ + //if we're doing analysis only on doc change, the parser will not give any changes + //to the scheduler, so, we won't have any parse events to respond to + return; + + } String text = event.getText(); boolean parseNow = true; if (event == null || text == null ) { ! parseNow = false; } if(parseNow){ ! if(text.indexOf("\n") == -1 && text.indexOf("\r") == -1){ ! parseNow = false; ! ! } } ! if(!parseNow){ // carriage return in changed text means parse now, anything // else means parse later ! scheduler.parseLater(); } else { ! scheduler.parseNow(); } } *************** *** 191,207 **** * @return a provider signaling the grammar to be used for the parser. */ ! private static IGrammarVersionProvider getGrammarProviderFromEdit(IPyEdit editorView) { ! try { ! return editorView.getPythonNature(); ! } catch (RuntimeException e) { ! //let's treat that correctly even if we do not have a default grammar (just log it) ! return new IGrammarVersionProvider(){ ! public int getGrammarVersion() { ! return IGrammarVersionProvider.LATEST_GRAMMAR_VERSION; ! } ! }; ! } ! } --- 207,223 ---- * @return a provider signaling the grammar to be used for the parser. */ ! private static IGrammarVersionProvider getGrammarProviderFromEdit(IPyEdit editorView) { ! try { ! return editorView.getPythonNature(); ! } catch (RuntimeException e) { ! //let's treat that correctly even if we do not have a default grammar (just log it) ! return new IGrammarVersionProvider(){ ! public int getGrammarVersion() { ! return IGrammarVersionProvider.LATEST_GRAMMAR_VERSION; ! } ! }; ! } ! } *************** *** 210,213 **** --- 226,232 ---- */ public void dispose() { + this.disposed = true; + this.scheduler.dispose(); + // remove the listeners if (document != null){ *************** *** 215,219 **** } synchronized(parserListeners){ ! parserListeners.clear(); } } --- 234,238 ---- } synchronized(parserListeners){ ! parserListeners.clear(); } } *************** *** 229,233 **** public void forceReparse(Object ... argsToReparse){ ! scheduler.parseNow(true, argsToReparse); } --- 248,255 ---- public void forceReparse(Object ... argsToReparse){ ! if(disposed){ ! return; ! } ! scheduler.parseNow(true, argsToReparse); } *************** *** 239,243 **** public void setDocument(IDocument document, IEditorInput input) { ! setDocument(document, true, input); } --- 261,265 ---- public void setDocument(IDocument document, IEditorInput input) { ! setDocument(document, true, input); } *************** *** 259,264 **** if(addToScheduler){ ! // Reparse document on the initial set (force it) ! scheduler.parseNow(true); } } --- 281,286 ---- if(addToScheduler){ ! // Reparse document on the initial set (force it) ! scheduler.parseNow(true); } } *************** *** 269,275 **** Assert.isNotNull(listener); synchronized(parserListeners){ ! if (!parserListeners.contains(listener)){ ! parserListeners.add(listener); ! } } } --- 291,297 ---- Assert.isNotNull(listener); synchronized(parserListeners){ ! if (!parserListeners.contains(listener)){ ! parserListeners.add(listener); ! } } } *************** *** 279,283 **** Assert.isNotNull(listener); synchronized(parserListeners){ ! parserListeners.remove(listener); } } --- 301,305 ---- Assert.isNotNull(listener); synchronized(parserListeners){ ! parserListeners.remove(listener); } } *************** *** 290,311 **** */ @SuppressWarnings("unchecked") ! protected void fireParserChanged(SimpleNode root, IAdaptable file, IDocument doc, Object ... argsToReparse) { this.root = root; synchronized(parserListeners){ ! for (IParserObserver l : new ArrayList<IParserObserver>(parserListeners)) { //work on a copy (because listeners may want to remove themselves and we cannot afford concurrent modifications here) ! if(l instanceof IParserObserver2){ ! ((IParserObserver2)l).parserChanged(root, file, doc, argsToReparse); ! }else{ ! l.parserChanged(root, file, doc); ! } ! } ! List<IParserObserver> participants = ExtensionHelper.getParticipants(ExtensionHelper.PYDEV_PARSER_OBSERVER); for (IParserObserver observer : participants) { ! if(observer instanceof IParserObserver2){ ! ((IParserObserver2)observer).parserChanged(root, file, doc, argsToReparse); ! }else{ ! observer.parserChanged(root, file, doc); ! } } } --- 312,333 ---- */ @SuppressWarnings("unchecked") ! protected void fireParserChanged(SimpleNode root, IAdaptable file, IDocument doc, Object ... argsToReparse) { this.root = root; synchronized(parserListeners){ ! for (IParserObserver l : new ArrayList<IParserObserver>(parserListeners)) { //work on a copy (because listeners may want to remove themselves and we cannot afford concurrent modifications here) ! if(l instanceof IParserObserver2){ ! ((IParserObserver2)l).parserChanged(root, file, doc, argsToReparse); ! }else{ ! l.parserChanged(root, file, doc); ! } ! } ! List<IParserObserver> participants = ExtensionHelper.getParticipants(ExtensionHelper.PYDEV_PARSER_OBSERVER); for (IParserObserver observer : participants) { ! if(observer instanceof IParserObserver2){ ! ((IParserObserver2)observer).parserChanged(root, file, doc, argsToReparse); ! }else{ ! observer.parserChanged(root, file, doc); ! } } } *************** *** 317,336 **** */ @SuppressWarnings("unchecked") ! protected void fireParserError(Throwable error, IAdaptable file, IDocument doc, Object ... argsToReparse) { synchronized(parserListeners){ ! for (IParserObserver l : new ArrayList<IParserObserver>(parserListeners)) {//work on a copy (because listeners may want to remove themselves and we cannot afford concurrent modifications here) ! if(l instanceof IParserObserver2){ ! ((IParserObserver2)l).parserError(error, file, doc, argsToReparse); ! }else{ ! l.parserError(error, file, doc); ! } } List<IParserObserver> participants = ExtensionHelper.getParticipants(ExtensionHelper.PYDEV_PARSER_OBSERVER); for (IParserObserver observer : participants) { ! if(observer instanceof IParserObserver2){ ! ((IParserObserver2)observer).parserError(error, file, doc, argsToReparse); ! }else{ ! observer.parserError(error, file, doc); ! } } } --- 339,358 ---- */ @SuppressWarnings("unchecked") ! protected void fireParserError(Throwable error, IAdaptable file, IDocument doc, Object ... argsToReparse) { synchronized(parserListeners){ ! for (IParserObserver l : new ArrayList<IParserObserver>(parserListeners)) {//work on a copy (because listeners may want to remove themselves and we cannot afford concurrent modifications here) ! if(l instanceof IParserObserver2){ ! ((IParserObserver2)l).parserError(error, file, doc, argsToReparse); ! }else{ ! l.parserError(error, file, doc); ! } } List<IParserObserver> participants = ExtensionHelper.getParticipants(ExtensionHelper.PYDEV_PARSER_OBSERVER); for (IParserObserver observer : participants) { ! if(observer instanceof IParserObserver2){ ! ((IParserObserver2)observer).parserError(error, file, doc, argsToReparse); ! }else{ ! observer.parserError(error, file, doc); ! } } } *************** *** 373,399 **** //delete the markers if (original != null){ ! try { ! IMarker[] markers = original.findMarkers(IMarker.PROBLEM, false, IResource.DEPTH_ZERO); ! if(markers.length > 0){ ! original.deleteMarkers(IMarker.PROBLEM, false, IResource.DEPTH_ZERO); ! } ! } catch (ResourceException e) { ! //ok, if it is a resource exception, it may have happened because the resource does not exist anymore ! //so, there is no need to log this failure if(original.exists()){ Log.log(e); } ! } catch (CoreException e) { ! Log.log(e); ! } ! }else if(adaptable == null){ ! //ok, we have nothing... maybe we are in tests... ! if (!PyParser.ACCEPT_NULL_INPUT_EDITOR){ ! throw new RuntimeException("Null input editor received in parser!"); ! } } //end delete the markers if(obj.o1 != null){ //ok, reparse succesful, lets erase the markers that are in the editor we just parsed --- 395,425 ---- //delete the markers if (original != null){ ! try { ! deleteErrorMarkers(original); ! } catch (ResourceException e) { ! //ok, if it is a resource exception, it may have happened because the resource does not exist anymore ! //so, there is no need to log this failure if(original.exists()){ Log.log(e); } ! } catch (CoreException e) { ! Log.log(e); ! } ! }else if(adaptable == null){ ! //ok, we have nothing... maybe we are in tests... ! if (!PyParser.ACCEPT_NULL_INPUT_EDITOR){ ! throw new RuntimeException("Null input editor received in parser!"); ! } } //end delete the markers + + if(disposed){ + //if it was disposed in this time, don't fire any notification nor return anything valid. + return new Tuple<SimpleNode, Throwable>(null, null); + } + + if(obj.o1 != null){ //ok, reparse succesful, lets erase the markers that are in the editor we just parsed *************** *** 411,414 **** --- 437,452 ---- return obj; } + + /** + * This function will remove the markers related to errors. + * @param resource the file that should have the markers removed + * @throws CoreException + */ + public static void deleteErrorMarkers(IResource resource) throws CoreException { + IMarker[] markers = resource.findMarkers(IMarker.PROBLEM, false, IResource.DEPTH_ZERO); + if(markers.length > 0){ + resource.deleteMarkers(IMarker.PROBLEM, false, IResource.DEPTH_ZERO); + } + } *************** *** 419,422 **** --- 457,461 ---- public static class ParserInfo{ public IDocument document; + public boolean stillTryToChangeCurrentLine=true; *************** *** 453,471 **** /** * @param grammarVersion: see IPythonNature.GRAMMAR_XXX constants */ ! public ParserInfo(IDocument document, boolean changedCurrentLine, int grammarVersion){ ! this.document = document; ! this.stillTryToChangeCurrentLine = changedCurrentLine; ! this.grammarVersion = grammarVersion; } ! public ParserInfo(IDocument document, boolean changedCurrentLine, IPythonNature nature){ ! this(document, changedCurrentLine, nature.getGrammarVersion()); } ! public ParserInfo(IDocument document, boolean changedCurrentLine, IPythonNature nature, int currentLine){ ! this(document, changedCurrentLine, nature); ! this.currentLine = currentLine; } } --- 492,530 ---- /** + * The module name of the contents parsed (may be null) + */ + public final String moduleName; + + /** + * The file that's been parsed (may be null) + */ + public final File file; + + /** * @param grammarVersion: see IPythonNature.GRAMMAR_XXX constants */ ! public ParserInfo(IDocument document, boolean stillTryToChangeCurrentLine, int grammarVersion){ ! this(document, stillTryToChangeCurrentLine, grammarVersion, -1, null, null); } ! public ParserInfo(IDocument document, boolean stillTryToChangeCurrentLine, IPythonNature nature){ ! this(document, stillTryToChangeCurrentLine, nature.getGrammarVersion()); } ! public ParserInfo(IDocument document, boolean stillTryToChangeCurrentLine, IPythonNature nature, int currentLine, String moduleName, File file){ ! this(document, stillTryToChangeCurrentLine, nature.getGrammarVersion(), currentLine, moduleName, file); ! } ! ! public ParserInfo(IDocument document, boolean stillTryToChangeCurrentLine, IPythonNature nature, int currentLine){ ! this(document, stillTryToChangeCurrentLine, nature.getGrammarVersion(), currentLine, null, null); ! } ! ! public ParserInfo(IDocument document, boolean stillTryToChangeCurrentLine, int grammarVersion, ! int currentLine, String name, File f) { ! this.document = document; ! this.stillTryToChangeCurrentLine = stillTryToChangeCurrentLine; ! this.grammarVersion = grammarVersion; ! this.moduleName = name; ! this.file = f; } } *************** *** 566,569 **** --- 625,635 ---- } + + /** + * This list of callbacks is mostly used for testing, so that we can check what's been parsed. + */ + public final static List<ICallback<Object, Tuple3<SimpleNode, Throwable, ParserInfo>>> successfulParseListeners = + new ArrayList<ICallback<Object, Tuple3<SimpleNode, Throwable, ParserInfo>>>(); + /** *************** *** 592,602 **** //we don't want to keep the string from being released, so, just get the char array from the string char[] cs = newDoc.get().toCharArray(); ! in = new FastCharStream(cs); }else{ ! //this should be deprecated in the future (it is still here so that we can evaluate ! //the changes done by the change of the reader). String initialDoc = newDoc.get(); ! StringReader inString = new StringReader(initialDoc); ! in = new ReaderCharStream(inString); throw new RuntimeException("This char stream reader was deprecated (was maintained only for testing purposes)."); } --- 658,668 ---- //we don't want to keep the string from being released, so, just get the char array from the string char[] cs = newDoc.get().toCharArray(); ! in = new FastCharStream(cs); }else{ ! //this should be deprecated in the future (it is still here so that we can evaluate ! //the changes done by the change of the reader). String initialDoc = newDoc.get(); ! StringReader inString = new StringReader(initialDoc); ! in = new ReaderCharStream(inString); throw new RuntimeException("This char stream reader was deprecated (was maintained only for testing purposes)."); } *************** *** 612,621 **** } try { ! ! if(ENABLE_TRACING){ ! //grammar has to be generated with debugging info for this to make a difference ! grammar.enable_tracing(); ! } SimpleNode newRoot = grammar.file_input(); // parses the file if(newRoot != null){ --- 678,688 ---- } + Tuple<SimpleNode, Throwable> returnVar = new Tuple<SimpleNode, Throwable>(null, null); try { ! ! if(ENABLE_TRACING){ ! //grammar has to be generated with debugging info for this to make a difference ! grammar.enable_tracing(); ! } SimpleNode newRoot = grammar.file_input(); // parses the file if(newRoot != null){ *************** *** 625,630 **** } } ! return new Tuple<SimpleNode, Throwable>(newRoot,null); ! } catch (Throwable e) { --- 692,706 ---- } } ! returnVar.o1 = newRoot; ! ! //only notify successful parses ! if(successfulParseListeners.size() > 0){ ! Tuple3<SimpleNode, Throwable, ParserInfo> param = new Tuple3<SimpleNode, Throwable, ParserInfo>( ! returnVar.o1, returnVar.o2, info); ! ! for(ICallback<Object, Tuple3<SimpleNode, Throwable, ParserInfo>> callback: successfulParseListeners){ ! callback.call(param); ! } ! } } catch (Throwable e) { *************** *** 655,659 **** } } ! return new Tuple<SimpleNode, Throwable>(newRoot, parseErr); }else if(e instanceof TokenMgrError){ --- 731,736 ---- } } ! ! returnVar = new Tuple<SimpleNode, Throwable>(newRoot, parseErr); }else if(e instanceof TokenMgrError){ *************** *** 667,671 **** } ! return new Tuple<SimpleNode, Throwable>(newRoot, tokenErr); }else if(e.getClass().getName().indexOf("LookaheadSuccess") != -1){ --- 744,748 ---- } ! returnVar = new Tuple<SimpleNode, Throwable>(newRoot, tokenErr); }else if(e.getClass().getName().indexOf("LookaheadSuccess") != -1){ *************** *** 674,682 **** Log.log(e); } - return new Tuple<SimpleNode, Throwable>(null, null); } } /** * @param tokenErr --- 751,761 ---- Log.log(e); } } + + return returnVar; } + /** * @param tokenErr *************** *** 715,720 **** line = tokenErr.currentToken.beginLine-2; ! }else{ ! return null; } } --- 794,799 ---- line = tokenErr.currentToken.beginLine-2; ! }else{ ! return null; } } *************** *** 775,779 **** info.document = doc; info.stillTryToChangeCurrentLine = false; ! return reparseDocument(info).o1; } return null; --- 854,858 ---- info.document = doc; info.stillTryToChangeCurrentLine = false; ! return reparseDocument(info).o1; } return null; *************** *** 788,791 **** --- 867,963 ---- } + /** + * Adds the error markers for some error that was found in the parsing process. + * + * @param error the error find while parsing the document + * @param resource the resource that should have the error added + * @param doc the document with the resource contents + * @return the error description (or null) + * + * @throws BadLocationException + * @throws CoreException + */ + public static ErrorDescription createParserErrorMarkers(Throwable error, IAdaptable resource, IDocument doc) + throws BadLocationException, CoreException { + ErrorDescription errDesc; + if(resource == null){ + return null; + } + IResource fileAdapter = (IResource) resource.getAdapter(IResource.class); + if(fileAdapter == null){ + return null; + } + + errDesc = createErrorDesc(error, doc); + + Map<String, Object> map = new HashMap<String, Object>(); + + map.put(IMarker.MESSAGE, errDesc.message); + map.put(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); + map.put(IMarker.LINE_NUMBER, errDesc.errorLine); + map.put(IMarker.CHAR_START, errDesc.errorStart); + map.put(IMarker.CHAR_END, errDesc.errorEnd); + map.put(IMarker.TRANSIENT, true); + MarkerUtilities.createMarker(fileAdapter, map, IMarker.PROBLEM); + return errDesc; + } + + + /** + * Creates the error description for a given error in the parse. + */ + private static ErrorDescription createErrorDesc(Throwable error, IDocument doc) throws BadLocationException { + int errorStart = -1; + int errorEnd = -1; + int errorLine = -1; + String message = null; + if (error instanceof ParseException) { + ParseException parseErr = (ParseException) error; + + // Figure out where the error is in the document, and create a + // marker for it + if(parseErr.currentToken == null){ + IRegion endLine = doc.getLineInformationOfOffset(doc.getLength()); + errorStart = endLine.getOffset(); + errorEnd = endLine.getOffset() + endLine.getLength(); + + }else{ + Token errorToken = parseErr.currentToken.next != null ? parseErr.currentToken.next : parseErr.currentToken; + IRegion startLine = doc.getLineInformation(errorToken.beginLine - 1); + IRegion endLine; + if (errorToken.endLine == 0){ + endLine = startLine; + }else{ + endLine = doc.getLineInformation(errorToken.endLine - 1); + } + errorStart = startLine.getOffset() + errorToken.beginColumn - 1; + errorEnd = endLine.getOffset() + errorToken.endColumn; + } + message = parseErr.getMessage(); + + } else if(error instanceof TokenMgrError){ + TokenMgrError tokenErr = (TokenMgrError) error; + IRegion startLine = doc.getLineInformation(tokenErr.errorLine - 1); + errorStart = startLine.getOffset(); + errorEnd = startLine.getOffset() + tokenErr.errorColumn; + message = tokenErr.getMessage(); + } else{ + Log.log("Error, expecting ParseException or TokenMgrError. Received: "+error); + return new ErrorDescription(null, 0, 0, 0); + } + errorLine = doc.getLineOfOffset(errorStart); + + // map.put(IMarker.LOCATION, "Whassup?"); this is the location field + // in task manager + if (message != null) { // prettyprint + message = message.replaceAll("\\r\\n", " "); + message = message.replaceAll("\\r", " "); + message = message.replaceAll("\\n", " "); + } + + + return new ErrorDescription(message, errorLine, errorStart, errorEnd); + } + Index: PyParserManager.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.parser/src/org/python/pydev/parser/PyParserManager.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** PyParserManager.java 3 Apr 2007 18:44:58 -0000 1.2 --- PyParserManager.java 27 Sep 2008 19:58:43 -0000 1.3 *************** *** 88,97 **** String property = event.getProperty(); if(property.equals(USE_PYDEV_ANALYSIS_ONLY_ON_DOC_SAVE) || property.equals(PYDEV_ELAPSE_BEFORE_ANALYSIS)){ ! //reset the caches ! millisBeforeAnalysis = PyParserManager.this.prefs.getInt(PYDEV_ELAPSE_BEFORE_ANALYSIS); ! useOnlyOnSave = PyParserManager.this.prefs.getBoolean(USE_PYDEV_ANALYSIS_ONLY_ON_DOC_SAVE); ! ! ! //and set the needed parsers boolean useAnalysisOnlyOnDocSave = useAnalysisOnlyOnDocSave(); --- 88,97 ---- String property = event.getProperty(); if(property.equals(USE_PYDEV_ANALYSIS_ONLY_ON_DOC_SAVE) || property.equals(PYDEV_ELAPSE_BEFORE_ANALYSIS)){ ! //reset the caches ! millisBeforeAnalysis = PyParserManager.this.prefs.getInt(PYDEV_ELAPSE_BEFORE_ANALYSIS); ! useOnlyOnSave = PyParserManager.this.prefs.getBoolean(USE_PYDEV_ANALYSIS_ONLY_ON_DOC_SAVE); ! ! ! //and set the needed parsers boolean useAnalysisOnlyOnDocSave = useAnalysisOnlyOnDocSave(); --- NEW FILE: ErrorDescription.java --- package org.python.pydev.parser; public class ErrorDescription { public String message; public int errorLine; public int errorStart; public int errorEnd; public ErrorDescription(String message, int errorLine, int errorStart, int errorEnd) { super(); this.message = message; this.errorLine = errorLine; this.errorStart = errorStart; this.errorEnd = errorEnd; } } Index: ParsingThread.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.parser/src/org/python/pydev/parser/ParsingThread.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** ParsingThread.java 3 Apr 2007 18:44:58 -0000 1.4 --- ParsingThread.java 27 Sep 2008 19:58:43 -0000 1.5 *************** *** 15,18 **** --- 15,23 ---- private ParserScheduler parser; private Object[] argsToReparse; + + /** + * Identifies whether this parsing thread is disposed. + */ + private boolean disposed; ParsingThread(ParserScheduler parser, Object ... argsToReparse) { *************** *** 24,35 **** public void run() { try { ! if(force == false){ ! makeOkAndSleepUntilIdleTimeElapses(); ! } ! ! while(!okToGo && force == false){ makeOkAndSleepUntilIdleTimeElapses(); } //ok, now we parse it... if we have not been requested to stop it try { --- 29,44 ---- public void run() { try { ! if(force == false){ ! makeOkAndSleepUntilIdleTimeElapses(); ! } ! ! while(!okToGo && force == false && !disposed){ makeOkAndSleepUntilIdleTimeElapses(); } + if(disposed){ + return; + } + //ok, now we parse it... if we have not been requested to stop it try { *************** *** 57,59 **** --- 66,72 ---- } + public void dispose() { + this.disposed = true; + } + } \ No newline at end of file Index: ParserPlugin.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.parser/src/org/python/pydev/parser/ParserPlugin.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** ParserPlugin.java 25 Jun 2005 20:23:36 -0000 1.1 --- ParserPlugin.java 27 Sep 2008 19:58:43 -0000 1.2 *************** *** 9,69 **** */ public class ParserPlugin extends AbstractUIPlugin { ! //The shared instance. ! private static ParserPlugin plugin; ! //Resource bundle. ! private ResourceBundle resourceBundle; ! ! /** ! * The constructor. ! */ ! public ParserPlugin() { ! super(); ! plugin = this; ! try { ! resourceBundle = ResourceBundle.getBundle("org.python.pydev.parser.ParserPluginResources"); ! } catch (MissingResourceException x) { ! resourceBundle = null; ! } ! } ! /** ! * This method is called upon plug-in activation ! */ ! public void start(BundleContext context) throws Exception { ! super.start(context); ! } ! /** ! * This method is called when the plug-in is stopped ! */ ! public void stop(BundleContext context) throws Exception { ! super.stop(context); ! } ! /** ! * Returns the shared instance. ! */ ! public static ParserPlugin getDefault() { ! return plugin; ! } ! /** ! * Returns the string from the plugin's resource bundle, ! * or 'key' if not found. ! */ ! public static String getResourceString(String key) { ! ResourceBundle bundle = ParserPlugin.getDefault().getResourceBundle(); ! try { ! return (bundle != null) ? bundle.getString(key) : key; ! } catch (MissingResourceException e) { ! return key; ! } ! } ! /** ! * Returns the plugin's resource bundle, ! */ ! public ResourceBundle getResourceBundle() { ! return resourceBundle; ! } } --- 9,69 ---- */ public class ParserPlugin extends AbstractUIPlugin { ! //The shared instance. ! private static ParserPlugin plugin; ! //Resource bundle. ! private ResourceBundle resourceBundle; ! ! /** ! * The constructor. ! */ ! public ParserPlugin() { ! super(); ! plugin = this; ! try { ! resourceBundle = ResourceBundle.getBundle("org.python.pydev.parser.ParserPluginResources"); ! } catch (MissingResourceException x) { ! resourceBundle = null; ! } ! } ! /** ! * This method is called upon plug-in activation ! */ ! public void start(BundleContext context) throws Exception { ! super.start(context); ! } ! /** ! * This method is called when the plug-in is stopped ! */ ! public void stop(BundleContext context) throws Exception { ! super.stop(context); ! } ! /** ! * Returns the shared instance. ! */ ! public static ParserPlugin getDefault() { ! return plugin; ! } ! /** ! * Returns the string from the plugin's resource bundle, ! * or 'key' if not found. ! */ ! public static String getResourceString(String key) { ! ResourceBundle bundle = ParserPlugin.getDefault().getResourceBundle(); ! try { ! return (bundle != null) ? bundle.getString(key) : key; ! } catch (MissingResourceException e) { ! return key; ! } ! } ! /** ! * Returns the plugin's resource bundle, ! */ ! public ResourceBundle getResourceBundle() { ! return resourceBundle; ! } } |
From: Fabio Z. <fa...@us...> - 2008-09-27 20:02:15
|
Update of /cvsroot/pydev/org.python.pydev.refactoring/tests/org/python/pydev/refactoring/tests/codegenerator/constructorfield In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv21605/tests/org/python/pydev/refactoring/tests/codegenerator/constructorfield Modified Files: MockupConstructorFieldConfig.java MockupConstructorFieldRequestProcessor.java ConstructorFieldTestSuite.java ConstructorFieldTestCase.java Log Message: Synching to latest changes: Pydev <ul> <li><strong>Editor</strong>: Cursor settings no longer overridden</li> <li><strong>Code-completion</strong>: If __all__ is defined with runtime elements (and not only in a single assign statement), it's ignored for code-completion purposes</li> <li><strong>Debugger</strong>: Pythonpath the same in debug and regular modes (sys.path[0] is the same directory as the file run)</li> <li><strong>Debugger</strong>: Persist choices done in the debugger when files from the debugger are not found</li> <li><strong>Interpreter config</strong>: "email" automatically added to the "forced builtins"</li> <li><strong>Parser</strong>: Correctly recognizing absolute import with 3 or more levels</li> <li><strong>Syntax check</strong>: Option to do only on active editor</li> </ul> Also: tabs changed for spaces Index: ConstructorFieldTestSuite.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/tests/org/python/pydev/refactoring/tests/codegenerator/constructorfield/ConstructorFieldTestSuite.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** ConstructorFieldTestSuite.java 20 Oct 2007 19:31:02 -0000 1.3 --- ConstructorFieldTestSuite.java 27 Sep 2008 20:00:47 -0000 1.4 *************** *** 14,29 **** public class ConstructorFieldTestSuite extends AbstractIOTestSuite { ! public static Test suite() { ! TESTDIR = "tests" + File.separator + "python" + File.separator + "codegenerator" + File.separator + "constructorfield"; ! ConstructorFieldTestSuite testSuite = new ConstructorFieldTestSuite(); ! testSuite.createTests(); ! return testSuite; ! } ! @Override ! protected IInputOutputTestCase createTestCase(String testCaseName) { ! return new ConstructorFieldTestCase(testCaseName); ! } } --- 14,29 ---- public class ConstructorFieldTestSuite extends AbstractIOTestSuite { ! public static Test suite() { ! TESTDIR = "tests" + File.separator + "python" + File.separator + "codegenerator" + File.separator + "constructorfield"; ! ConstructorFieldTestSuite testSuite = new ConstructorFieldTestSuite(); ! testSuite.createTests(); ! return testSuite; ! } ! @Override ! protected IInputOutputTestCase createTestCase(String testCaseName) { ! return new ConstructorFieldTestCase(testCaseName); ! } } Index: ConstructorFieldTestCase.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/tests/org/python/pydev/refactoring/tests/codegenerator/constructorfield/ConstructorFieldTestCase.java,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** ConstructorFieldTestCase.java 5 Feb 2008 13:07:01 -0000 1.6 --- ConstructorFieldTestCase.java 27 Sep 2008 20:00:47 -0000 1.7 *************** *** 20,83 **** public class ConstructorFieldTestCase extends AbstractIOTestCase { ! private CompletionEnvironmentSetupHelper setupHelper; public ConstructorFieldTestCase(String name) { ! super(name); ! } ! @Override ! public void runTest() throws Throwable { ! setupHelper = new CompletionEnvironmentSetupHelper(); ! setupHelper.setupEnv(); ! try{ ! MockupConstructorFieldConfig config = initConfig(); ! MockupConstructorFieldRequestProcessor requestProcessor = setupRequestProcessor(config); ! IDocument refactoringDoc = applyConstructorUsingFields(requestProcessor); ! this.setTestGenerated(refactoringDoc.get()); ! assertEquals(getExpected(), getGenerated()); ! }finally{ ! setupHelper.tearDownEnv(); ! } ! ! } ! ! private IDocument applyConstructorUsingFields(MockupConstructorFieldRequestProcessor requestProcessor) throws BadLocationException { ! ConstructorMethodEdit constructorEdit = new ConstructorMethodEdit(requestProcessor.getRefactoringRequests().get(0)); ! IDocument refactoringDoc = new Document(getSource()); ! constructorEdit.getEdit().apply(refactoringDoc); ! return refactoringDoc; ! } ! private MockupConstructorFieldRequestProcessor setupRequestProcessor(MockupConstructorFieldConfig config) throws Throwable { ! ModuleAdapter module = setupHelper.createModuleAdapter(this); ! ! List<IClassDefAdapter> classes = module.getClasses(); ! assertTrue(classes.size() > 0); ! MockupConstructorFieldRequestProcessor requestProcessor = new MockupConstructorFieldRequestProcessor(module, config); ! return requestProcessor; ! } ! private MockupConstructorFieldConfig initConfig() { ! MockupConstructorFieldConfig config = null; ! XStream xstream = new XStream(); ! xstream.alias("config", MockupConstructorFieldConfig.class); ! if (getConfig().length() > 0) { ! config = (MockupConstructorFieldConfig) xstream.fromXML(getConfig()); ! } else { ! fail("Could not unserialize configuration"); ! } ! return config; ! } ! @Override ! public String getExpected() { ! return getResult(); ! } } --- 20,83 ---- public class ConstructorFieldTestCase extends AbstractIOTestCase { ! private CompletionEnvironmentSetupHelper setupHelper; public ConstructorFieldTestCase(String name) { ! super(name); ! } ! @Override ! public void runTest() throws Throwable { ! setupHelper = new CompletionEnvironmentSetupHelper(); ! setupHelper.setupEnv(); ! try{ ! MockupConstructorFieldConfig config = initConfig(); ! MockupConstructorFieldRequestProcessor requestProcessor = setupRequestProcessor(config); ! IDocument refactoringDoc = applyConstructorUsingFields(requestProcessor); ! this.setTestGenerated(refactoringDoc.get()); ! assertEquals(getExpected(), getGenerated()); ! }finally{ ! setupHelper.tearDownEnv(); ! } ! ! } ! ! private IDocument applyConstructorUsingFields(MockupConstructorFieldRequestProcessor requestProcessor) throws BadLocationException { ! ConstructorMethodEdit constructorEdit = new ConstructorMethodEdit(requestProcessor.getRefactoringRequests().get(0)); ! IDocument refactoringDoc = new Document(getSource()); ! constructorEdit.getEdit().apply(refactoringDoc); ! return refactoringDoc; ! } ! private MockupConstructorFieldRequestProcessor setupRequestProcessor(MockupConstructorFieldConfig config) throws Throwable { ! ModuleAdapter module = setupHelper.createModuleAdapter(this); ! ! List<IClassDefAdapter> classes = module.getClasses(); ! assertTrue(classes.size() > 0); ! MockupConstructorFieldRequestProcessor requestProcessor = new MockupConstructorFieldRequestProcessor(module, config); ! return requestProcessor; ! } ! private MockupConstructorFieldConfig initConfig() { ! MockupConstructorFieldConfig config = null; ! XStream xstream = new XStream(); ! xstream.alias("config", MockupConstructorFieldConfig.class); ! if (getConfig().length() > 0) { ! config = (MockupConstructorFieldConfig) xstream.fromXML(getConfig()); ! } else { ! fail("Could not unserialize configuration"); ! } ! return config; ! } ! @Override ! public String getExpected() { ! return getResult(); ! } } Index: MockupConstructorFieldRequestProcessor.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/tests/org/python/pydev/refactoring/tests/codegenerator/constructorfield/MockupConstructorFieldRequestProcessor.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** MockupConstructorFieldRequestProcessor.java 20 Oct 2007 19:31:02 -0000 1.5 --- MockupConstructorFieldRequestProcessor.java 27 Sep 2008 20:00:47 -0000 1.6 *************** *** 16,53 **** public class MockupConstructorFieldRequestProcessor implements IRequestProcessor<ConstructorFieldRequest> { ! private ModuleAdapter module; ! private int classSelection; ! private int offsetStrategy; ! private List<Integer> attributeSelection; ! private MockupConstructorFieldRequestProcessor(ModuleAdapter module, int classSelection, List<Integer> attributeSelection, ! int offsetStrategy) { ! this.module = module; ! this.attributeSelection = attributeSelection; ! this.classSelection = classSelection; ! this.offsetStrategy = offsetStrategy; ! } ! public MockupConstructorFieldRequestProcessor(ModuleAdapter module, MockupConstructorFieldConfig config) { ! this(module, config.getClassSelection(), config.getAttributeSelection(), config.getOffsetStrategy()); ! } ! public List<ConstructorFieldRequest> getRefactoringRequests() { ! IClassDefAdapter clazz = module.getClasses().get(classSelection); ! List<INodeAdapter> attributes = new ArrayList<INodeAdapter>(); ! for (int index : attributeSelection) { ! attributes.add(clazz.getAttributes().get(index)); ! } ! ConstructorFieldRequest req = new ConstructorFieldRequest(clazz, attributes, this.offsetStrategy, "\n"); ! List<ConstructorFieldRequest> requests = new ArrayList<ConstructorFieldRequest>(); ! requests.add(req); ! return requests; ! } } --- 16,53 ---- public class MockupConstructorFieldRequestProcessor implements IRequestProcessor<ConstructorFieldRequest> { ! private ModuleAdapter module; ! private int classSelection; ! private int offsetStrategy; ! private List<Integer> attributeSelection; ! private MockupConstructorFieldRequestProcessor(ModuleAdapter module, int classSelection, List<Integer> attributeSelection, ! int offsetStrategy) { ! this.module = module; ! this.attributeSelection = attributeSelection; ! this.classSelection = classSelection; ! this.offsetStrategy = offsetStrategy; ! } ! public MockupConstructorFieldRequestProcessor(ModuleAdapter module, MockupConstructorFieldConfig config) { ! this(module, config.getClassSelection(), config.getAttributeSelection(), config.getOffsetStrategy()); ! } ! public List<ConstructorFieldRequest> getRefactoringRequests() { ! IClassDefAdapter clazz = module.getClasses().get(classSelection); ! List<INodeAdapter> attributes = new ArrayList<INodeAdapter>(); ! for (int index : attributeSelection) { ! attributes.add(clazz.getAttributes().get(index)); ! } ! ConstructorFieldRequest req = new ConstructorFieldRequest(clazz, attributes, this.offsetStrategy, "\n"); ! List<ConstructorFieldRequest> requests = new ArrayList<ConstructorFieldRequest>(); ! requests.add(req); ! return requests; ! } } Index: MockupConstructorFieldConfig.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/tests/org/python/pydev/refactoring/tests/codegenerator/constructorfield/MockupConstructorFieldConfig.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** MockupConstructorFieldConfig.java 20 Oct 2007 19:31:02 -0000 1.2 --- MockupConstructorFieldConfig.java 27 Sep 2008 20:00:47 -0000 1.3 *************** *** 11,37 **** public class MockupConstructorFieldConfig { ! private int classSelection; ! private ArrayList<Integer> attributeSelection; ! private int offsetStrategy; ! public MockupConstructorFieldConfig() { ! this.classSelection = 0; ! this.offsetStrategy = IOffsetStrategy.AFTERINIT; ! this.attributeSelection = new ArrayList<Integer>(); ! attributeSelection.add(0); ! } ! public ArrayList<Integer> getAttributeSelection() { ! return attributeSelection; ! } ! public int getClassSelection() { ! return classSelection; ! } ! public int getOffsetStrategy() { ! return offsetStrategy; ! } } --- 11,37 ---- public class MockupConstructorFieldConfig { ! private int classSelection; ! private ArrayList<Integer> attributeSelection; ! private int offsetStrategy; ! public MockupConstructorFieldConfig() { ! this.classSelection = 0; ! this.offsetStrategy = IOffsetStrategy.AFTERINIT; ! this.attributeSelection = new ArrayList<Integer>(); ! attributeSelection.add(0); ! } ! public ArrayList<Integer> getAttributeSelection() { ! return attributeSelection; ! } ! public int getClassSelection() { ! return classSelection; ! } ! public int getOffsetStrategy() { ! return offsetStrategy; ! } } |
From: Fabio Z. <fa...@us...> - 2008-09-27 20:02:14
|
Update of /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/ui/pages/extractlocal In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv21605/src/org/python/pydev/refactoring/ui/pages/extractlocal Modified Files: ExtractLocalPage.java ExtractLocalComposite.java Log Message: Synching to latest changes: Pydev <ul> <li><strong>Editor</strong>: Cursor settings no longer overridden</li> <li><strong>Code-completion</strong>: If __all__ is defined with runtime elements (and not only in a single assign statement), it's ignored for code-completion purposes</li> <li><strong>Debugger</strong>: Pythonpath the same in debug and regular modes (sys.path[0] is the same directory as the file run)</li> <li><strong>Debugger</strong>: Persist choices done in the debugger when files from the debugger are not found</li> <li><strong>Interpreter config</strong>: "email" automatically added to the "forced builtins"</li> <li><strong>Parser</strong>: Correctly recognizing absolute import with 3 or more levels</li> <li><strong>Syntax check</strong>: Option to do only on active editor</li> </ul> Also: tabs changed for spaces Index: ExtractLocalComposite.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/ui/pages/extractlocal/ExtractLocalComposite.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** ExtractLocalComposite.java 20 Oct 2007 19:31:00 -0000 1.1 --- ExtractLocalComposite.java 27 Sep 2008 20:00:48 -0000 1.2 *************** *** 22,75 **** public class ExtractLocalComposite extends Composite { ! private LabeledEdit variableNameEdit; ! private AbstractScopeNode<?> scopeAdapter; ! private IValidationPage page; ! public ExtractLocalComposite(IValidationPage page, Composite parent, AbstractScopeNode<?> scope) { ! super(parent, SWT.NONE); ! this.page = page; ! this.scopeAdapter = scope; ! createComposite(); ! } ! public void createComposite() { ! setLayout(new GridLayout()); ! createVariableName(this); ! pack(); ! } ! private void createVariableName(Composite control) { ! Composite variableNameComposite = new Composite(control, SWT.NONE); ! FillLayout compositeLayout = new FillLayout(SWT.HORIZONTAL); ! GridData gridData = new GridData(); ! gridData.horizontalAlignment = GridData.FILL; ! variableNameComposite.setLayoutData(gridData); ! variableNameComposite.setLayout(compositeLayout); ! variableNameEdit = new LabeledEdit(variableNameComposite, Messages.extractLocalVariableTitle); ! } ! public void registerListeners(final IValidationPage page) { ! variableNameEdit.getEdit().addListener(SWT.Modify, page); ! } ! public String getVariableName() { ! return variableNameEdit.getEdit().getText(); ! } ! public boolean validate() { ! NameValidator nameValidator = new NameValidator(scopeAdapter); ! try { ! nameValidator.validateVariableName(getVariableName()); ! nameValidator.validateUniqueVariable(getVariableName()); ! } catch (Throwable e) { ! page.setErrorMessage(e.getMessage()); ! } ! return page.getErrorMessage() == null; ! } } --- 22,75 ---- public class ExtractLocalComposite extends Composite { ! private LabeledEdit variableNameEdit; ! private AbstractScopeNode<?> scopeAdapter; ! private IValidationPage page; ! public ExtractLocalComposite(IValidationPage page, Composite parent, AbstractScopeNode<?> scope) { ! super(parent, SWT.NONE); ! this.page = page; ! this.scopeAdapter = scope; ! createComposite(); ! } ! public void createComposite() { ! setLayout(new GridLayout()); ! createVariableName(this); ! pack(); ! } ! private void createVariableName(Composite control) { ! Composite variableNameComposite = new Composite(control, SWT.NONE); ! FillLayout compositeLayout = new FillLayout(SWT.HORIZONTAL); ! GridData gridData = new GridData(); ! gridData.horizontalAlignment = GridData.FILL; ! variableNameComposite.setLayoutData(gridData); ! variableNameComposite.setLayout(compositeLayout); ! variableNameEdit = new LabeledEdit(variableNameComposite, Messages.extractLocalVariableTitle); ! } ! public void registerListeners(final IValidationPage page) { ! variableNameEdit.getEdit().addListener(SWT.Modify, page); ! } ! public String getVariableName() { ! return variableNameEdit.getEdit().getText(); ! } ! public boolean validate() { ! NameValidator nameValidator = new NameValidator(scopeAdapter); ! try { ! nameValidator.validateVariableName(getVariableName()); ! nameValidator.validateUniqueVariable(getVariableName()); ! } catch (Throwable e) { ! page.setErrorMessage(e.getMessage()); ! } ! return page.getErrorMessage() == null; ! } } Index: ExtractLocalPage.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/ui/pages/extractlocal/ExtractLocalPage.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** ExtractLocalPage.java 20 Oct 2007 19:31:00 -0000 1.1 --- ExtractLocalPage.java 27 Sep 2008 20:00:48 -0000 1.2 *************** *** 17,72 **** public class ExtractLocalPage extends PyDevInputWizardPage { ! public ExtractLocalRequestProcessor requestProcessor; ! private ExtractLocalComposite extractComposite; ! private Composite parent; ! public ExtractLocalPage(String name, ExtractLocalRequestProcessor requestProcessor) { ! super(name); ! this.setTitle(name); ! this.requestProcessor = requestProcessor; ! } ! public void createControl(Composite parent) { ! this.parent = parent; ! setupComposite(); ! } ! public void setupComposite() { ! if (extractComposite != null) { ! extractComposite.dispose(); ! extractComposite = null; ! } ! ! extractComposite = new ExtractLocalComposite(this, parent, requestProcessor.getScopeAdapter()); ! extractComposite.registerListeners(this); ! setControl(this.extractComposite); ! voodooResizeToPage(); ! setPageComplete(false); ! } ! @Override ! public boolean canFlipToNextPage() { ! return isPageComplete(); ! } ! public void validate() { ! setErrorMessage(null); ! extractComposite.validate(); ! setPageComplete(getErrorMessage() == null); ! if (isPageComplete()) { ! applySettings(); ! } ! } ! private void applySettings() { ! this.requestProcessor.setVariableName(extractComposite.getVariableName()); ! } ! public void handleEvent(Event event) { ! validate(); ! } } --- 17,72 ---- public class ExtractLocalPage extends PyDevInputWizardPage { ! public ExtractLocalRequestProcessor requestProcessor; ! private ExtractLocalComposite extractComposite; ! private Composite parent; ! public ExtractLocalPage(String name, ExtractLocalRequestProcessor requestProcessor) { ! super(name); ! this.setTitle(name); ! this.requestProcessor = requestProcessor; ! } ! public void createControl(Composite parent) { ! this.parent = parent; ! setupComposite(); ! } ! public void setupComposite() { ! if (extractComposite != null) { ! extractComposite.dispose(); ! extractComposite = null; ! } ! ! extractComposite = new ExtractLocalComposite(this, parent, requestProcessor.getScopeAdapter()); ! extractComposite.registerListeners(this); ! setControl(this.extractComposite); ! voodooResizeToPage(); ! setPageComplete(false); ! } ! @Override ! public boolean canFlipToNextPage() { ! return isPageComplete(); ! } ! public void validate() { ! setErrorMessage(null); ! extractComposite.validate(); ! setPageComplete(getErrorMessage() == null); ! if (isPageComplete()) { ! applySettings(); ! } ! } ! private void applySettings() { ! this.requestProcessor.setVariableName(extractComposite.getVariableName()); ! } ! public void handleEvent(Event event) { ! validate(); ! } } |
From: Fabio Z. <fa...@us...> - 2008-09-27 20:02:13
|
Update of /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/ui/model In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv21605/src/org/python/pydev/refactoring/ui/model Modified Files: OffsetStrategyModel.java OffsetStrategyProvider.java Log Message: Synching to latest changes: Pydev <ul> <li><strong>Editor</strong>: Cursor settings no longer overridden</li> <li><strong>Code-completion</strong>: If __all__ is defined with runtime elements (and not only in a single assign statement), it's ignored for code-completion purposes</li> <li><strong>Debugger</strong>: Pythonpath the same in debug and regular modes (sys.path[0] is the same directory as the file run)</li> <li><strong>Debugger</strong>: Persist choices done in the debugger when files from the debugger are not found</li> <li><strong>Interpreter config</strong>: "email" automatically added to the "forced builtins"</li> <li><strong>Parser</strong>: Correctly recognizing absolute import with 3 or more levels</li> <li><strong>Syntax check</strong>: Option to do only on active editor</li> </ul> Also: tabs changed for spaces Index: OffsetStrategyModel.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/ui/model/OffsetStrategyModel.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** OffsetStrategyModel.java 20 Oct 2007 19:31:04 -0000 1.2 --- OffsetStrategyModel.java 27 Sep 2008 20:00:44 -0000 1.3 *************** *** 12,32 **** public class OffsetStrategyModel extends StructuredSelection { ! private int key; ! private String description; ! public OffsetStrategyModel(int key, String description) { ! this.key = key; ! this.description = description; ! } ! @Override ! public String toString() { ! return description; ! } ! public int getStrategy() { ! return key; ! } } --- 12,32 ---- public class OffsetStrategyModel extends StructuredSelection { ! private int key; ! private String description; ! public OffsetStrategyModel(int key, String description) { ! this.key = key; ! this.description = description; ! } ! @Override ! public String toString() { ! return description; ! } ! public int getStrategy() { ! return key; ! } } Index: OffsetStrategyProvider.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/ui/model/OffsetStrategyProvider.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** OffsetStrategyProvider.java 20 Oct 2007 19:31:04 -0000 1.3 --- OffsetStrategyProvider.java 27 Sep 2008 20:00:44 -0000 1.4 *************** *** 20,91 **** public class OffsetStrategyProvider implements IStructuredContentProvider { ! private List<OffsetStrategyModel> strategies; ! private String initLabel; ! private String beginLabel; ! private String endLabel; ! public OffsetStrategyProvider(int strategyOption) { ! strategies = new ArrayList<OffsetStrategyModel>(); ! initLabel(); ! initStrategies(strategyOption); ! } ! public OffsetStrategyProvider(AbstractScopeNode<?> scopeAdapter, int strategyOption) { ! strategies = new ArrayList<OffsetStrategyModel>(); ! strategyOption = updateLabel(scopeAdapter, strategyOption); ! initStrategies(strategyOption); ! } ! private void initLabel() { ! initLabel = Messages.offsetStrategyAfterInit; ! beginLabel = Messages.offsetStrategyBegin; ! endLabel = Messages.offsetStrategyEnd; ! } ! private int updateLabel(AbstractScopeNode<?> scopeAdapter, int strategyOption) { ! if (scopeAdapter != null) { ! if (scopeAdapter.getNodeBodyIndent() == 0) { ! beginLabel = Messages.offsetStrategyBeginModule; ! endLabel = Messages.offsetStrategyEndModule; ! if ((strategyOption & IOffsetStrategy.AFTERINIT) == IOffsetStrategy.AFTERINIT) { ! strategyOption &= ~IOffsetStrategy.AFTERINIT; ! } ! } else ! initLabel(); ! } ! return strategyOption; ! } ! private void initStrategies(int strategyOption) { ! setStrategy(strategyOption, IOffsetStrategy.AFTERINIT, initLabel); ! setStrategy(strategyOption, IOffsetStrategy.BEGIN, beginLabel); ! setStrategy(strategyOption, IOffsetStrategy.END, endLabel); ! } ! private void setStrategy(int strategyOption, int id, String label) { ! if ((strategyOption & id) == id) { ! strategies.add(new OffsetStrategyModel(id, label)); ! } ! } ! public OffsetStrategyModel get(int i) { ! return this.strategies.get(i); ! } ! public Object[] getElements(Object inputElement) { ! return strategies.toArray(); ! } ! public void dispose() { ! this.strategies = null; ! } ! public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { ! } } --- 20,91 ---- public class OffsetStrategyProvider implements IStructuredContentProvider { ! private List<OffsetStrategyModel> strategies; ! private String initLabel; ! private String beginLabel; ! private String endLabel; ! public OffsetStrategyProvider(int strategyOption) { ! strategies = new ArrayList<OffsetStrategyModel>(); ! initLabel(); ! initStrategies(strategyOption); ! } ! public OffsetStrategyProvider(AbstractScopeNode<?> scopeAdapter, int strategyOption) { ! strategies = new ArrayList<OffsetStrategyModel>(); ! strategyOption = updateLabel(scopeAdapter, strategyOption); ! initStrategies(strategyOption); ! } ! private void initLabel() { ! initLabel = Messages.offsetStrategyAfterInit; ! beginLabel = Messages.offsetStrategyBegin; ! endLabel = Messages.offsetStrategyEnd; ! } ! private int updateLabel(AbstractScopeNode<?> scopeAdapter, int strategyOption) { ! if (scopeAdapter != null) { ! if (scopeAdapter.getNodeBodyIndent() == 0) { ! beginLabel = Messages.offsetStrategyBeginModule; ! endLabel = Messages.offsetStrategyEndModule; ! if ((strategyOption & IOffsetStrategy.AFTERINIT) == IOffsetStrategy.AFTERINIT) { ! strategyOption &= ~IOffsetStrategy.AFTERINIT; ! } ! } else ! initLabel(); ! } ! return strategyOption; ! } ! private void initStrategies(int strategyOption) { ! setStrategy(strategyOption, IOffsetStrategy.AFTERINIT, initLabel); ! setStrategy(strategyOption, IOffsetStrategy.BEGIN, beginLabel); ! setStrategy(strategyOption, IOffsetStrategy.END, endLabel); ! } ! private void setStrategy(int strategyOption, int id, String label) { ! if ((strategyOption & id) == id) { ! strategies.add(new OffsetStrategyModel(id, label)); ! } ! } ! public OffsetStrategyModel get(int i) { ! return this.strategies.get(i); ! } ! public Object[] getElements(Object inputElement) { ! return strategies.toArray(); ! } ! public void dispose() { ! this.strategies = null; ! } ! public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { ! } } |
From: Fabio Z. <fa...@us...> - 2008-09-27 20:02:12
|
Update of /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/coderefactoring/extractlocal/edit In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv21605/src/org/python/pydev/refactoring/coderefactoring/extractlocal/edit Modified Files: ReplaceWithVariableEdit.java CreateLocalVariableEdit.java Log Message: Synching to latest changes: Pydev <ul> <li><strong>Editor</strong>: Cursor settings no longer overridden</li> <li><strong>Code-completion</strong>: If __all__ is defined with runtime elements (and not only in a single assign statement), it's ignored for code-completion purposes</li> <li><strong>Debugger</strong>: Pythonpath the same in debug and regular modes (sys.path[0] is the same directory as the file run)</li> <li><strong>Debugger</strong>: Persist choices done in the debugger when files from the debugger are not found</li> <li><strong>Interpreter config</strong>: "email" automatically added to the "forced builtins"</li> <li><strong>Parser</strong>: Correctly recognizing absolute import with 3 or more levels</li> <li><strong>Syntax check</strong>: Option to do only on active editor</li> </ul> Also: tabs changed for spaces Index: CreateLocalVariableEdit.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/coderefactoring/extractlocal/edit/CreateLocalVariableEdit.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** CreateLocalVariableEdit.java 20 Oct 2007 19:31:03 -0000 1.1 --- CreateLocalVariableEdit.java 27 Sep 2008 20:00:44 -0000 1.2 *************** *** 21,54 **** public class CreateLocalVariableEdit extends AbstractInsertEdit { ! private RefactoringInfo info; ! ! private String variableName; ! private exprType expression; ! public CreateLocalVariableEdit(ExtractLocalRequest req) { ! super(req); ! this.info = req.getRefactoringInfo(); ! this.variableName = req.getVariableName(); ! this.expression = req.getExpression(); ! } ! @Override ! protected SimpleNode getEditNode() { ! exprType variable = new Name(variableName, expr_contextType.Store); ! exprType[] target = {variable}; ! ! return new Assign(target, expression); ! } ! ! @Override ! public int getOffset() { ! PySelection selection = new PySelection(info.getDocument(), info.getExtendedSelection()); ! return selection.getStartLineOffset(); ! } ! @Override ! public int getOffsetStrategy() { ! return 0; ! } } --- 21,54 ---- public class CreateLocalVariableEdit extends AbstractInsertEdit { ! private RefactoringInfo info; ! ! private String variableName; ! private exprType expression; ! public CreateLocalVariableEdit(ExtractLocalRequest req) { ! super(req); ! this.info = req.getRefactoringInfo(); ! this.variableName = req.getVariableName(); ! this.expression = req.getExpression(); ! } ! @Override ! protected SimpleNode getEditNode() { ! exprType variable = new Name(variableName, expr_contextType.Store); ! exprType[] target = {variable}; ! ! return new Assign(target, expression); ! } ! ! @Override ! public int getOffset() { ! PySelection selection = new PySelection(info.getDocument(), info.getExtendedSelection()); ! return selection.getStartLineOffset(); ! } ! @Override ! public int getOffsetStrategy() { ! return 0; ! } } Index: ReplaceWithVariableEdit.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/coderefactoring/extractlocal/edit/ReplaceWithVariableEdit.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** ReplaceWithVariableEdit.java 20 Oct 2007 19:31:03 -0000 1.1 --- ReplaceWithVariableEdit.java 27 Sep 2008 20:00:44 -0000 1.2 *************** *** 18,58 **** public class ReplaceWithVariableEdit extends AbstractReplaceEdit { ! private String variableName; ! private int offset; ! private int replaceLength; ! public ReplaceWithVariableEdit(ExtractLocalRequest req) { ! super(req); ! this.variableName = req.getVariableName(); ! ! ITextSelection selection = req.getRefactoringInfo().getExtendedSelection(); ! this.offset = selection.getOffset(); ! this.replaceLength = selection.getLength(); ! this.offsetAdapter = req.getOffsetNode(); ! } ! @Override ! protected SimpleNode getEditNode() { ! Name name = new Name(variableName, expr_contextType.Load); ! return name; ! } ! @Override ! public int getOffsetStrategy() { ! return 0; ! } ! @Override ! public int getOffset() { ! return offset; ! } ! @Override ! protected int getReplaceLength() { ! return replaceLength; ! } } --- 18,58 ---- public class ReplaceWithVariableEdit extends AbstractReplaceEdit { ! private String variableName; ! private int offset; ! private int replaceLength; ! public ReplaceWithVariableEdit(ExtractLocalRequest req) { ! super(req); ! this.variableName = req.getVariableName(); ! ! ITextSelection selection = req.getRefactoringInfo().getExtendedSelection(); ! this.offset = selection.getOffset(); ! this.replaceLength = selection.getLength(); ! this.offsetAdapter = req.getOffsetNode(); ! } ! @Override ! protected SimpleNode getEditNode() { ! Name name = new Name(variableName, expr_contextType.Load); ! return name; ! } ! @Override ! public int getOffsetStrategy() { ! return 0; ! } ! @Override ! public int getOffset() { ! return offset; ! } ! @Override ! protected int getReplaceLength() { ! return replaceLength; ! } } |
From: Fabio Z. <fa...@us...> - 2008-09-27 20:02:11
|
Update of /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/codegenerator/constructorfield/request In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv21605/src/org/python/pydev/refactoring/codegenerator/constructorfield/request Modified Files: ConstructorFieldRequest.java Log Message: Synching to latest changes: Pydev <ul> <li><strong>Editor</strong>: Cursor settings no longer overridden</li> <li><strong>Code-completion</strong>: If __all__ is defined with runtime elements (and not only in a single assign statement), it's ignored for code-completion purposes</li> <li><strong>Debugger</strong>: Pythonpath the same in debug and regular modes (sys.path[0] is the same directory as the file run)</li> <li><strong>Debugger</strong>: Persist choices done in the debugger when files from the debugger are not found</li> <li><strong>Interpreter config</strong>: "email" automatically added to the "forced builtins"</li> <li><strong>Parser</strong>: Correctly recognizing absolute import with 3 or more levels</li> <li><strong>Syntax check</strong>: Option to do only on active editor</li> </ul> Also: tabs changed for spaces Index: ConstructorFieldRequest.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/codegenerator/constructorfield/request/ConstructorFieldRequest.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** ConstructorFieldRequest.java 20 Oct 2007 19:31:02 -0000 1.5 --- ConstructorFieldRequest.java 27 Sep 2008 20:00:48 -0000 1.6 *************** *** 19,52 **** public class ConstructorFieldRequest implements IRefactoringRequest { ! private IClassDefAdapter classAdapter; ! private List<INodeAdapter> attributeAdapters; ! private int offsetStrategy; private String newLineDelim; ! public ConstructorFieldRequest(IClassDefAdapter classAdapter, List<INodeAdapter> attributeAdapters, int offsetStrategy, String newLineDelim) { ! this.classAdapter = classAdapter; ! this.attributeAdapters = attributeAdapters; ! this.offsetStrategy = offsetStrategy; this.newLineDelim = newLineDelim; ! } ! public IASTNodeAdapter<? extends SimpleNode> getOffsetNode() { ! return classAdapter; ! } ! public List<INodeAdapter> getAttributeAdapters() { ! return attributeAdapters; ! } ! public IClassDefAdapter getClassAdapter() { ! return classAdapter; ! } ! public int getOffsetStrategy() { ! return offsetStrategy; ! } public String getNewLineDelim() { --- 19,52 ---- public class ConstructorFieldRequest implements IRefactoringRequest { ! private IClassDefAdapter classAdapter; ! private List<INodeAdapter> attributeAdapters; ! private int offsetStrategy; private String newLineDelim; ! public ConstructorFieldRequest(IClassDefAdapter classAdapter, List<INodeAdapter> attributeAdapters, int offsetStrategy, String newLineDelim) { ! this.classAdapter = classAdapter; ! this.attributeAdapters = attributeAdapters; ! this.offsetStrategy = offsetStrategy; this.newLineDelim = newLineDelim; ! } ! public IASTNodeAdapter<? extends SimpleNode> getOffsetNode() { ! return classAdapter; ! } ! public List<INodeAdapter> getAttributeAdapters() { ! return attributeAdapters; ! } ! public IClassDefAdapter getClassAdapter() { ! return classAdapter; ! } ! public int getOffsetStrategy() { ! return offsetStrategy; ! } public String getNewLineDelim() { |
From: Fabio Z. <fa...@us...> - 2008-09-27 20:02:10
|
Update of /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/core/request In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv21605/src/org/python/pydev/refactoring/core/request Modified Files: IRefactoringRequest.java IRequestProcessor.java Log Message: Synching to latest changes: Pydev <ul> <li><strong>Editor</strong>: Cursor settings no longer overridden</li> <li><strong>Code-completion</strong>: If __all__ is defined with runtime elements (and not only in a single assign statement), it's ignored for code-completion purposes</li> <li><strong>Debugger</strong>: Pythonpath the same in debug and regular modes (sys.path[0] is the same directory as the file run)</li> <li><strong>Debugger</strong>: Persist choices done in the debugger when files from the debugger are not found</li> <li><strong>Interpreter config</strong>: "email" automatically added to the "forced builtins"</li> <li><strong>Parser</strong>: Correctly recognizing absolute import with 3 or more levels</li> <li><strong>Syntax check</strong>: Option to do only on active editor</li> </ul> Also: tabs changed for spaces Index: IRequestProcessor.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/core/request/IRequestProcessor.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** IRequestProcessor.java 20 Oct 2007 19:31:02 -0000 1.2 --- IRequestProcessor.java 27 Sep 2008 20:00:48 -0000 1.3 *************** *** 11,14 **** public interface IRequestProcessor<T> { ! public List<T> getRefactoringRequests(); } --- 11,14 ---- public interface IRequestProcessor<T> { ! public List<T> getRefactoringRequests(); } Index: IRefactoringRequest.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/core/request/IRefactoringRequest.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** IRefactoringRequest.java 20 Oct 2007 19:31:02 -0000 1.3 --- IRefactoringRequest.java 27 Sep 2008 20:00:48 -0000 1.4 *************** *** 14,18 **** public interface IRefactoringRequest { ! public abstract IASTNodeAdapter<? extends SimpleNode> getOffsetNode(); public abstract String getNewLineDelim(); --- 14,18 ---- public interface IRefactoringRequest { ! public abstract IASTNodeAdapter<? extends SimpleNode> getOffsetNode(); public abstract String getNewLineDelim(); |
From: Fabio Z. <fa...@us...> - 2008-09-27 20:02:05
|
Update of /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/unittest In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv20604/src/org/python/pydev/debug/unittest Modified Files: _TestResult.java _TestReportView.java _PyUnitTestRunner.java _TestReportContentProvider.java _ITestRunListener.java _TestReportLabelProvider.java Log Message: Synching to latest changes: Pydev <ul> <li><strong>Editor</strong>: Cursor settings no longer overridden</li> <li><strong>Code-completion</strong>: If __all__ is defined with runtime elements (and not only in a single assign statement), it's ignored for code-completion purposes</li> <li><strong>Debugger</strong>: Pythonpath the same in debug and regular modes (sys.path[0] is the same directory as the file run)</li> <li><strong>Debugger</strong>: Persist choices done in the debugger when files from the debugger are not found</li> <li><strong>Interpreter config</strong>: "email" automatically added to the "forced builtins"</li> <li><strong>Parser</strong>: Correctly recognizing absolute import with 3 or more levels</li> <li><strong>Syntax check</strong>: Option to do only on active editor</li> </ul> Also: tabs changed for spaces Index: _TestReportContentProvider.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/unittest/_TestReportContentProvider.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** _TestReportContentProvider.java 30 Mar 2008 21:45:18 -0000 1.1 --- _TestReportContentProvider.java 27 Sep 2008 19:59:09 -0000 1.2 *************** *** 23,101 **** // */ //public class TestReportContentProvider implements IStructuredContentProvider, ! // ITestRunListener { // ! // private TableViewer viewer; ! // private TestResult currentResult; ! // private String testFile; ! // ! // public TestReportContentProvider() { ! // PydevDebugPlugin.getDefault().addTestListener(this); ! // } // ! // public void dispose() { ! // PydevDebugPlugin.getDefault().removeTestListener(this); ! // } ! // ! // public Object[] getElements(Object inputElement) { ! // return ((List)inputElement).toArray(); ! // } // ! // private List getTestResults() { ! // return (List)viewer.getInput(); ! // } ! // ! // public void inputChanged(Viewer tableViewer, Object oldInput, ! // Object newInput) { ! // viewer = (TableViewer)tableViewer; ! // ! // } ! // public void testsStarted(int testCount, String testFile) { ! // this.testFile = testFile; ! // ((List)viewer.getInput()).clear(); ! // currentResult = null; ! // Control ctrl = viewer.getControl(); ! // if (ctrl == null || ctrl.isDisposed()) ! // return; ! // ctrl.getDisplay().syncExec(new Runnable() { ! // public void run() { ! // if (!viewer.getControl().isDisposed()) ! // viewer.refresh(); ! // } ! // }); ! // } // // ! // public void testsFinished(String summary) { ! // addLastResult(); ! // } // // ! // public void testStarted(String klass, String method) { ! // addLastResult(); ! // currentResult = new TestResult(testFile, klass, method, 0, System.currentTimeMillis()); ! // } // ! // public void testOK(String klass, String method) { ! // } // ! // public void testFailed(String klass, String method, String failureType, String trace) { ! // currentResult.testFailed(failureType); ! // } // ! // private void addLastResult() { ! // if (currentResult != null) { ! // currentResult.testFinished(); ! // getTestResults().add(currentResult); ! // Control ctrl = viewer.getControl(); ! // if (ctrl == null || ctrl.isDisposed()) ! // return; ! // ctrl.getDisplay().syncExec(new Runnable() { ! // public void run() { ! // int lineIndex = currentResult.isFailure() ? 0 : -1; ! // if (!viewer.getControl().isDisposed()) ! // viewer.insert(currentResult, lineIndex); ! // } ! // }); ! // } ! // } //} --- 23,101 ---- // */ //public class TestReportContentProvider implements IStructuredContentProvider, ! // ITestRunListener { // ! // private TableViewer viewer; ! // private TestResult currentResult; ! // private String testFile; ! // ! // public TestReportContentProvider() { ! // PydevDebugPlugin.getDefault().addTestListener(this); ! // } // ! // public void dispose() { ! // PydevDebugPlugin.getDefault().removeTestListener(this); ! // } ! // ! // public Object[] getElements(Object inputElement) { ! // return ((List)inputElement).toArray(); ! // } // ! // private List getTestResults() { ! // return (List)viewer.getInput(); ! // } ! // ! // public void inputChanged(Viewer tableViewer, Object oldInput, ! // Object newInput) { ! // viewer = (TableViewer)tableViewer; ! // ! // } ! // public void testsStarted(int testCount, String testFile) { ! // this.testFile = testFile; ! // ((List)viewer.getInput()).clear(); ! // currentResult = null; ! // Control ctrl = viewer.getControl(); ! // if (ctrl == null || ctrl.isDisposed()) ! // return; ! // ctrl.getDisplay().syncExec(new Runnable() { ! // public void run() { ! // if (!viewer.getControl().isDisposed()) ! // viewer.refresh(); ! // } ! // }); ! // } // // ! // public void testsFinished(String summary) { ! // addLastResult(); ! // } // // ! // public void testStarted(String klass, String method) { ! // addLastResult(); ! // currentResult = new TestResult(testFile, klass, method, 0, System.currentTimeMillis()); ! // } // ! // public void testOK(String klass, String method) { ! // } // ! // public void testFailed(String klass, String method, String failureType, String trace) { ! // currentResult.testFailed(failureType); ! // } // ! // private void addLastResult() { ! // if (currentResult != null) { ! // currentResult.testFinished(); ! // getTestResults().add(currentResult); ! // Control ctrl = viewer.getControl(); ! // if (ctrl == null || ctrl.isDisposed()) ! // return; ! // ctrl.getDisplay().syncExec(new Runnable() { ! // public void run() { ! // int lineIndex = currentResult.isFailure() ? 0 : -1; ! // if (!viewer.getControl().isDisposed()) ! // viewer.insert(currentResult, lineIndex); ! // } ! // }); ! // } ! // } //} Index: _PyUnitTestRunner.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/unittest/_PyUnitTestRunner.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** _PyUnitTestRunner.java 30 Mar 2008 21:45:18 -0000 1.1 --- _PyUnitTestRunner.java 27 Sep 2008 19:59:08 -0000 1.2 *************** *** 19,49 **** //public class PyUnitTestRunner { // ! // public static class ConsoleListener implements ITestRunListener { // ! // public void testsStarted(int testCount, String testFile) { ! // System.out.println("STARTING TEST RUN: " + ! // String.valueOf(testCount) + " tests"); ! // } // ! // public void testsFinished(String summary) { ! // System.out.println(summary); // ! // //MessageDialog.openInformation(null, "Test Results", messageLong); ! // } // ! // public void testStarted(String klass, String method) { ! // } // ! // public void testFailed(String klass, String method, String failureType, String trace) { ! // System.out.print(klass + " " + method + "... "); ! // System.out.println(failureType); ! // System.out.println(trace); ! // } // ! // public void testOK(String klass, String method) { ! // System.out.print(klass + " " + method + "... "); ! // System.out.println("OK"); ! // } ! // } // // public static final int BUFFER_SIZE = 1024 * 4; --- 19,49 ---- //public class PyUnitTestRunner { // ! // public static class ConsoleListener implements ITestRunListener { // ! // public void testsStarted(int testCount, String testFile) { ! // System.out.println("STARTING TEST RUN: " + ! // String.valueOf(testCount) + " tests"); ! // } // ! // public void testsFinished(String summary) { ! // System.out.println(summary); // ! // //MessageDialog.openInformation(null, "Test Results", messageLong); ! // } // ! // public void testStarted(String klass, String method) { ! // } // ! // public void testFailed(String klass, String method, String failureType, String trace) { ! // System.out.print(klass + " " + method + "... "); ! // System.out.println(failureType); ! // System.out.println(trace); ! // } // ! // public void testOK(String klass, String method) { ! // System.out.print(klass + " " + method + "... "); ! // System.out.println("OK"); ! // } ! // } // // public static final int BUFFER_SIZE = 1024 * 4; *************** *** 62,87 **** // // public PyUnitTestRunner(IProgressMonitor monitor, int port, String testFile) { ! // this.monitor = (SubProgressMonitor) monitor; ! // portToReadFrom = port; ! // this.testFile = testFile; // } // // public void readTestResults() throws IOException{ ! // ITestRunListener listener = new ConsoleListener(); ! // PydevDebugPlugin.getDefault().addTestListener(listener); // // //sleepALittle(1000); // try { ! // serverSocket = new ServerSocket(portToReadFrom); //read from this portToRead ! // try { ! // socketToRead = serverSocket.accept(); ! // try { ! // readMessage(); ! // } finally { ! // socketToRead.close(); ! // } ! // } finally { ! // serverSocket.close(); ! // } // } catch (SocketException e) { // e.printStackTrace(); --- 62,87 ---- // // public PyUnitTestRunner(IProgressMonitor monitor, int port, String testFile) { ! // this.monitor = (SubProgressMonitor) monitor; ! // portToReadFrom = port; ! // this.testFile = testFile; // } // // public void readTestResults() throws IOException{ ! // ITestRunListener listener = new ConsoleListener(); ! // PydevDebugPlugin.getDefault().addTestListener(listener); // // //sleepALittle(1000); // try { ! // serverSocket = new ServerSocket(portToReadFrom); //read from this portToRead ! // try { ! // socketToRead = serverSocket.accept(); ! // try { ! // readMessage(); ! // } finally { ! // socketToRead.close(); ! // } ! // } finally { ! // serverSocket.close(); ! // } // } catch (SocketException e) { // e.printStackTrace(); *************** *** 90,94 **** // throw e; // } finally { ! // PydevDebugPlugin.getDefault().removeTestListener(listener); // } // } --- 90,94 ---- // throw e; // } finally { ! // PydevDebugPlugin.getDefault().removeTestListener(listener); // } // } *************** *** 100,187 **** // */ // private void readMessage() throws IOException, SocketException { ! // reader = new BufferedReader( ! // new InputStreamReader(socketToRead.getInputStream())); // try { ! // String line = null; ! // while ((line = reader.readLine()) != null) { ! // System.out.println(line); ! // parseMessage(line); ! // } ! // } catch (SocketException e) { ! // //e.printStackTrace(); ! // } catch (IOException e) { ! // e.printStackTrace(); ! // } ! // finally { ! // reader.close(); // } // } // // private void parseMessage(String line) { ! // int start; ! // PydevDebugPlugin plugin = PydevDebugPlugin.getDefault(); ! // if (line.startsWith("starting tests ")) { ! // start = "starting tests ".length(); ! // int count = Integer.parseInt(line.substring(start)); ! // monitor.subTask("Starting test run"); ! // plugin.fireTestsStarted(count, testFile); ! // } ! // if (line.startsWith("ending tests ")) { ! // start = "ending tests ".length(); ! // String timeTaken = line.substring(start, line.indexOf(";")); ! // String result = line.substring(line.indexOf(";") + 1, ! // line.length()); ! // String summary = timeTaken +'\n'+ result; ! // monitor.subTask("Ending test run"); ! // plugin.fireTestsFinished(summary); ! // } ! // if (line.startsWith("starting test ")) { ! // start = "starting test ".length(); ! // String method = line.substring(start, line.indexOf("(")); ! // method = method.trim(); ! // String klass = line.substring(line.indexOf("(") + 1, ! // line.indexOf(")")); ! // klass = klass.trim(); ! // monitor.subTask(line); ! // plugin.fireTestStarted(klass, method); ! // } ! // if (line.startsWith("test OK ")) { ! // start = "test OK ".length(); ! // String method = line.substring(start, line.indexOf("(")); ! // String klass = line.substring(line.indexOf("(") + 1, ! // line.indexOf(")")); ! // monitor.subTask(line); ! // plugin.fireTestOK(klass, method); ! // } ! // if (line.startsWith("failing test ")) { ! // start = "failing test ".length(); ! // String method = line.substring(start, line.indexOf("(")); ! // String klass = line.substring(line.indexOf("(") + 1, ! // line.indexOf(")")); ! // StringWriter buffer = new StringWriter(); ! // PrintWriter writer = new PrintWriter(buffer); ! // String frame = null; ! // String failureType = ""; ! // try { ! // while ((frame = reader.readLine()) != null && ! // (!frame.equals("END TRACE"))) { ! // //writer.println(frame); ! // ! // if (frame.startsWith("TYPE:")) { ! // int cnt = "TYPE:".length(); ! // failureType = frame.substring(cnt, frame.indexOf(".")); ! // } ! // else { ! // writer.println(frame); ! // } ! // } ! // ! // } catch (IOException e) { ! // e.printStackTrace(); ! // } ! // String trace = buffer.getBuffer().toString(); ! // monitor.subTask(line); ! // plugin.fireTestFailed(klass, method, failureType, trace); ! // } // } // /** --- 100,187 ---- // */ // private void readMessage() throws IOException, SocketException { ! // reader = new BufferedReader( ! // new InputStreamReader(socketToRead.getInputStream())); // try { ! // String line = null; ! // while ((line = reader.readLine()) != null) { ! // System.out.println(line); ! // parseMessage(line); ! // } ! // } catch (SocketException e) { ! // //e.printStackTrace(); ! // } catch (IOException e) { ! // e.printStackTrace(); ! // } ! // finally { ! // reader.close(); // } // } // // private void parseMessage(String line) { ! // int start; ! // PydevDebugPlugin plugin = PydevDebugPlugin.getDefault(); ! // if (line.startsWith("starting tests ")) { ! // start = "starting tests ".length(); ! // int count = Integer.parseInt(line.substring(start)); ! // monitor.subTask("Starting test run"); ! // plugin.fireTestsStarted(count, testFile); ! // } ! // if (line.startsWith("ending tests ")) { ! // start = "ending tests ".length(); ! // String timeTaken = line.substring(start, line.indexOf(";")); ! // String result = line.substring(line.indexOf(";") + 1, ! // line.length()); ! // String summary = timeTaken +'\n'+ result; ! // monitor.subTask("Ending test run"); ! // plugin.fireTestsFinished(summary); ! // } ! // if (line.startsWith("starting test ")) { ! // start = "starting test ".length(); ! // String method = line.substring(start, line.indexOf("(")); ! // method = method.trim(); ! // String klass = line.substring(line.indexOf("(") + 1, ! // line.indexOf(")")); ! // klass = klass.trim(); ! // monitor.subTask(line); ! // plugin.fireTestStarted(klass, method); ! // } ! // if (line.startsWith("test OK ")) { ! // start = "test OK ".length(); ! // String method = line.substring(start, line.indexOf("(")); ! // String klass = line.substring(line.indexOf("(") + 1, ! // line.indexOf(")")); ! // monitor.subTask(line); ! // plugin.fireTestOK(klass, method); ! // } ! // if (line.startsWith("failing test ")) { ! // start = "failing test ".length(); ! // String method = line.substring(start, line.indexOf("(")); ! // String klass = line.substring(line.indexOf("(") + 1, ! // line.indexOf(")")); ! // StringWriter buffer = new StringWriter(); ! // PrintWriter writer = new PrintWriter(buffer); ! // String frame = null; ! // String failureType = ""; ! // try { ! // while ((frame = reader.readLine()) != null && ! // (!frame.equals("END TRACE"))) { ! // //writer.println(frame); ! // ! // if (frame.startsWith("TYPE:")) { ! // int cnt = "TYPE:".length(); ! // failureType = frame.substring(cnt, frame.indexOf(".")); ! // } ! // else { ! // writer.println(frame); ! // } ! // } ! // ! // } catch (IOException e) { ! // e.printStackTrace(); ! // } ! // String trace = buffer.getBuffer().toString(); ! // monitor.subTask(line); ! // plugin.fireTestFailed(klass, method, failureType, trace); ! // } // } // /** Index: _ITestRunListener.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/unittest/_ITestRunListener.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** _ITestRunListener.java 30 Mar 2008 21:45:18 -0000 1.1 --- _ITestRunListener.java 27 Sep 2008 19:59:09 -0000 1.2 *************** *** 15,22 **** // */ //public interface ITestRunListener { ! // void testsStarted(int testCount, String testFile); ! // void testsFinished(String summary); ! // void testStarted(String klass, String method); ! // void testOK(String klass, String method); ! // void testFailed(String klass, String method, String failureType, String trace); //} --- 15,22 ---- // */ //public interface ITestRunListener { ! // void testsStarted(int testCount, String testFile); ! // void testsFinished(String summary); ! // void testStarted(String klass, String method); ! // void testOK(String klass, String method); ! // void testFailed(String klass, String method, String failureType, String trace); //} Index: _TestResult.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/unittest/_TestResult.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** _TestResult.java 30 Mar 2008 21:45:18 -0000 1.1 --- _TestResult.java 27 Sep 2008 19:59:08 -0000 1.2 *************** *** 15,54 **** // */ //public class TestResult { ! // public final static int OK = 0; ! // public final static int FAIL = 1; ! // public final static int ERROR = 2; ! // public String testFile; ! // public String klass; ! // public String method; ! // public int status; ! // public long startTime; ! // public long endTime; ! // ! // public TestResult(String testFile, String klass, String method, int status, long startTime) { ! // this.testFile = testFile; ! // this.klass = klass; ! // this.method = method; ! // this.status = status; ! // this.startTime = startTime; ! // } ! // ! // public void testFailed(String failureType) { ! // //System.out.println("Failure type:" + failureType + ":"); ! // if (failureType.equals("FAIL")) ! // status = FAIL; ! // else if (failureType.equals("ERROR")) ! // status = ERROR; ! // } // ! // public boolean isFailure() { ! // return status != OK; ! // } // ! // public void testFinished() { ! // endTime = System.currentTimeMillis(); ! // } ! // ! // public long testDuration() { ! // return endTime - startTime; ! // } //} --- 15,54 ---- // */ //public class TestResult { ! // public final static int OK = 0; ! // public final static int FAIL = 1; ! // public final static int ERROR = 2; ! // public String testFile; ! // public String klass; ! // public String method; ! // public int status; ! // public long startTime; ! // public long endTime; ! // ! // public TestResult(String testFile, String klass, String method, int status, long startTime) { ! // this.testFile = testFile; ! // this.klass = klass; ! // this.method = method; ! // this.status = status; ! // this.startTime = startTime; ! // } ! // ! // public void testFailed(String failureType) { ! // //System.out.println("Failure type:" + failureType + ":"); ! // if (failureType.equals("FAIL")) ! // status = FAIL; ! // else if (failureType.equals("ERROR")) ! // status = ERROR; ! // } // ! // public boolean isFailure() { ! // return status != OK; ! // } // ! // public void testFinished() { ! // endTime = System.currentTimeMillis(); ! // } ! // ! // public long testDuration() { ! // return endTime - startTime; ! // } //} Index: _TestReportView.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/unittest/_TestReportView.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** _TestReportView.java 30 Mar 2008 21:45:18 -0000 1.1 --- _TestReportView.java 27 Sep 2008 19:59:08 -0000 1.2 *************** *** 53,138 **** //public class TestReportView extends ViewPart { // ! // private TableViewer viewer; ! // private DoubleClickTestAction doubleClickAction = new DoubleClickTestAction(); ! // private static Control colorLabel; ! // private static Control failuresCountLabel; ! // private static Control errorsCountLabel; ! // private ITestRunListener listener; ! // private boolean fIsDisposed= false; ! // ! // public class LabelListener implements ITestRunListener { // ! // private boolean success; ! // private int testsExecuted; ! // private int errCount; ! // private int failCount; ! // ! // private void setLabelTextColor(){ ! // Color green = colorLabel.getDisplay().getSystemColor(SWT.COLOR_GREEN); ! // Color red = colorLabel.getDisplay().getSystemColor(SWT.COLOR_RED); ! // Color gray = colorLabel.getDisplay().getSystemColor(SWT.COLOR_GRAY); ! // Color color; ! // if (testsExecuted == 0) ! // color = gray; ! // else ! // color = success? green: red; ! // colorLabel.setBackground(color); ! // colorLabel.redraw(); // ! // String strErrCount = Integer.toString(errCount); ! // String errText = "Errors: " + strErrCount; ! // ((Label)errorsCountLabel).setText(errText); ! // errorsCountLabel.redraw(); ! // ! // String strFailCount = Integer.toString(failCount); ! // String failText = "Failures: " + strFailCount; ! // ((Label)failuresCountLabel).setText(failText); ! // failuresCountLabel.redraw(); ! // } // ! // public void testsStarted(int testCount, String testFile) { ! // success = true; ! // testsExecuted = 0; ! // errCount = 0; ! // failCount = 0; ! // updateLabels(); ! // //postShowTestReportView(); ! // } // ! // public void testsFinished(String summary) { ! // //if (colorLabel == null || colorLabel.isDisposed()) ! // // return; ! // updateLabels(); ! // } // ! // private void updateLabels() { ! // colorLabel.getDisplay().syncExec(new Runnable() { ! // public void run() { ! // if (colorLabel.isDisposed()) ! // return; ! // setLabelTextColor(); ! // } ! // }); ! // } // ! // public void testStarted(String klass, String method) { ! // testsExecuted++; ! // } // ! // public void testOK(String klass, String method) { // ! // } // ! // public void testFailed(String klass, String method, String failureType, String trace) { ! // success = false; ! // if (failureType.equals("ERROR")) ! // errCount++; ! // else if (failureType.equals("FAIL")) ! // failCount++; ! // if (colorLabel == null || colorLabel.isDisposed()) ! // return; ! // updateLabels(); ! // } ! // } // // private final class DoubleClickTestAction extends ProgressAction { --- 53,138 ---- //public class TestReportView extends ViewPart { // ! // private TableViewer viewer; ! // private DoubleClickTestAction doubleClickAction = new DoubleClickTestAction(); ! // private static Control colorLabel; ! // private static Control failuresCountLabel; ! // private static Control errorsCountLabel; ! // private ITestRunListener listener; ! // private boolean fIsDisposed= false; ! // ! // public class LabelListener implements ITestRunListener { // ! // private boolean success; ! // private int testsExecuted; ! // private int errCount; ! // private int failCount; ! // ! // private void setLabelTextColor(){ ! // Color green = colorLabel.getDisplay().getSystemColor(SWT.COLOR_GREEN); ! // Color red = colorLabel.getDisplay().getSystemColor(SWT.COLOR_RED); ! // Color gray = colorLabel.getDisplay().getSystemColor(SWT.COLOR_GRAY); ! // Color color; ! // if (testsExecuted == 0) ! // color = gray; ! // else ! // color = success? green: red; ! // colorLabel.setBackground(color); ! // colorLabel.redraw(); // ! // String strErrCount = Integer.toString(errCount); ! // String errText = "Errors: " + strErrCount; ! // ((Label)errorsCountLabel).setText(errText); ! // errorsCountLabel.redraw(); ! // ! // String strFailCount = Integer.toString(failCount); ! // String failText = "Failures: " + strFailCount; ! // ((Label)failuresCountLabel).setText(failText); ! // failuresCountLabel.redraw(); ! // } // ! // public void testsStarted(int testCount, String testFile) { ! // success = true; ! // testsExecuted = 0; ! // errCount = 0; ! // failCount = 0; ! // updateLabels(); ! // //postShowTestReportView(); ! // } // ! // public void testsFinished(String summary) { ! // //if (colorLabel == null || colorLabel.isDisposed()) ! // // return; ! // updateLabels(); ! // } // ! // private void updateLabels() { ! // colorLabel.getDisplay().syncExec(new Runnable() { ! // public void run() { ! // if (colorLabel.isDisposed()) ! // return; ! // setLabelTextColor(); ! // } ! // }); ! // } // ! // public void testStarted(String klass, String method) { ! // testsExecuted++; ! // } // ! // public void testOK(String klass, String method) { // ! // } // ! // public void testFailed(String klass, String method, String failureType, String trace) { ! // success = false; ! // if (failureType.equals("ERROR")) ! // errCount++; ! // else if (failureType.equals("FAIL")) ! // failCount++; ! // if (colorLabel == null || colorLabel.isDisposed()) ! // return; ! // updateLabels(); ! // } ! // } // // private final class DoubleClickTestAction extends ProgressAction { *************** *** 157,163 **** // String method = ((TestResult)obj).method; // if (realFile.exists() && !realFile.isDirectory()) { ! // Location loc = navigateToClassMethod(realFile, klass, method); // //ItemPointer p = new ItemPointer(realFile, new Location(-1, -1), null); ! // ItemPointer p = new ItemPointer(realFile, loc, null); // PyOpenAction act = new PyOpenAction(); // act.run(p); --- 157,163 ---- // String method = ((TestResult)obj).method; // if (realFile.exists() && !realFile.isDirectory()) { ! // Location loc = navigateToClassMethod(realFile, klass, method); // //ItemPointer p = new ItemPointer(realFile, new Location(-1, -1), null); ! // ItemPointer p = new ItemPointer(realFile, loc, null); // PyOpenAction act = new PyOpenAction(); // act.run(p); *************** *** 180,185 **** // // private Location navigateToClassMethod(File file, String klass, String method) { ! // Location loc = new Location(); ! // int lineCnt = 0; // //StringBuffer contents = new StringBuffer(); // BufferedReader input = null; --- 180,185 ---- // // private Location navigateToClassMethod(File file, String klass, String method) { ! // Location loc = new Location(); ! // int lineCnt = 0; // //StringBuffer contents = new StringBuffer(); // BufferedReader input = null; *************** *** 187,192 **** // boolean foundMethod = false; // // klass is of the form module.class; we only need class ! // String new_klass = klass.substring(klass.indexOf(".") + 1); ! // klass = new_klass; // try { // //use buffering --- 187,192 ---- // boolean foundMethod = false; // // klass is of the form module.class; we only need class ! // String new_klass = klass.substring(klass.indexOf(".") + 1); ! // klass = new_klass; // try { // //use buffering *************** *** 195,206 **** // String line = null; // while (( line = input.readLine()) != null){ ! // lineCnt++; ! // if (line.indexOf(klass) > 0) { ! // foundClass = true; ! // } ! // if (foundClass && (line.indexOf(method) > 0)){ ! // foundMethod = true; ! // break; ! // } // //contents.append(line); // //contents.append(System.getProperty("line.separator")); --- 195,206 ---- // String line = null; // while (( line = input.readLine()) != null){ ! // lineCnt++; ! // if (line.indexOf(klass) > 0) { ! // foundClass = true; ! // } ! // if (foundClass && (line.indexOf(method) > 0)){ ! // foundMethod = true; ! // break; ! // } // //contents.append(line); // //contents.append(System.getProperty("line.separator")); *************** *** 225,240 **** // } // if (foundClass && foundMethod) ! // loc.line = lineCnt; // return loc; // } // } ! // ! // public TableViewer getViewer(){ ! // return viewer; ! // } ! // /* (non-Javadoc) ! // * @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite) ! // */ ! // public void createPartControl(Composite parent) { // GridLayout layout = new GridLayout(); // layout.numColumns = 1; --- 225,240 ---- // } // if (foundClass && foundMethod) ! // loc.line = lineCnt; // return loc; // } // } ! // ! // public TableViewer getViewer(){ ! // return viewer; ! // } ! // /* (non-Javadoc) ! // * @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite) ! // */ ! // public void createPartControl(Composite parent) { // GridLayout layout = new GridLayout(); // layout.numColumns = 1; *************** *** 249,258 **** // labelData.grabExcessHorizontalSpace = true; // labelData.horizontalAlignment = GridData.FILL; ! // Color gray = colorLabel.getDisplay().getSystemColor(SWT.COLOR_GRAY); ! // colorLabel.setBackground(gray); // colorLabel.setLayoutData(labelData); // // Image imageFailures = PydevDebugPlugin.getDefault().imageCache.get("icons/testfailures_ovr.gif"); ! // Image imageErrors = PydevDebugPlugin.getDefault().imageCache.get("icons/testerrors_ovr.gif"); // // Composite labelComposite = new Composite(parent, SWT.MULTI); --- 249,258 ---- // labelData.grabExcessHorizontalSpace = true; // labelData.horizontalAlignment = GridData.FILL; ! // Color gray = colorLabel.getDisplay().getSystemColor(SWT.COLOR_GRAY); ! // colorLabel.setBackground(gray); // colorLabel.setLayoutData(labelData); // // Image imageFailures = PydevDebugPlugin.getDefault().imageCache.get("icons/testfailures_ovr.gif"); ! // Image imageErrors = PydevDebugPlugin.getDefault().imageCache.get("icons/testerrors_ovr.gif"); // // Composite labelComposite = new Composite(parent, SWT.MULTI); *************** *** 260,264 **** // labelComposite.setLayout(labelLayout); // ! // Label failuresIconLabel = new Label(labelComposite, SWT.NONE); // failuresIconLabel.setImage(imageFailures); // failuresCountLabel = new Label(labelComposite, SWT.NONE); --- 260,264 ---- // labelComposite.setLayout(labelLayout); // ! // Label failuresIconLabel = new Label(labelComposite, SWT.NONE); // failuresIconLabel.setImage(imageFailures); // failuresCountLabel = new Label(labelComposite, SWT.NONE); *************** *** 271,280 **** // ((Label)errorsCountLabel).setText("Errors: "); // //errorsCountLabel.setSize(20,10); ! // // Table table = new Table(parent, SWT.SINGLE | SWT.H_SCROLL ! // | SWT.V_SCROLL | SWT.FULL_SELECTION); ! // table.setHeaderVisible(true); ! // table.setLinesVisible(true); ! // // GridData layoutData = new GridData(); // layoutData.grabExcessHorizontalSpace = true; --- 271,280 ---- // ((Label)errorsCountLabel).setText("Errors: "); // //errorsCountLabel.setSize(20,10); ! // // Table table = new Table(parent, SWT.SINGLE | SWT.H_SCROLL ! // | SWT.V_SCROLL | SWT.FULL_SELECTION); ! // table.setHeaderVisible(true); ! // table.setLinesVisible(true); ! // // GridData layoutData = new GridData(); // layoutData.grabExcessHorizontalSpace = true; *************** *** 283,324 **** // layoutData.verticalAlignment = GridData.FILL; // table.setLayoutData(layoutData); ! // ! // TableColumn column = new TableColumn(table, SWT.NONE, 0); ! // column.setText("Test"); ! // column.setWidth(300); ! // column.setAlignment(SWT.LEFT); // ! // column = new TableColumn(table, SWT.NONE, 1); ! // column.setText("Time (ms)"); ! // column.setWidth(100); ! // column.setAlignment(SWT.RIGHT); // ! // viewer = new TableViewer(table); ! // viewer.setLabelProvider(new TestReportLabelProvider()); ! // viewer.setContentProvider(new TestReportContentProvider()); ! // viewer.setInput(new ArrayList()); // ! // hookViewerActions(); ! // ! // // Register listener for colorLabel ! // listener = new LabelListener(); ! // PydevDebugPlugin.getDefault().addTestListener(listener); ! // ! // } // ! // public void dispose() { ! // fIsDisposed = true; ! // if (listener != null) { ! // PydevDebugPlugin.getDefault().removeTestListener(listener); ! // } ! // } // ! // /* (non-Javadoc) ! // * @see org.eclipse.ui.IWorkbenchPart#setFocus() ! // */ ! // public void setFocus() { ! // viewer.getControl().setFocus(); // ! // } // // private void hookViewerActions() { --- 283,324 ---- // layoutData.verticalAlignment = GridData.FILL; // table.setLayoutData(layoutData); ! // ! // TableColumn column = new TableColumn(table, SWT.NONE, 0); ! // column.setText("Test"); ! // column.setWidth(300); ! // column.setAlignment(SWT.LEFT); // ! // column = new TableColumn(table, SWT.NONE, 1); ! // column.setText("Time (ms)"); ! // column.setWidth(100); ! // column.setAlignment(SWT.RIGHT); // ! // viewer = new TableViewer(table); ! // viewer.setLabelProvider(new TestReportLabelProvider()); ! // viewer.setContentProvider(new TestReportContentProvider()); ! // viewer.setInput(new ArrayList()); // ! // hookViewerActions(); ! // ! // // Register listener for colorLabel ! // listener = new LabelListener(); ! // PydevDebugPlugin.getDefault().addTestListener(listener); ! // ! // } // ! // public void dispose() { ! // fIsDisposed = true; ! // if (listener != null) { ! // PydevDebugPlugin.getDefault().removeTestListener(listener); ! // } ! // } // ! // /* (non-Javadoc) ! // * @see org.eclipse.ui.IWorkbenchPart#setFocus() ! // */ ! // public void setFocus() { ! // viewer.getControl().setFocus(); // ! // } // // private void hookViewerActions() { *************** *** 330,378 **** // } // ! // ! // private boolean isDisposed() { ! // return fIsDisposed; ! // } ! // ! // private void postSyncRunnable(Runnable r) { ! // if (!isDisposed()) ! // getDisplay().syncExec(r); ! // } ! // ! // private Display getDisplay() { ! // return getViewSite().getShell().getDisplay(); ! // } ! // ! // protected void postShowTestReportView() { ! // postSyncRunnable(new Runnable() { ! // public void run() { ! // if (isDisposed()) ! // return; ! // showTestReportView(); ! // } ! // }); ! // } ! // public void showTestReportView() { ! // String viewName = "org.python.pydev.debug.unittest.TestReportView"; ! // IWorkbenchWindow window= getSite().getWorkbenchWindow(); ! // IWorkbenchPage page= window.getActivePage(); ! // TestReportView testRunner= null; ! // ! // if (page != null) { ! // try { // show the result view ! // testRunner= (TestReportView)page.findView(viewName); ! // if(testRunner == null) { ! // IWorkbenchPart activePart= page.getActivePart(); ! // testRunner= (TestReportView)page.showView(viewName); ! // //restore focus ! // page.activate(activePart); ! // } else { ! // page.bringToTop(testRunner); ! // } ! // } catch (PartInitException pie) { ! // pie.printStackTrace(); ! // } ! // } ! // } // //} --- 330,378 ---- // } // ! // ! // private boolean isDisposed() { ! // return fIsDisposed; ! // } ! // ! // private void postSyncRunnable(Runnable r) { ! // if (!isDisposed()) ! // getDisplay().syncExec(r); ! // } ! // ! // private Display getDisplay() { ! // return getViewSite().getShell().getDisplay(); ! // } ! // ! // protected void postShowTestReportView() { ! // postSyncRunnable(new Runnable() { ! // public void run() { ! // if (isDisposed()) ! // return; ! // showTestReportView(); ! // } ! // }); ! // } ! // public void showTestReportView() { ! // String viewName = "org.python.pydev.debug.unittest.TestReportView"; ! // IWorkbenchWindow window= getSite().getWorkbenchWindow(); ! // IWorkbenchPage page= window.getActivePage(); ! // TestReportView testRunner= null; ! // ! // if (page != null) { ! // try { // show the result view ! // testRunner= (TestReportView)page.findView(viewName); ! // if(testRunner == null) { ! // IWorkbenchPart activePart= page.getActivePart(); ! // testRunner= (TestReportView)page.showView(viewName); ! // //restore focus ! // page.activate(activePart); ! // } else { ! // page.bringToTop(testRunner); ! // } ! // } catch (PartInitException pie) { ! // pie.printStackTrace(); ! // } ! // } ! // } // //} Index: _TestReportLabelProvider.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/unittest/_TestReportLabelProvider.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** _TestReportLabelProvider.java 30 Mar 2008 21:45:18 -0000 1.1 --- _TestReportLabelProvider.java 27 Sep 2008 19:59:09 -0000 1.2 *************** *** 25,69 **** //public class TestReportLabelProvider extends LabelProvider //implements ITableLabelProvider, IColorProvider { ! // ! // private Image[] images; ! // ! // public TestReportLabelProvider() { ! // images = new Image[3]; ! // images[TestResult.OK] = PydevDebugPlugin.getDefault().imageCache.get("icons/testok.gif"); ! // images[TestResult.FAIL] = PydevDebugPlugin.getDefault().imageCache.get("icons/testfail.gif"); ! // images[TestResult.ERROR] = PydevDebugPlugin.getDefault().imageCache.get("icons/testerr.gif"); ! // } ! // ! // ! // public String getColumnText(Object element, int columnIndex) { ! // TestResult result = (TestResult)element; ! // switch(columnIndex) { ! // case 0: ! // return result.method + " - " + result.klass; ! // case 1: ! // return Long.toString(result.testDuration()); ! // } ! // return null; ! // } // ! // public Image getColumnImage(Object element, int columnIndex) { ! // if (columnIndex == 0) ! // return images[((TestResult)element).status]; ! // return null; ! // } // ! // public void dispose() { ! // for (int i = 0; i < images.length; i++) ! // images[i].dispose(); ! // } ! // ! // public Color getForeground(Object element) { ! // if (((TestResult)element).isFailure()) ! // return Display.getDefault().getSystemColor(SWT.COLOR_RED); ! // return null; ! // } ! // ! // public Color getBackground(Object element) { ! // return null; ! // } //} --- 25,69 ---- //public class TestReportLabelProvider extends LabelProvider //implements ITableLabelProvider, IColorProvider { ! // ! // private Image[] images; ! // ! // public TestReportLabelProvider() { ! // images = new Image[3]; ! // images[TestResult.OK] = PydevDebugPlugin.getDefault().imageCache.get("icons/testok.gif"); ! // images[TestResult.FAIL] = PydevDebugPlugin.getDefault().imageCache.get("icons/testfail.gif"); ! // images[TestResult.ERROR] = PydevDebugPlugin.getDefault().imageCache.get("icons/testerr.gif"); ! // } ! // ! // ! // public String getColumnText(Object element, int columnIndex) { ! // TestResult result = (TestResult)element; ! // switch(columnIndex) { ! // case 0: ! // return result.method + " - " + result.klass; ! // case 1: ! // return Long.toString(result.testDuration()); ! // } ! // return null; ! // } // ! // public Image getColumnImage(Object element, int columnIndex) { ! // if (columnIndex == 0) ! // return images[((TestResult)element).status]; ! // return null; ! // } // ! // public void dispose() { ! // for (int i = 0; i < images.length; i++) ! // images[i].dispose(); ! // } ! // ! // public Color getForeground(Object element) { ! // if (((TestResult)element).isFailure()) ! // return Display.getDefault().getSystemColor(SWT.COLOR_RED); ! // return null; ! // } ! // ! // public Color getBackground(Object element) { ! // return null; ! // } //} |
From: Fabio Z. <fa...@us...> - 2008-09-27 20:02:01
|
Update of /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/ui/actions In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv20604/src/org/python/pydev/debug/ui/actions Modified Files: WatchExpressionAction.java AbstractBreakpointRulerAction.java PythonTestActionDelegate.java PythonBreakpointPropertiesRulerActionDelegate.java RunEditorAsPython.java RunEditorAsJython.java ManageBreakpointRulerActionDelegate.java EnableDisableBreakpointRulerActionDelegate.java Log Message: Synching to latest changes: Pydev <ul> <li><strong>Editor</strong>: Cursor settings no longer overridden</li> <li><strong>Code-completion</strong>: If __all__ is defined with runtime elements (and not only in a single assign statement), it's ignored for code-completion purposes</li> <li><strong>Debugger</strong>: Pythonpath the same in debug and regular modes (sys.path[0] is the same directory as the file run)</li> <li><strong>Debugger</strong>: Persist choices done in the debugger when files from the debugger are not found</li> <li><strong>Interpreter config</strong>: "email" automatically added to the "forced builtins"</li> <li><strong>Parser</strong>: Correctly recognizing absolute import with 3 or more levels</li> <li><strong>Syntax check</strong>: Option to do only on active editor</li> </ul> Also: tabs changed for spaces Index: PythonBreakpointPropertiesRulerActionDelegate.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/ui/actions/PythonBreakpointPropertiesRulerActionDelegate.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** PythonBreakpointPropertiesRulerActionDelegate.java 17 Dec 2005 12:58:44 -0000 1.1 --- PythonBreakpointPropertiesRulerActionDelegate.java 27 Sep 2008 19:59:07 -0000 1.2 *************** *** 14,27 **** */ public class PythonBreakpointPropertiesRulerActionDelegate extends ! AbstractRulerActionDelegate { ! /* (non-Javadoc) ! * @see org.eclipse.ui.texteditor.AbstractRulerActionDelegate#createAction(org.eclipse.ui.texteditor.ITextEditor, org.eclipse.jface.text.source.IVerticalRulerInfo) ! */ ! @Override ! protected IAction createAction(ITextEditor editor, ! IVerticalRulerInfo rulerInfo) { ! return new PythonBreakpointPropertiesRulerAction(editor, rulerInfo); ! } } --- 14,27 ---- */ public class PythonBreakpointPropertiesRulerActionDelegate extends ! AbstractRulerActionDelegate { ! /* (non-Javadoc) ! * @see org.eclipse.ui.texteditor.AbstractRulerActionDelegate#createAction(org.eclipse.ui.texteditor.ITextEditor, org.eclipse.jface.text.source.IVerticalRulerInfo) ! */ ! @Override ! protected IAction createAction(ITextEditor editor, ! IVerticalRulerInfo rulerInfo) { ! return new PythonBreakpointPropertiesRulerAction(editor, rulerInfo); ! } } Index: PythonTestActionDelegate.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/ui/actions/PythonTestActionDelegate.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** PythonTestActionDelegate.java 21 Mar 2005 16:40:23 -0000 1.3 --- PythonTestActionDelegate.java 27 Sep 2008 19:59:07 -0000 1.4 *************** *** 28,162 **** */ public class PythonTestActionDelegate extends ActionDelegate ! implements IObjectActionDelegate { ! /** ! * @author ggheorg ! * ! * TODO To change the template for this generated type comment go to ! * Window - Preferences - Java - Code Style - Code Templates ! */ ! public static class Listener implements ITestRunListener { ! private boolean passed = true; ! public void testsStarted(int testCount) { ! System.out.println("STARTING TEST RUN: " + String.valueOf(testCount) + " tests"); ! } ! public void testsFinished() { ! String message = passed ? "PASS": "FAIL"; ! System.out.println("END TEST RUN"); ! String messageLong = "TEST RUN STATUS: " + message; ! System.out.println(messageLong); ! //MessageDialog.openInformation(null, "Test Results", messageLong); ! } ! public void testStarted(String klass, String method) { ! } ! public void testFailed(String klass, String method, String trace) { ! System.out.println("TEST FAILED!"); ! System.out.println(klass + " " + method); ! System.out.println(trace); ! passed = false; ! } ! } ! private IFile selectedFile; ! private IWorkbenchPart part; ! public void run(IAction action) { ! if (part != null && selectedFile != null) { ! try { ! // get the location of the workspace root ! /* ! IWorkspace workspace = ResourcesPlugin.getWorkspace(); ! IPath wsRootPath = workspace.getRoot().getLocation(); ! String wsRootDir = wsRootPath.toString(); ! */ ! // get the full physical path for the selected file ! IPath fullPath = selectedFile.getLocation(); ! int segmentCount = fullPath.segmentCount(); ! // get the test module name and path so that we can import it in Python ! IPath noextPath = fullPath.removeFileExtension(); ! String moduleName = noextPath.lastSegment(); ! IPath modulePath = fullPath.uptoSegment(segmentCount-1); ! String moduleDir = modulePath.toString(); ! // get the project the file belongs to ! IProject selectedProject = selectedFile.getProject(); ! ITestRunListener listener = new Listener(); ! PydevPlugin.getDefault().addTestListener(listener); ! try { ! PydevPlugin.getDefault().runTests(moduleDir, moduleName, selectedProject); ! } catch (CoreException e1) { ! // TODO Auto-generated catch block ! e1.printStackTrace(); ! } ! PydevPlugin.getDefault().removeTestListener(listener); ! ! /* Process p = Runtime.getRuntime().exec(new String[]{"python"}); ! ! //we have the process... ! OutputStreamWriter writer = new OutputStreamWriter(p.getOutputStream()); ! int bufsize = 64; // small bufsize so that we can see the progress ! BufferedReader in = new BufferedReader(new InputStreamReader(p ! .getInputStream()), bufsize); ! BufferedReader eIn = new BufferedReader(new InputStreamReader( ! p.getErrorStream()), bufsize); ! writer.write("import sys, os, unittest\n"); ! writer.write("os.chdir('" + wsRootDir + moduleDir + "')\n"); ! String arg = "sys.path.append('" + wsRootDir + moduleDir + "')\n"; ! writer.write(arg); ! arg = "unittest.TestProgram('" + moduleName + "', argv=['" + moduleName + "', '--verbose'])\n"; ! //arg = "unittest.TestProgram('" + moduleName + "')\n"; ! writer.write(arg); ! writer.flush(); ! writer.close(); ! ! String str; ! ArrayList testResults = new ArrayList(); ! while ((str = eIn.readLine()) != null) { ! //System.out.println("STDERR: " + str); ! //System.out.println(str); ! testResults.add(str); ! } ! eIn.close(); ! while ((str = in.readLine()) != null) { ! //System.out.println("STDOUT: " + str); ! System.out.println(str); ! } ! in.close(); ! p.waitFor(); ! System.out.println("testResults list:"); ! Iterator it = testResults.iterator(); ! while (it.hasNext()) { ! String line = it.next().toString(); ! ! System.out.println(line); ! } ! */ } catch (IOException e) { ! e.printStackTrace(); ! } ! } ! } ! ! public void selectionChanged(IAction action, ISelection selection) { ! selectedFile = null; ! if (selection instanceof IStructuredSelection) { ! if (((IStructuredSelection) selection).size() == 1) { ! Object selectedResource = ((IStructuredSelection) selection).getFirstElement(); ! if (selectedResource instanceof IFile) ! selectedFile = (IFile) selectedResource; ! } ! } ! } ! public void setActivePart(IAction action, IWorkbenchPart targetPart) { ! this.part = targetPart; ! } } --- 28,162 ---- */ public class PythonTestActionDelegate extends ActionDelegate ! implements IObjectActionDelegate { ! /** ! * @author ggheorg ! * ! * TODO To change the template for this generated type comment go to ! * Window - Preferences - Java - Code Style - Code Templates ! */ ! public static class Listener implements ITestRunListener { ! private boolean passed = true; ! public void testsStarted(int testCount) { ! System.out.println("STARTING TEST RUN: " + String.valueOf(testCount) + " tests"); ! } ! public void testsFinished() { ! String message = passed ? "PASS": "FAIL"; ! System.out.println("END TEST RUN"); ! String messageLong = "TEST RUN STATUS: " + message; ! System.out.println(messageLong); ! //MessageDialog.openInformation(null, "Test Results", messageLong); ! } ! public void testStarted(String klass, String method) { ! } ! public void testFailed(String klass, String method, String trace) { ! System.out.println("TEST FAILED!"); ! System.out.println(klass + " " + method); ! System.out.println(trace); ! passed = false; ! } ! } ! private IFile selectedFile; ! private IWorkbenchPart part; ! public void run(IAction action) { ! if (part != null && selectedFile != null) { ! try { ! // get the location of the workspace root ! /* ! IWorkspace workspace = ResourcesPlugin.getWorkspace(); ! IPath wsRootPath = workspace.getRoot().getLocation(); ! String wsRootDir = wsRootPath.toString(); ! */ ! // get the full physical path for the selected file ! IPath fullPath = selectedFile.getLocation(); ! int segmentCount = fullPath.segmentCount(); ! // get the test module name and path so that we can import it in Python ! IPath noextPath = fullPath.removeFileExtension(); ! String moduleName = noextPath.lastSegment(); ! IPath modulePath = fullPath.uptoSegment(segmentCount-1); ! String moduleDir = modulePath.toString(); ! // get the project the file belongs to ! IProject selectedProject = selectedFile.getProject(); ! ITestRunListener listener = new Listener(); ! PydevPlugin.getDefault().addTestListener(listener); ! try { ! PydevPlugin.getDefault().runTests(moduleDir, moduleName, selectedProject); ! } catch (CoreException e1) { ! // TODO Auto-generated catch block ! e1.printStackTrace(); ! } ! PydevPlugin.getDefault().removeTestListener(listener); ! ! /* Process p = Runtime.getRuntime().exec(new String[]{"python"}); ! ! //we have the process... ! OutputStreamWriter writer = new OutputStreamWriter(p.getOutputStream()); ! int bufsize = 64; // small bufsize so that we can see the progress ! BufferedReader in = new BufferedReader(new InputStreamReader(p ! .getInputStream()), bufsize); ! BufferedReader eIn = new BufferedReader(new InputStreamReader( ! p.getErrorStream()), bufsize); ! writer.write("import sys, os, unittest\n"); ! writer.write("os.chdir('" + wsRootDir + moduleDir + "')\n"); ! String arg = "sys.path.append('" + wsRootDir + moduleDir + "')\n"; ! writer.write(arg); ! arg = "unittest.TestProgram('" + moduleName + "', argv=['" + moduleName + "', '--verbose'])\n"; ! //arg = "unittest.TestProgram('" + moduleName + "')\n"; ! writer.write(arg); ! writer.flush(); ! writer.close(); ! ! String str; ! ArrayList testResults = new ArrayList(); ! while ((str = eIn.readLine()) != null) { ! //System.out.println("STDERR: " + str); ! //System.out.println(str); ! testResults.add(str); ! } ! eIn.close(); ! while ((str = in.readLine()) != null) { ! //System.out.println("STDOUT: " + str); ! System.out.println(str); ! } ! in.close(); ! p.waitFor(); ! System.out.println("testResults list:"); ! Iterator it = testResults.iterator(); ! while (it.hasNext()) { ! String line = it.next().toString(); ! ! System.out.println(line); ! } ! */ } catch (IOException e) { ! e.printStackTrace(); ! } ! } ! } ! ! public void selectionChanged(IAction action, ISelection selection) { ! selectedFile = null; ! if (selection instanceof IStructuredSelection) { ! if (((IStructuredSelection) selection).size() == 1) { ! Object selectedResource = ((IStructuredSelection) selection).getFirstElement(); ! if (selectedResource instanceof IFile) ! selectedFile = (IFile) selectedResource; ! } ! } ! } ! public void setActivePart(IAction action, IWorkbenchPart targetPart) { ! this.part = targetPart; ! } } Index: EnableDisableBreakpointRulerActionDelegate.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/ui/actions/EnableDisableBreakpointRulerActionDelegate.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** EnableDisableBreakpointRulerActionDelegate.java 17 Dec 2005 12:58:44 -0000 1.1 --- EnableDisableBreakpointRulerActionDelegate.java 27 Sep 2008 19:59:07 -0000 1.2 *************** *** 7,16 **** public class EnableDisableBreakpointRulerActionDelegate extends ! AbstractRulerActionDelegate { ! @Override ! protected IAction createAction(ITextEditor editor, IVerticalRulerInfo rulerInfo) { ! return new EnableDisableBreakpointRulerAction(editor, rulerInfo); ! } } --- 7,16 ---- public class EnableDisableBreakpointRulerActionDelegate extends ! AbstractRulerActionDelegate { ! @Override ! protected IAction createAction(ITextEditor editor, IVerticalRulerInfo rulerInfo) { ! return new EnableDisableBreakpointRulerAction(editor, rulerInfo); ! } } Index: AbstractBreakpointRulerAction.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/ui/actions/AbstractBreakpointRulerAction.java,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** AbstractBreakpointRulerAction.java 16 Sep 2007 17:15:20 -0000 1.8 --- AbstractBreakpointRulerAction.java 27 Sep 2008 19:59:07 -0000 1.9 *************** *** 37,86 **** public abstract class AbstractBreakpointRulerAction extends Action implements IUpdate { ! protected IVerticalRulerInfo fInfo; ! protected ITextEditor fTextEditor; ! private IBreakpoint fBreakpoint; ! protected IBreakpoint getBreakpoint() { ! return fBreakpoint; ! } ! protected void setBreakpoint(IBreakpoint breakpoint) { ! fBreakpoint = breakpoint; ! } ! protected ITextEditor getTextEditor() { ! return fTextEditor; ! } ! protected void setTextEditor(ITextEditor textEditor) { ! fTextEditor = textEditor; ! } ! protected IVerticalRulerInfo getInfo() { ! return fInfo; ! } ! protected void setInfo(IVerticalRulerInfo info) { ! fInfo = info; ! } ! protected IBreakpoint determineBreakpoint() { ! IBreakpoint[] breakpoints= DebugPlugin.getDefault().getBreakpointManager().getBreakpoints(PyDebugModelPresentation.PY_DEBUG_MODEL_ID); ! for (int i= 0; i < breakpoints.length; i++) { ! IBreakpoint breakpoint= breakpoints[i]; ! if (breakpoint instanceof PyBreakpoint ) { ! PyBreakpoint pyBreakpoint= (PyBreakpoint)breakpoint; ! try { ! if (breakpointAtRulerLine(pyBreakpoint, getPydevFileEditorInput())) { ! return pyBreakpoint; ! } ! } catch (CoreException ce) { ! PydevDebugPlugin.log(IStatus.ERROR,ce.getLocalizedMessage(),ce); ! continue; ! } ! } ! } ! return null; ! } /** --- 37,86 ---- public abstract class AbstractBreakpointRulerAction extends Action implements IUpdate { ! protected IVerticalRulerInfo fInfo; ! protected ITextEditor fTextEditor; ! private IBreakpoint fBreakpoint; ! protected IBreakpoint getBreakpoint() { ! return fBreakpoint; ! } ! protected void setBreakpoint(IBreakpoint breakpoint) { ! fBreakpoint = breakpoint; ! } ! protected ITextEditor getTextEditor() { ! return fTextEditor; ! } ! protected void setTextEditor(ITextEditor textEditor) { ! fTextEditor = textEditor; ! } ! protected IVerticalRulerInfo getInfo() { ! return fInfo; ! } ! protected void setInfo(IVerticalRulerInfo info) { ! fInfo = info; ! } ! protected IBreakpoint determineBreakpoint() { ! IBreakpoint[] breakpoints= DebugPlugin.getDefault().getBreakpointManager().getBreakpoints(PyDebugModelPresentation.PY_DEBUG_MODEL_ID); ! for (int i= 0; i < breakpoints.length; i++) { ! IBreakpoint breakpoint= breakpoints[i]; ! if (breakpoint instanceof PyBreakpoint ) { ! PyBreakpoint pyBreakpoint= (PyBreakpoint)breakpoint; ! try { ! if (breakpointAtRulerLine(pyBreakpoint, getPydevFileEditorInput())) { ! return pyBreakpoint; ! } ! } catch (CoreException ce) { ! PydevDebugPlugin.log(IStatus.ERROR,ce.getLocalizedMessage(),ce); ! continue; ! } ! } ! } ! return null; ! } /** *************** *** 92,102 **** } ! protected boolean breakpointAtRulerLine(PyBreakpoint pyBreakpoint, PydevFileEditorInput pydevFileEditorInput) throws CoreException { IDocument doc = getDocument(); ! IMarker marker = pyBreakpoint.getMarker(); Position position= getMarkerPosition(doc, marker); ! if (position != null) { ! try { ! int markerLineNumber= doc.getLineOfOffset(position.getOffset()); if(getResourceForDebugMarkers() instanceof IFile){ //workspace file --- 92,102 ---- } ! protected boolean breakpointAtRulerLine(PyBreakpoint pyBreakpoint, PydevFileEditorInput pydevFileEditorInput) throws CoreException { IDocument doc = getDocument(); ! IMarker marker = pyBreakpoint.getMarker(); Position position= getMarkerPosition(doc, marker); ! if (position != null) { ! try { ! int markerLineNumber= doc.getLineOfOffset(position.getOffset()); if(getResourceForDebugMarkers() instanceof IFile){ //workspace file *************** *** 111,131 **** return true; } ! } catch (BadLocationException x) { ! } ! } ! ! return false; ! } ! ! protected IResource getResourceForDebugMarkers() { ! return getResourceForDebugMarkers(fTextEditor); ! } ! public boolean isExternalFileEditor() { ! return isExternalFileEditor(fTextEditor); ! } ! public PydevFileEditorInput getPydevFileEditorInput() { ! return getPydevFileEditorInput(fTextEditor); } --- 111,131 ---- return true; } ! } catch (BadLocationException x) { ! } ! } ! ! return false; ! } ! ! protected IResource getResourceForDebugMarkers() { ! return getResourceForDebugMarkers(fTextEditor); ! } ! public boolean isExternalFileEditor() { ! return isExternalFileEditor(fTextEditor); ! } ! public PydevFileEditorInput getPydevFileEditorInput() { ! return getPydevFileEditorInput(fTextEditor); } *************** *** 136,169 **** // utilities ------------------------------------------------------------------------------------------------------- ! ! /** ! * @return whether we're in an external editor or not. ! */ ! public static boolean isExternalFileEditor(ITextEditor editor) { ! PydevFileEditorInput pydevFileEditorInput = getPydevFileEditorInput(editor); ! if(pydevFileEditorInput != null){ ! return true; ! } ! return false; ! } ! ! ! ! /** ! * @return the PydevFileEditorInput if we're dealing with an external file (or null otherwise) ! */ ! public static PydevFileEditorInput getPydevFileEditorInput(ITextEditor editor) { ! IEditorInput input = editor.getEditorInput(); ! PydevFileEditorInput pydevFileEditorInput = null; ! //only return not null if it's an external file (FileEditorInput marks a workspace file) if(input instanceof FileEditorInput){ return null; } ! if (input instanceof PydevFileEditorInput) { ! pydevFileEditorInput = (PydevFileEditorInput) input; ! } else { if(input instanceof IPathEditorInput && !(input instanceof FileEditorInput)){ IPathEditorInput pathEditorInput = (IPathEditorInput) input; --- 136,169 ---- // utilities ------------------------------------------------------------------------------------------------------- ! ! /** ! * @return whether we're in an external editor or not. ! */ ! public static boolean isExternalFileEditor(ITextEditor editor) { ! PydevFileEditorInput pydevFileEditorInput = getPydevFileEditorInput(editor); ! if(pydevFileEditorInput != null){ ! return true; ! } ! return false; ! } ! ! ! ! /** ! * @return the PydevFileEditorInput if we're dealing with an external file (or null otherwise) ! */ ! public static PydevFileEditorInput getPydevFileEditorInput(ITextEditor editor) { ! IEditorInput input = editor.getEditorInput(); ! PydevFileEditorInput pydevFileEditorInput = null; ! //only return not null if it's an external file (FileEditorInput marks a workspace file) if(input instanceof FileEditorInput){ return null; } ! if (input instanceof PydevFileEditorInput) { ! pydevFileEditorInput = (PydevFileEditorInput) input; ! } else { if(input instanceof IPathEditorInput && !(input instanceof FileEditorInput)){ IPathEditorInput pathEditorInput = (IPathEditorInput) input; *************** *** 174,180 **** } } ! } ! return pydevFileEditorInput; ! } --- 174,180 ---- } } ! } ! return pydevFileEditorInput; ! } *************** *** 184,202 **** */ protected static boolean isInSameExternalEditor(IMarker marker, PydevFileEditorInput pydevFileEditorInput) throws CoreException { ! if(marker == null || pydevFileEditorInput == null){ ! return false; ! } ! String attribute = (String) marker.getAttribute(PyBreakpoint.PY_BREAK_EXTERNAL_PATH_ID); if(attribute != null){ File file = pydevFileEditorInput.getFile(); if(file == null){ ! return false; } ! if(attribute.equals(REF.getFileAbsolutePath(file))){ return true; } } ! return false; } --- 184,202 ---- */ protected static boolean isInSameExternalEditor(IMarker marker, PydevFileEditorInput pydevFileEditorInput) throws CoreException { ! if(marker == null || pydevFileEditorInput == null){ ! return false; ! } ! String attribute = (String) marker.getAttribute(PyBreakpoint.PY_BREAK_EXTERNAL_PATH_ID); if(attribute != null){ File file = pydevFileEditorInput.getFile(); if(file == null){ ! return false; } ! if(attribute.equals(REF.getFileAbsolutePath(file))){ return true; } } ! return false; } *************** *** 234,254 **** ! /** ! * @return the resource for which to create the marker or <code>null</code> * * If the editor maps to a workspace file, it will return that file. Otherwise, it will return the * workspace root (so, markers from external files will be created in the workspace root). ! */ ! public static IResource getResourceForDebugMarkers(ITextEditor textEditor) { ! IEditorInput input= textEditor.getEditorInput(); ! IResource resource= (IResource) input.getAdapter(IFile.class); ! if (resource == null) { ! resource= (IResource) input.getAdapter(IResource.class); ! } if(resource == null){ resource = ResourcesPlugin.getWorkspace().getRoot(); } ! return resource; ! } --- 234,254 ---- ! /** ! * @return the resource for which to create the marker or <code>null</code> * * If the editor maps to a workspace file, it will return that file. Otherwise, it will return the * workspace root (so, markers from external files will be created in the workspace root). ! */ ! public static IResource getResourceForDebugMarkers(ITextEditor textEditor) { ! IEditorInput input= textEditor.getEditorInput(); ! IResource resource= (IResource) input.getAdapter(IFile.class); ! if (resource == null) { ! resource= (IResource) input.getAdapter(IResource.class); ! } if(resource == null){ resource = ResourcesPlugin.getWorkspace().getRoot(); } ! return resource; ! } *************** *** 309,315 **** IBreakpointManager breakpointManager = DebugPlugin.getDefault().getBreakpointManager(); for (IMarker marker : markers) { ! if(marker == null){ ! continue; ! } IBreakpoint breakpoint = breakpointManager.getBreakpoint(marker); if (breakpoint != null && breakpointManager.isRegistered(breakpoint)) { --- 309,315 ---- IBreakpointManager breakpointManager = DebugPlugin.getDefault().getBreakpointManager(); for (IMarker marker : markers) { ! if(marker == null){ ! continue; ! } IBreakpoint breakpoint = breakpointManager.getBreakpoint(marker); if (breakpoint != null && breakpointManager.isRegistered(breakpoint)) { Index: WatchExpressionAction.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/ui/actions/WatchExpressionAction.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** WatchExpressionAction.java 5 Oct 2005 19:47:11 -0000 1.1 --- WatchExpressionAction.java 27 Sep 2008 19:59:07 -0000 1.2 *************** *** 19,69 **** public class WatchExpressionAction implements IEditorActionDelegate { ! private ITextSelection fSelection; ! public void setActiveEditor(IAction action, IEditorPart targetEditor) { ! } ! public void run(IAction action) { ! if (fSelection == null) { ! return; ! } ! String text = fSelection.getText(); ! createExpression(text); ! } ! public void selectionChanged(IAction action, ISelection selection) { ! fSelection = null; if (selection instanceof ITextSelection ) { fSelection = (ITextSelection) selection; } ! } ! ! private void showExpressionsView() { ! IWorkbenchPage page = PydevDebugPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow().getActivePage(); ! IViewPart part = page.findView(IDebugUIConstants.ID_EXPRESSION_VIEW); ! if (part == null) { ! try { ! page.showView(IDebugUIConstants.ID_EXPRESSION_VIEW); ! } catch (PartInitException e) { ! } ! } else { ! page.bringToTop(part); ! } ! } ! private void createExpression(String variable) { ! IWatchExpression expression = DebugPlugin.getDefault().getExpressionManager().newWatchExpression(variable); ! ! DebugPlugin.getDefault().getExpressionManager().addExpression(expression); ! IAdaptable object = DebugUITools.getDebugContext(); ! IDebugElement context = null; ! if (object instanceof IDebugElement) { ! context = (IDebugElement) object; ! } else if (object instanceof ILaunch) { ! context = ((ILaunch) object).getDebugTarget(); ! } ! expression.setExpressionContext(context); ! showExpressionsView(); ! } } --- 19,69 ---- public class WatchExpressionAction implements IEditorActionDelegate { ! private ITextSelection fSelection; ! public void setActiveEditor(IAction action, IEditorPart targetEditor) { ! } ! public void run(IAction action) { ! if (fSelection == null) { ! return; ! } ! String text = fSelection.getText(); ! createExpression(text); ! } ! public void selectionChanged(IAction action, ISelection selection) { ! fSelection = null; if (selection instanceof ITextSelection ) { fSelection = (ITextSelection) selection; } ! } ! ! private void showExpressionsView() { ! IWorkbenchPage page = PydevDebugPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow().getActivePage(); ! IViewPart part = page.findView(IDebugUIConstants.ID_EXPRESSION_VIEW); ! if (part == null) { ! try { ! page.showView(IDebugUIConstants.ID_EXPRESSION_VIEW); ! } catch (PartInitException e) { ! } ! } else { ! page.bringToTop(part); ! } ! } ! private void createExpression(String variable) { ! IWatchExpression expression = DebugPlugin.getDefault().getExpressionManager().newWatchExpression(variable); ! ! DebugPlugin.getDefault().getExpressionManager().addExpression(expression); ! IAdaptable object = DebugUITools.getDebugContext(); ! IDebugElement context = null; ! if (object instanceof IDebugElement) { ! context = (IDebugElement) object; ! } else if (object instanceof ILaunch) { ! context = ((ILaunch) object).getDebugTarget(); ! } ! expression.setExpressionContext(context); ! showExpressionsView(); ! } } Index: RunEditorAsPython.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/ui/actions/RunEditorAsPython.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** RunEditorAsPython.java 3 Feb 2006 11:52:02 -0000 1.1 --- RunEditorAsPython.java 27 Sep 2008 19:59:07 -0000 1.2 *************** *** 7,14 **** public class RunEditorAsPython extends PyAction{ ! public void run(IAction action) { ! LaunchShortcut shortcut = new LaunchShortcut(); ! shortcut.launch(getPyEdit(), "run"); ! } } --- 7,14 ---- public class RunEditorAsPython extends PyAction{ ! public void run(IAction action) { ! LaunchShortcut shortcut = new LaunchShortcut(); ! shortcut.launch(getPyEdit(), "run"); ! } } Index: ManageBreakpointRulerActionDelegate.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/ui/actions/ManageBreakpointRulerActionDelegate.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** ManageBreakpointRulerActionDelegate.java 7 May 2004 02:03:05 -0000 1.1 --- ManageBreakpointRulerActionDelegate.java 27 Sep 2008 19:59:07 -0000 1.2 *************** *** 15,22 **** */ public class ManageBreakpointRulerActionDelegate ! extends AbstractRulerActionDelegate { ! protected IAction createAction(ITextEditor editor, IVerticalRulerInfo rulerInfo) { ! return new BreakpointRulerAction(editor, rulerInfo); ! } } --- 15,22 ---- */ public class ManageBreakpointRulerActionDelegate ! extends AbstractRulerActionDelegate { ! protected IAction createAction(ITextEditor editor, IVerticalRulerInfo rulerInfo) { ! return new BreakpointRulerAction(editor, rulerInfo); ! } } Index: RunEditorAsJython.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src/org/python/pydev/debug/ui/actions/RunEditorAsJython.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** RunEditorAsJython.java 3 Feb 2006 11:52:02 -0000 1.1 --- RunEditorAsJython.java 27 Sep 2008 19:59:07 -0000 1.2 *************** *** 7,14 **** public class RunEditorAsJython extends PyAction{ ! public void run(IAction action) { ! JythonLaunchShortcut shortcut = new JythonLaunchShortcut(); ! shortcut.launch(getPyEdit(), "run"); ! } } --- 7,14 ---- public class RunEditorAsJython extends PyAction{ ! public void run(IAction action) { ! JythonLaunchShortcut shortcut = new JythonLaunchShortcut(); ! shortcut.launch(getPyEdit(), "run"); ! } } |
Update of /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/ast/adapters/offsetstrategy In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv21605/src/org/python/pydev/refactoring/ast/adapters/offsetstrategy Modified Files: InitOffset.java AbstractOffsetStrategy.java EndOffset.java IOffsetStrategy.java BeginOffset.java Log Message: Synching to latest changes: Pydev <ul> <li><strong>Editor</strong>: Cursor settings no longer overridden</li> <li><strong>Code-completion</strong>: If __all__ is defined with runtime elements (and not only in a single assign statement), it's ignored for code-completion purposes</li> <li><strong>Debugger</strong>: Pythonpath the same in debug and regular modes (sys.path[0] is the same directory as the file run)</li> <li><strong>Debugger</strong>: Persist choices done in the debugger when files from the debugger are not found</li> <li><strong>Interpreter config</strong>: "email" automatically added to the "forced builtins"</li> <li><strong>Parser</strong>: Correctly recognizing absolute import with 3 or more levels</li> <li><strong>Syntax check</strong>: Option to do only on active editor</li> </ul> Also: tabs changed for spaces Index: BeginOffset.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/ast/adapters/offsetstrategy/BeginOffset.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** BeginOffset.java 20 Oct 2007 19:31:02 -0000 1.3 --- BeginOffset.java 27 Sep 2008 20:00:51 -0000 1.4 *************** *** 22,46 **** public class BeginOffset extends AbstractOffsetStrategy { ! public BeginOffset(IASTNodeAdapter<? extends SimpleNode> adapter, IDocument doc) { ! super(adapter, doc); ! } ! protected int getLine() { ! SimpleNode node = adapter.getASTNode(); ! if(nodeHelper.isClassDef(node)){ ! ClassDef classNode = (ClassDef) node; ! Str strNode = NodeUtils.getNodeDocStringNode(node); ! ! if(strNode != null){ ! return NodeUtils.getLineEnd(strNode) -1; ! } ! ! FindLastLineVisitor findLastLineVisitor = new FindLastLineVisitor(); try { classNode.name.accept(findLastLineVisitor); if(classNode.bases != null){ ! for (SimpleNode n : classNode.bases) { ! n.accept(findLastLineVisitor); ! } } SimpleNode lastNode = findLastLineVisitor.getLastNode(); --- 22,46 ---- public class BeginOffset extends AbstractOffsetStrategy { ! public BeginOffset(IASTNodeAdapter<? extends SimpleNode> adapter, IDocument doc) { ! super(adapter, doc); ! } ! protected int getLine() { ! SimpleNode node = adapter.getASTNode(); ! if(nodeHelper.isClassDef(node)){ ! ClassDef classNode = (ClassDef) node; ! Str strNode = NodeUtils.getNodeDocStringNode(node); ! ! if(strNode != null){ ! return NodeUtils.getLineEnd(strNode) -1; ! } ! ! FindLastLineVisitor findLastLineVisitor = new FindLastLineVisitor(); try { classNode.name.accept(findLastLineVisitor); if(classNode.bases != null){ ! for (SimpleNode n : classNode.bases) { ! n.accept(findLastLineVisitor); ! } } SimpleNode lastNode = findLastLineVisitor.getLastNode(); *************** *** 56,75 **** } ! } ! ! int startLine = adapter.getNodeFirstLine() - 1; ! if (startLine < 0){ ! startLine = 0; ! } ! return startLine; ! } ! @Override ! protected int getLineIndendation() throws BadLocationException { ! if (adapter.getNodeBodyIndent() == 0) ! return 0; ! else { ! return doc.getLineLength(getLine()); ! } ! } } --- 56,75 ---- } ! } ! ! int startLine = adapter.getNodeFirstLine() - 1; ! if (startLine < 0){ ! startLine = 0; ! } ! return startLine; ! } ! @Override ! protected int getLineIndendation() throws BadLocationException { ! if (adapter.getNodeBodyIndent() == 0) ! return 0; ! else { ! return doc.getLineLength(getLine()); ! } ! } } Index: EndOffset.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/ast/adapters/offsetstrategy/EndOffset.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** EndOffset.java 20 Oct 2007 19:31:02 -0000 1.2 --- EndOffset.java 27 Sep 2008 20:00:51 -0000 1.3 *************** *** 15,28 **** public class EndOffset extends AbstractOffsetStrategy { ! public EndOffset(IASTNodeAdapter<? extends SimpleNode> adapter, IDocument doc) { ! super(adapter, doc); ! } ! protected int getLine() { ! int endLine = adapter.getNodeLastLine() - 1; ! if (endLine < 0) ! endLine = 0; ! return endLine; ! } } --- 15,28 ---- public class EndOffset extends AbstractOffsetStrategy { ! public EndOffset(IASTNodeAdapter<? extends SimpleNode> adapter, IDocument doc) { ! super(adapter, doc); ! } ! protected int getLine() { ! int endLine = adapter.getNodeLastLine() - 1; ! if (endLine < 0) ! endLine = 0; ! return endLine; ! } } Index: InitOffset.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/ast/adapters/offsetstrategy/InitOffset.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** InitOffset.java 20 Oct 2007 19:31:02 -0000 1.4 --- InitOffset.java 27 Sep 2008 20:00:50 -0000 1.5 *************** *** 20,44 **** public class InitOffset extends BeginOffset { ! public InitOffset(IASTNodeAdapter<? extends SimpleNode> adapter, IDocument doc) { ! super(adapter, doc); ! } ! @Override ! protected int getLine() { ! SimpleNode node = adapter.getASTNode(); ! if (nodeHelper.isClassDef(node)) { ! ClassDef classNode = (ClassDef) node; ! for (stmtType statement : classNode.body) { ! if (nodeHelper.isInit(statement)) { ! FunctionDef func = (FunctionDef) statement; ! stmtType lastStmt = func.body[func.body.length - 1]; ! LastLineVisitor visitor = VisitorFactory.createVisitor(LastLineVisitor.class, lastStmt); ! return visitor.getLastLine() - 1; ! } ! } ! } ! return super.getLine(); ! } } --- 20,44 ---- public class InitOffset extends BeginOffset { ! public InitOffset(IASTNodeAdapter<? extends SimpleNode> adapter, IDocument doc) { ! super(adapter, doc); ! } ! @Override ! protected int getLine() { ! SimpleNode node = adapter.getASTNode(); ! if (nodeHelper.isClassDef(node)) { ! ClassDef classNode = (ClassDef) node; ! for (stmtType statement : classNode.body) { ! if (nodeHelper.isInit(statement)) { ! FunctionDef func = (FunctionDef) statement; ! stmtType lastStmt = func.body[func.body.length - 1]; ! LastLineVisitor visitor = VisitorFactory.createVisitor(LastLineVisitor.class, lastStmt); ! return visitor.getLastLine() - 1; ! } ! } ! } ! return super.getLine(); ! } } Index: AbstractOffsetStrategy.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/ast/adapters/offsetstrategy/AbstractOffsetStrategy.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** AbstractOffsetStrategy.java 20 Oct 2007 19:31:02 -0000 1.3 --- AbstractOffsetStrategy.java 27 Sep 2008 20:00:51 -0000 1.4 *************** *** 19,50 **** public abstract class AbstractOffsetStrategy implements IOffsetStrategy { ! protected IDocument doc; ! protected IASTNodeAdapter<? extends SimpleNode> adapter; ! protected NodeHelper nodeHelper; ! public AbstractOffsetStrategy(IASTNodeAdapter<? extends SimpleNode> adapter, IDocument doc) { ! this.adapter = adapter; ! this.doc = doc; ! this.nodeHelper = new NodeHelper(TextUtilities.getDefaultLineDelimiter(doc)); ! } ! protected IRegion getRegion() throws BadLocationException { ! return doc.getLineInformation(getLine()); ! } ! protected int getLineOffset() throws BadLocationException { ! return getRegion().getOffset(); ! } ! protected int getLineIndendation() throws BadLocationException { ! return doc.getLineLength(getLine()); ! } ! public int getOffset() throws BadLocationException { ! return getLineOffset() + getLineIndendation(); ! } ! protected abstract int getLine(); } --- 19,50 ---- public abstract class AbstractOffsetStrategy implements IOffsetStrategy { ! protected IDocument doc; ! protected IASTNodeAdapter<? extends SimpleNode> adapter; ! protected NodeHelper nodeHelper; ! public AbstractOffsetStrategy(IASTNodeAdapter<? extends SimpleNode> adapter, IDocument doc) { ! this.adapter = adapter; ! this.doc = doc; ! this.nodeHelper = new NodeHelper(TextUtilities.getDefaultLineDelimiter(doc)); ! } ! protected IRegion getRegion() throws BadLocationException { ! return doc.getLineInformation(getLine()); ! } ! protected int getLineOffset() throws BadLocationException { ! return getRegion().getOffset(); ! } ! protected int getLineIndendation() throws BadLocationException { ! return doc.getLineLength(getLine()); ! } ! public int getOffset() throws BadLocationException { ! return getLineOffset() + getLineIndendation(); ! } ! protected abstract int getLine(); } Index: IOffsetStrategy.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/ast/adapters/offsetstrategy/IOffsetStrategy.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** IOffsetStrategy.java 20 Oct 2007 19:31:02 -0000 1.2 --- IOffsetStrategy.java 27 Sep 2008 20:00:51 -0000 1.3 *************** *** 12,22 **** public interface IOffsetStrategy { ! public static final int AFTERINIT = 1; ! public final static int BEGIN = 2; ! public final static int END = 4; ! public abstract int getOffset() throws BadLocationException; } --- 12,22 ---- public interface IOffsetStrategy { ! public static final int AFTERINIT = 1; ! public final static int BEGIN = 2; ! public final static int END = 4; ! public abstract int getOffset() throws BadLocationException; } |
From: Fabio Z. <fa...@us...> - 2008-09-27 20:01:42
|
Update of /cvsroot/pydev/org.python.pydev.debug/src_console/org/python/pydev/debug/newconsole/env In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv20604/src_console/org/python/pydev/debug/newconsole/env Modified Files: IProcessFactory.java ChooseProcessTypeDialog.java PydevSpawnedInterpreterProcess.java Log Message: Synching to latest changes: Pydev <ul> <li><strong>Editor</strong>: Cursor settings no longer overridden</li> <li><strong>Code-completion</strong>: If __all__ is defined with runtime elements (and not only in a single assign statement), it's ignored for code-completion purposes</li> <li><strong>Debugger</strong>: Pythonpath the same in debug and regular modes (sys.path[0] is the same directory as the file run)</li> <li><strong>Debugger</strong>: Persist choices done in the debugger when files from the debugger are not found</li> <li><strong>Interpreter config</strong>: "email" automatically added to the "forced builtins"</li> <li><strong>Parser</strong>: Correctly recognizing absolute import with 3 or more levels</li> <li><strong>Syntax check</strong>: Option to do only on active editor</li> </ul> Also: tabs changed for spaces Index: ChooseProcessTypeDialog.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src_console/org/python/pydev/debug/newconsole/env/ChooseProcessTypeDialog.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** ChooseProcessTypeDialog.java 24 Mar 2008 01:53:27 -0000 1.2 --- ChooseProcessTypeDialog.java 27 Sep 2008 19:59:06 -0000 1.3 *************** *** 26,30 **** */ final class ChooseProcessTypeDialog extends Dialog { ! private Button checkboxForCurrentEditor; --- 26,30 ---- */ final class ChooseProcessTypeDialog extends Dialog { ! private Button checkboxForCurrentEditor; *************** *** 33,43 **** private Button checkboxJython; ! private PyEdit activeEditor; ! private Collection<String> pythonpath; ! private IInterpreterManager interpreterManager; ! ! private List<IPythonNature> natures = new ArrayList<IPythonNature>(); ChooseProcessTypeDialog(Shell shell, PyEdit activeEditor) { --- 33,43 ---- private Button checkboxJython; ! private PyEdit activeEditor; ! private Collection<String> pythonpath; ! private IInterpreterManager interpreterManager; ! ! private List<IPythonNature> natures = new ArrayList<IPythonNature>(); ChooseProcessTypeDialog(Shell shell, PyEdit activeEditor) { *************** *** 70,87 **** */ private void configureButton(Button checkBox, String python, IInterpreterManager interpreterManager) { ! boolean enabled = false; ! String text; ! try{ ! if(interpreterManager.getDefaultInterpreter() != null){ ! text = python+" console"; ! enabled = true; ! }else{ ! throw new NotConfiguredInterpreterException(); ! } ! }catch(NotConfiguredInterpreterException e){ ! text = "Unable to create console for "+python+" (interpreter not configured)"; ! } ! checkBox.setText(text); ! checkBox.setEnabled(enabled); } --- 70,87 ---- */ private void configureButton(Button checkBox, String python, IInterpreterManager interpreterManager) { ! boolean enabled = false; ! String text; ! try{ ! if(interpreterManager.getDefaultInterpreter() != null){ ! text = python+" console"; ! enabled = true; ! }else{ ! throw new NotConfiguredInterpreterException(); ! } ! }catch(NotConfiguredInterpreterException e){ ! text = "Unable to create console for "+python+" (interpreter not configured)"; ! } ! checkBox.setText(text); ! checkBox.setEnabled(enabled); } *************** *** 89,164 **** * Configures a button related to an editor. */ ! private void configureEditorButton() { ! boolean enabled = false; String text; try{ if(this.activeEditor != null){ ! IPythonNature nature = this.activeEditor.getPythonNature(); ! if(nature != null){ ! ! if(nature.getRelatedInterpreterManager().getDefaultInterpreter() != null){ ! text = "Console for currently active editor"; ! enabled = true; ! }else{ ! throw new NotConfiguredInterpreterException(); ! } ! }else{ ! text = "No python nature configured for the current editor"; ! } }else{ ! text = "Unable to create console for current editor (no active editor)"; } }catch(NotConfiguredInterpreterException e){ ! //expected ! text = "Unable to create console for current editor (interpreter not configured for the editor)"; } checkboxForCurrentEditor.setText(text); checkboxForCurrentEditor.setEnabled(enabled); ! } ! ! /** ! * Sets the internal pythonpath chosen. ! */ @Override protected void okPressed() { ! IInterpreterManager localInterpreterManager = null; ! if(checkboxForCurrentEditor.isEnabled() && checkboxForCurrentEditor.getSelection()){ ! IProject project = this.activeEditor.getProject(); ! PythonNature nature = PythonNature.getPythonNature(project); ! natures.add(nature); ! this.pythonpath = new ArrayList<String>(nature.getPythonPathNature().getCompleteProjectPythonPath( ! nature.getRelatedInterpreterManager().getDefaultInterpreter())); ! this.interpreterManager = nature.getRelatedInterpreterManager(); ! }else if(checkboxPython.isEnabled() && checkboxPython.getSelection()){ ! localInterpreterManager = PydevPlugin.getPythonInterpreterManager(); ! }else if(checkboxJython.isEnabled() && checkboxJython.getSelection()){ ! localInterpreterManager = PydevPlugin.getJythonInterpreterManager(); ! } if(localInterpreterManager != null){ ! this.interpreterManager = localInterpreterManager; ! String defaultInterpreter = localInterpreterManager.getDefaultInterpreter(); ! IWorkspace w = ResourcesPlugin.getWorkspace(); ! HashSet<String> pythonpath = new HashSet<String>(); ! for(IProject p:w.getRoot().getProjects()){ ! PythonNature nature = PythonNature.getPythonNature(p); ! try{ ! if(nature != null){ ! if(nature.getRelatedInterpreterManager() == localInterpreterManager){ ! natures.add(nature); ! pythonpath.addAll(nature.getPythonPathNature(). ! getCompleteProjectPythonPath(defaultInterpreter)); ! } ! } ! }catch(Exception e){ ! PydevPlugin.log(e); ! } ! } ! this.pythonpath = pythonpath; } --- 89,164 ---- * Configures a button related to an editor. */ ! private void configureEditorButton() { ! boolean enabled = false; String text; try{ if(this.activeEditor != null){ ! IPythonNature nature = this.activeEditor.getPythonNature(); ! if(nature != null){ ! ! if(nature.getRelatedInterpreterManager().getDefaultInterpreter() != null){ ! text = "Console for currently active editor"; ! enabled = true; ! }else{ ! throw new NotConfiguredInterpreterException(); ! } ! }else{ ! text = "No python nature configured for the current editor"; ! } }else{ ! text = "Unable to create console for current editor (no active editor)"; } }catch(NotConfiguredInterpreterException e){ ! //expected ! text = "Unable to create console for current editor (interpreter not configured for the editor)"; } checkboxForCurrentEditor.setText(text); checkboxForCurrentEditor.setEnabled(enabled); ! } ! ! /** ! * Sets the internal pythonpath chosen. ! */ @Override protected void okPressed() { ! IInterpreterManager localInterpreterManager = null; ! if(checkboxForCurrentEditor.isEnabled() && checkboxForCurrentEditor.getSelection()){ ! IProject project = this.activeEditor.getProject(); ! PythonNature nature = PythonNature.getPythonNature(project); ! natures.add(nature); ! this.pythonpath = new ArrayList<String>(nature.getPythonPathNature().getCompleteProjectPythonPath( ! nature.getRelatedInterpreterManager().getDefaultInterpreter())); ! this.interpreterManager = nature.getRelatedInterpreterManager(); ! }else if(checkboxPython.isEnabled() && checkboxPython.getSelection()){ ! localInterpreterManager = PydevPlugin.getPythonInterpreterManager(); ! }else if(checkboxJython.isEnabled() && checkboxJython.getSelection()){ ! localInterpreterManager = PydevPlugin.getJythonInterpreterManager(); ! } if(localInterpreterManager != null){ ! this.interpreterManager = localInterpreterManager; ! String defaultInterpreter = localInterpreterManager.getDefaultInterpreter(); ! IWorkspace w = ResourcesPlugin.getWorkspace(); ! HashSet<String> pythonpath = new HashSet<String>(); ! for(IProject p:w.getRoot().getProjects()){ ! PythonNature nature = PythonNature.getPythonNature(p); ! try{ ! if(nature != null){ ! if(nature.getRelatedInterpreterManager() == localInterpreterManager){ ! natures.add(nature); ! pythonpath.addAll(nature.getPythonPathNature(). ! getCompleteProjectPythonPath(defaultInterpreter)); ! } ! } ! }catch(Exception e){ ! PydevPlugin.log(e); ! } ! } ! this.pythonpath = pythonpath; } *************** *** 174,182 **** } ! public IInterpreterManager getInterpreterManager() { ! return this.interpreterManager; ! } ! ! public List<IPythonNature> getNatures() { return natures; } --- 174,182 ---- } ! public IInterpreterManager getInterpreterManager() { ! return this.interpreterManager; ! } ! ! public List<IPythonNature> getNatures() { return natures; } Index: IProcessFactory.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src_console/org/python/pydev/debug/newconsole/env/IProcessFactory.java,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** IProcessFactory.java 31 Jul 2008 23:48:22 -0000 1.8 --- IProcessFactory.java 27 Sep 2008 19:59:06 -0000 1.9 *************** *** 63,67 **** public Tuple3<Launch, Process, Integer> createInteractiveLaunch() throws UserCanceledException, Exception { ! IWorkbenchWindow workbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); IWorkbenchPage activePage = workbenchWindow.getActivePage(); --- 63,67 ---- public Tuple3<Launch, Process, Integer> createInteractiveLaunch() throws UserCanceledException, Exception { ! IWorkbenchWindow workbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); IWorkbenchPage activePage = workbenchWindow.getActivePage(); *************** *** 76,119 **** ChooseProcessTypeDialog dialog = new ChooseProcessTypeDialog(getShell(), edit); if(dialog.open() == ChooseProcessTypeDialog.OK){ ! ! Collection<String> pythonpath = dialog.getPythonpath(); ! IInterpreterManager interpreterManager = dialog.getInterpreterManager(); ! ! if(pythonpath != null && interpreterManager != null){ ! naturesUsed = dialog.getNatures(); ! int port = SocketUtil.findUnusedLocalPort(); ! int clientPort = SocketUtil.findUnusedLocalPort(); ! ! final Launch launch = new Launch(null, "interactive", null); ! launch.setAttribute(DebugPlugin.ATTR_CAPTURE_OUTPUT, "false"); ! launch.setAttribute(INTERACTIVE_LAUNCH_PORT, ""+port); ! ! String pythonpathEnv = SimpleRunner.makePythonPathEnvFromPaths(pythonpath); ! String[] env = SimpleRunner.createEnvWithPythonpath(pythonpathEnv); ! ! File scriptWithinPySrc = PydevPlugin.getScriptWithinPySrc("pydevconsole.py"); ! String[] commandLine; ! if(interpreterManager.isPython()){ ! commandLine = SimplePythonRunner.makeExecutableCommandStr(scriptWithinPySrc.getAbsolutePath(), ! new String[]{String.valueOf(port), String.valueOf(clientPort)}); ! ! }else if(interpreterManager.isJython()){ ! String vmArgs = PydevDebugPlugin.getDefault().getPreferenceStore(). ! getString(PydevConsoleConstants.INTERACTIVE_CONSOLE_VM_ARGS); ! ! commandLine = SimpleJythonRunner.makeExecutableCommandStrWithVMArgs(scriptWithinPySrc.getAbsolutePath(), ! pythonpathEnv, vmArgs, new String[]{String.valueOf(port), String.valueOf(clientPort)}); ! ! }else{ ! throw new RuntimeException("Expected interpreter manager to be python or jython related."); ! } ! process = SimpleRunner.createProcess(commandLine, env, null); ! PydevSpawnedInterpreterProcess spawnedInterpreterProcess = ! new PydevSpawnedInterpreterProcess(process, launch); ! ! launch.addProcess(spawnedInterpreterProcess); ! ! return new Tuple3<Launch, Process, Integer>(launch, process, clientPort); ! } } return null; --- 76,119 ---- ChooseProcessTypeDialog dialog = new ChooseProcessTypeDialog(getShell(), edit); if(dialog.open() == ChooseProcessTypeDialog.OK){ ! ! Collection<String> pythonpath = dialog.getPythonpath(); ! IInterpreterManager interpreterManager = dialog.getInterpreterManager(); ! ! if(pythonpath != null && interpreterManager != null){ ! naturesUsed = dialog.getNatures(); ! int port = SocketUtil.findUnusedLocalPort(); ! int clientPort = SocketUtil.findUnusedLocalPort(); ! ! final Launch launch = new Launch(null, "interactive", null); ! launch.setAttribute(DebugPlugin.ATTR_CAPTURE_OUTPUT, "false"); ! launch.setAttribute(INTERACTIVE_LAUNCH_PORT, ""+port); ! ! String pythonpathEnv = SimpleRunner.makePythonPathEnvFromPaths(pythonpath); ! String[] env = SimpleRunner.createEnvWithPythonpath(pythonpathEnv); ! ! File scriptWithinPySrc = PydevPlugin.getScriptWithinPySrc("pydevconsole.py"); ! String[] commandLine; ! if(interpreterManager.isPython()){ ! commandLine = SimplePythonRunner.makeExecutableCommandStr(scriptWithinPySrc.getAbsolutePath(), ! new String[]{String.valueOf(port), String.valueOf(clientPort)}); ! ! }else if(interpreterManager.isJython()){ ! String vmArgs = PydevDebugPlugin.getDefault().getPreferenceStore(). ! getString(PydevConsoleConstants.INTERACTIVE_CONSOLE_VM_ARGS); ! ! commandLine = SimpleJythonRunner.makeExecutableCommandStrWithVMArgs(scriptWithinPySrc.getAbsolutePath(), ! pythonpathEnv, vmArgs, new String[]{String.valueOf(port), String.valueOf(clientPort)}); ! ! }else{ ! throw new RuntimeException("Expected interpreter manager to be python or jython related."); ! } ! process = SimpleRunner.createProcess(commandLine, env, null); ! PydevSpawnedInterpreterProcess spawnedInterpreterProcess = ! new PydevSpawnedInterpreterProcess(process, launch); ! ! launch.addProcess(spawnedInterpreterProcess); ! ! return new Tuple3<Launch, Process, Integer>(launch, process, clientPort); ! } } return null; Index: PydevSpawnedInterpreterProcess.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.debug/src_console/org/python/pydev/debug/newconsole/env/PydevSpawnedInterpreterProcess.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** PydevSpawnedInterpreterProcess.java 31 Mar 2008 01:50:12 -0000 1.3 --- PydevSpawnedInterpreterProcess.java 27 Sep 2008 19:59:06 -0000 1.4 *************** *** 21,33 **** private boolean terminated; ! private Process spawnedInterpreterProcess; ! private ILaunch launch; private HashMap<String, String> attributes; public PydevSpawnedInterpreterProcess(Process spawnedInterpreterProcess, ILaunch launch){ ! this.spawnedInterpreterProcess = spawnedInterpreterProcess; ! this.launch = launch; ! this.attributes = new HashMap<String, String>(); ! this.setAttribute(IProcess.ATTR_PROCESS_TYPE, Constants.PROCESS_TYPE); } --- 21,33 ---- private boolean terminated; ! private Process spawnedInterpreterProcess; ! private ILaunch launch; private HashMap<String, String> attributes; public PydevSpawnedInterpreterProcess(Process spawnedInterpreterProcess, ILaunch launch){ ! this.spawnedInterpreterProcess = spawnedInterpreterProcess; ! this.launch = launch; ! this.attributes = new HashMap<String, String>(); ! this.setAttribute(IProcess.ATTR_PROCESS_TYPE, Constants.PROCESS_TYPE); } *************** *** 44,48 **** public ILaunch getLaunch() { ! return this.launch; } --- 44,48 ---- public ILaunch getLaunch() { ! return this.launch; } *************** *** 76,87 **** public void terminate() throws DebugException { ! try { ! if(this.spawnedInterpreterProcess != null){ ! this.spawnedInterpreterProcess.destroy(); ! } ! } catch (RuntimeException e) { ! PydevPlugin.log(e); ! } ! this.spawnedInterpreterProcess = null; terminated = true; } --- 76,87 ---- public void terminate() throws DebugException { ! try { ! if(this.spawnedInterpreterProcess != null){ ! this.spawnedInterpreterProcess.destroy(); ! } ! } catch (RuntimeException e) { ! PydevPlugin.log(e); ! } ! this.spawnedInterpreterProcess = null; terminated = true; } |
From: Fabio Z. <fa...@us...> - 2008-09-27 20:01:41
|
Update of /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/ast/visitors/context In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv21605/src/org/python/pydev/refactoring/ast/visitors/context Modified Files: PropertyVisitor.java AbstractContextVisitor.java ScopeAssignedVisitor.java LocalAttributeVisitor.java GlobalFunctionDefVisitor.java ScopeVariablesVisitor.java GlobalAttributeVisitor.java LocalFunctionDefVisitor.java ClassDefVisitor.java Log Message: Synching to latest changes: Pydev <ul> <li><strong>Editor</strong>: Cursor settings no longer overridden</li> <li><strong>Code-completion</strong>: If __all__ is defined with runtime elements (and not only in a single assign statement), it's ignored for code-completion purposes</li> <li><strong>Debugger</strong>: Pythonpath the same in debug and regular modes (sys.path[0] is the same directory as the file run)</li> <li><strong>Debugger</strong>: Persist choices done in the debugger when files from the debugger are not found</li> <li><strong>Interpreter config</strong>: "email" automatically added to the "forced builtins"</li> <li><strong>Parser</strong>: Correctly recognizing absolute import with 3 or more levels</li> <li><strong>Syntax check</strong>: Option to do only on active editor</li> </ul> Also: tabs changed for spaces Index: AbstractContextVisitor.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/ast/visitors/context/AbstractContextVisitor.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** AbstractContextVisitor.java 20 Oct 2007 19:30:59 -0000 1.5 --- AbstractContextVisitor.java 27 Sep 2008 20:00:47 -0000 1.6 *************** *** 28,196 **** public abstract class AbstractContextVisitor<T> extends VisitorBase { ! protected NodeHelper nodeHelper; ! protected List<T> nodes; ! protected final FastStack<AbstractScopeNode<?>> parents; ! protected final FastStack<SimpleNode> stack; ! protected ModuleAdapter moduleAdapter; ! public AbstractContextVisitor(ModuleAdapter module, AbstractNodeAdapter<? extends SimpleNode> parent) { ! super(); ! assert(module != null); ! this.moduleAdapter = module; ! nodeHelper = new NodeHelper(module.getEndLineDelimiter()); ! stack = new FastStack<SimpleNode>(); ! parents = new FastStack<AbstractScopeNode<?>>(); ! parents.push(moduleAdapter); ! stack.push(module.getASTNode()); ! nodes = new ArrayList<T>(); ! } ! private void add(T node) { ! nodes.add(node); ! } ! protected void after() { ! stack.pop(); ! } ! protected AbstractNodeAdapter<? extends SimpleNode> before(SimpleNode node) { ! AbstractNodeAdapter<? extends SimpleNode> context = createContext(node); ! stack.push(node); ! return context; ! } ! private AbstractNodeAdapter<? extends SimpleNode> create(SimpleNode node) { ! AbstractScopeNode<?> parent = parents.peek(); ! if (nodeHelper.isClassDef(node)) { ! return new ClassDefAdapter(moduleAdapter, parent, (ClassDef) node, moduleAdapter.getEndLineDelimiter()); ! } else if (nodeHelper.isFunctionDef(node)) { ! return new FunctionDefAdapter(moduleAdapter, parent, (FunctionDef) node, moduleAdapter.getEndLineDelimiter()); ! } else ! return new SimpleAdapter(moduleAdapter, parent, node, moduleAdapter.getEndLineDelimiter()); ! } ! protected abstract T createAdapter(AbstractScopeNode<?> parent, SimpleNode node); ! protected AbstractNodeAdapter<? extends SimpleNode> createContext(SimpleNode node) { ! if (nodeHelper.isModule(node)) { ! assert (node == moduleAdapter.getASTNode()); ! return moduleAdapter; ! } ! return create(node); ! } ! public List<T> getAll() { ! return nodes; ! } ! protected boolean isInClassDef() { ! for (SimpleNode node : stack) { ! if (nodeHelper.isClassDef(node)) ! return true; ! } ! return false; ! } ! protected boolean isInFunctionDef() { ! for (SimpleNode node : stack) { ! if (nodeHelper.isFunctionDef(node)) ! return true; ! } ! return false; ! } ! protected boolean isParentClassDecl() { ! return nodeHelper.isClassDef(parents.peek().getASTNode()); ! } ! public Iterator<T> iterator() { ! return nodes.iterator(); ! } ! protected void registerInContext(SimpleNode node) { ! T context = createAdapter(parents.peek(), node); ! add(context); ! } ! protected void trackContext(SimpleNode node) throws Exception { ! AbstractNodeAdapter<? extends SimpleNode> context = before(node); ! pushParent(context); ! traverse(node); ! parents.pop(); ! after(); ! } ! protected void updateASTContext(SimpleNode node) throws Exception { ! before(node); ! traverse(node); ! after(); ! } ! public void traverse(FunctionDef node) throws Exception { ! visit(node.decs); ! visit(node.name); ! visit(node.args); ! visit(node.body); ! } ! @Override ! public void traverse(SimpleNode node) throws Exception { ! if (nodeHelper.isFunctionDef(node)) { ! traverse((FunctionDef) node); ! } else ! node.traverse(this); ! } ! @Override ! protected Object unhandled_node(SimpleNode node) throws Exception { ! return null; ! } ! public void visit(SimpleNode node) throws Exception { ! if (node == null) ! return; ! node.accept(this); ! } ! protected void visit(SimpleNode[] body) throws Exception { ! if (body == null) ! return; ! for (SimpleNode node : body) { ! visit(node); ! } ! } ! public Object visitClassDef(ClassDef node) throws Exception { ! trackContext(node); ! return null; ! } ! @Override ! public Object visitFunctionDef(FunctionDef node) throws Exception { ! AbstractNodeAdapter<? extends SimpleNode> context = before(node); ! pushParent(context); ! traverse(node); ! parents.pop(); ! after(); ! return null; ! } ! protected void pushParent(AbstractNodeAdapter<? extends SimpleNode> context) { ! if (context instanceof AbstractScopeNode<?>) { ! parents.push((AbstractScopeNode<?>) context); ! } ! } } --- 28,196 ---- public abstract class AbstractContextVisitor<T> extends VisitorBase { ! protected NodeHelper nodeHelper; ! protected List<T> nodes; ! protected final FastStack<AbstractScopeNode<?>> parents; ! protected final FastStack<SimpleNode> stack; ! protected ModuleAdapter moduleAdapter; ! public AbstractContextVisitor(ModuleAdapter module, AbstractNodeAdapter<? extends SimpleNode> parent) { ! super(); ! assert(module != null); ! this.moduleAdapter = module; ! nodeHelper = new NodeHelper(module.getEndLineDelimiter()); ! stack = new FastStack<SimpleNode>(); ! parents = new FastStack<AbstractScopeNode<?>>(); ! parents.push(moduleAdapter); ! stack.push(module.getASTNode()); ! nodes = new ArrayList<T>(); ! } ! private void add(T node) { ! nodes.add(node); ! } ! protected void after() { ! stack.pop(); ! } ! protected AbstractNodeAdapter<? extends SimpleNode> before(SimpleNode node) { ! AbstractNodeAdapter<? extends SimpleNode> context = createContext(node); ! stack.push(node); ! return context; ! } ! private AbstractNodeAdapter<? extends SimpleNode> create(SimpleNode node) { ! AbstractScopeNode<?> parent = parents.peek(); ! if (nodeHelper.isClassDef(node)) { ! return new ClassDefAdapter(moduleAdapter, parent, (ClassDef) node, moduleAdapter.getEndLineDelimiter()); ! } else if (nodeHelper.isFunctionDef(node)) { ! return new FunctionDefAdapter(moduleAdapter, parent, (FunctionDef) node, moduleAdapter.getEndLineDelimiter()); ! } else ! return new SimpleAdapter(moduleAdapter, parent, node, moduleAdapter.getEndLineDelimiter()); ! } ! protected abstract T createAdapter(AbstractScopeNode<?> parent, SimpleNode node); ! protected AbstractNodeAdapter<? extends SimpleNode> createContext(SimpleNode node) { ! if (nodeHelper.isModule(node)) { ! assert (node == moduleAdapter.getASTNode()); ! return moduleAdapter; ! } ! return create(node); ! } ! public List<T> getAll() { ! return nodes; ! } ! protected boolean isInClassDef() { ! for (SimpleNode node : stack) { ! if (nodeHelper.isClassDef(node)) ! return true; ! } ! return false; ! } ! protected boolean isInFunctionDef() { ! for (SimpleNode node : stack) { ! if (nodeHelper.isFunctionDef(node)) ! return true; ! } ! return false; ! } ! protected boolean isParentClassDecl() { ! return nodeHelper.isClassDef(parents.peek().getASTNode()); ! } ! public Iterator<T> iterator() { ! return nodes.iterator(); ! } ! protected void registerInContext(SimpleNode node) { ! T context = createAdapter(parents.peek(), node); ! add(context); ! } ! protected void trackContext(SimpleNode node) throws Exception { ! AbstractNodeAdapter<? extends SimpleNode> context = before(node); ! pushParent(context); ! traverse(node); ! parents.pop(); ! after(); ! } ! protected void updateASTContext(SimpleNode node) throws Exception { ! before(node); ! traverse(node); ! after(); ! } ! public void traverse(FunctionDef node) throws Exception { ! visit(node.decs); ! visit(node.name); ! visit(node.args); ! visit(node.body); ! } ! @Override ! public void traverse(SimpleNode node) throws Exception { ! if (nodeHelper.isFunctionDef(node)) { ! traverse((FunctionDef) node); ! } else ! node.traverse(this); ! } ! @Override ! protected Object unhandled_node(SimpleNode node) throws Exception { ! return null; ! } ! public void visit(SimpleNode node) throws Exception { ! if (node == null) ! return; ! node.accept(this); ! } ! protected void visit(SimpleNode[] body) throws Exception { ! if (body == null) ! return; ! for (SimpleNode node : body) { ! visit(node); ! } ! } ! public Object visitClassDef(ClassDef node) throws Exception { ! trackContext(node); ! return null; ! } ! @Override ! public Object visitFunctionDef(FunctionDef node) throws Exception { ! AbstractNodeAdapter<? extends SimpleNode> context = before(node); ! pushParent(context); ! traverse(node); ! parents.pop(); ! after(); ! return null; ! } ! protected void pushParent(AbstractNodeAdapter<? extends SimpleNode> context) { ! if (context instanceof AbstractScopeNode<?>) { ! parents.push((AbstractScopeNode<?>) context); ! } ! } } Index: ScopeAssignedVisitor.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/ast/visitors/context/ScopeAssignedVisitor.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** ScopeAssignedVisitor.java 20 Oct 2007 19:30:59 -0000 1.4 --- ScopeAssignedVisitor.java 27 Sep 2008 20:00:47 -0000 1.5 *************** *** 26,97 **** public class ScopeAssignedVisitor extends AbstractContextVisitor<SimpleAdapter> { ! private List<String> globalVars; ! public ScopeAssignedVisitor(ModuleAdapter module, AbstractScopeNode<?> parent) { ! super(module, parent); ! globalVars = new ArrayList<String>(); ! } ! @Override ! protected void registerInContext(SimpleNode node) { ! String varName = nodeHelper.getName(node); ! if (!(globalVars.contains(varName))) { ! globalVars.add(varName); ! super.registerInContext(node); ! } ! } ! @Override ! public Object visitImport(Import node) throws Exception { ! return null; ! } ! @Override ! public Object visitImportFrom(ImportFrom node) throws Exception { ! return null; ! } ! @Override ! public Object visitName(Name node) throws Exception { ! if (nodeHelper.isAssign(stack.peek())) ! registerInContext(node); ! return null; ! } ! @Override ! public Object visitAttribute(Attribute node) throws Exception { ! // ignore attribute (must) ! return null; ! } ! @Override ! public Object visitAssign(Assign node) throws Exception { ! before(node); ! visit(node.targets); ! after(); ! return null; ! } ! @Override ! public Object visitModule(Module node) throws Exception { ! visit(node.body); ! return null; ! } ! @Override ! public Object visitFunctionDef(FunctionDef node) throws Exception { ! return null; ! } ! @Override ! public Object visitClassDef(ClassDef node) throws Exception { ! return null; ! } ! @Override ! protected SimpleAdapter createAdapter(AbstractScopeNode<?> parent, SimpleNode node) { ! return new SimpleAdapter(moduleAdapter, parent, node, moduleAdapter.getEndLineDelimiter()); ! } } --- 26,97 ---- public class ScopeAssignedVisitor extends AbstractContextVisitor<SimpleAdapter> { ! private List<String> globalVars; ! public ScopeAssignedVisitor(ModuleAdapter module, AbstractScopeNode<?> parent) { ! super(module, parent); ! globalVars = new ArrayList<String>(); ! } ! @Override ! protected void registerInContext(SimpleNode node) { ! String varName = nodeHelper.getName(node); ! if (!(globalVars.contains(varName))) { ! globalVars.add(varName); ! super.registerInContext(node); ! } ! } ! @Override ! public Object visitImport(Import node) throws Exception { ! return null; ! } ! @Override ! public Object visitImportFrom(ImportFrom node) throws Exception { ! return null; ! } ! @Override ! public Object visitName(Name node) throws Exception { ! if (nodeHelper.isAssign(stack.peek())) ! registerInContext(node); ! return null; ! } ! @Override ! public Object visitAttribute(Attribute node) throws Exception { ! // ignore attribute (must) ! return null; ! } ! @Override ! public Object visitAssign(Assign node) throws Exception { ! before(node); ! visit(node.targets); ! after(); ! return null; ! } ! @Override ! public Object visitModule(Module node) throws Exception { ! visit(node.body); ! return null; ! } ! @Override ! public Object visitFunctionDef(FunctionDef node) throws Exception { ! return null; ! } ! @Override ! public Object visitClassDef(ClassDef node) throws Exception { ! return null; ! } ! @Override ! protected SimpleAdapter createAdapter(AbstractScopeNode<?> parent, SimpleNode node) { ! return new SimpleAdapter(moduleAdapter, parent, node, moduleAdapter.getEndLineDelimiter()); ! } } Index: LocalFunctionDefVisitor.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/ast/visitors/context/LocalFunctionDefVisitor.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** LocalFunctionDefVisitor.java 20 Oct 2007 19:30:59 -0000 1.3 --- LocalFunctionDefVisitor.java 27 Sep 2008 20:00:47 -0000 1.4 *************** *** 14,27 **** public class LocalFunctionDefVisitor extends GlobalFunctionDefVisitor { ! public LocalFunctionDefVisitor(ModuleAdapter module, AbstractScopeNode<?> parent) { ! super(module, parent); ! } ! @Override ! public void visit(SimpleNode node) throws Exception { ! if (nodeHelper.isClassDef(node)) { ! return; ! } ! super.visit(node); ! } } --- 14,27 ---- public class LocalFunctionDefVisitor extends GlobalFunctionDefVisitor { ! public LocalFunctionDefVisitor(ModuleAdapter module, AbstractScopeNode<?> parent) { ! super(module, parent); ! } ! @Override ! public void visit(SimpleNode node) throws Exception { ! if (nodeHelper.isClassDef(node)) { ! return; ! } ! super.visit(node); ! } } Index: ClassDefVisitor.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/ast/visitors/context/ClassDefVisitor.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** ClassDefVisitor.java 20 Oct 2007 19:30:59 -0000 1.5 --- ClassDefVisitor.java 27 Sep 2008 20:00:47 -0000 1.6 *************** *** 19,36 **** public class ClassDefVisitor extends AbstractContextVisitor<IClassDefAdapter> { ! public ClassDefVisitor(ModuleAdapter module, AbstractNodeAdapter<? extends SimpleNode> parent) { ! super(module, parent); ! } ! @Override ! protected IClassDefAdapter createAdapter(AbstractScopeNode<?> parent, SimpleNode node) { ! return new ClassDefAdapter(moduleAdapter, parent, (ClassDef) node, moduleAdapter.getEndLineDelimiter()); ! } ! @Override ! public Object visitClassDef(ClassDef node) throws Exception { ! registerInContext(node); ! return super.visitClassDef(node); ! } } --- 19,36 ---- public class ClassDefVisitor extends AbstractContextVisitor<IClassDefAdapter> { ! public ClassDefVisitor(ModuleAdapter module, AbstractNodeAdapter<? extends SimpleNode> parent) { ! super(module, parent); ! } ! @Override ! protected IClassDefAdapter createAdapter(AbstractScopeNode<?> parent, SimpleNode node) { ! return new ClassDefAdapter(moduleAdapter, parent, (ClassDef) node, moduleAdapter.getEndLineDelimiter()); ! } ! @Override ! public Object visitClassDef(ClassDef node) throws Exception { ! registerInContext(node); ! return super.visitClassDef(node); ! } } Index: GlobalFunctionDefVisitor.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/ast/visitors/context/GlobalFunctionDefVisitor.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** GlobalFunctionDefVisitor.java 20 Oct 2007 19:30:59 -0000 1.4 --- GlobalFunctionDefVisitor.java 27 Sep 2008 20:00:47 -0000 1.5 *************** *** 16,38 **** public class GlobalFunctionDefVisitor extends AbstractContextVisitor<FunctionDefAdapter> { ! public GlobalFunctionDefVisitor(ModuleAdapter module, AbstractScopeNode<?> parent) { ! super(module, parent); ! } ! @Override ! protected FunctionDefAdapter createAdapter(AbstractScopeNode<?> parent, SimpleNode node) { ! return new FunctionDefAdapter(moduleAdapter, parent, (FunctionDef) node, moduleAdapter.getEndLineDelimiter()); ! } ! @Override ! public void visit(SimpleNode node) throws Exception { ! super.visit(node); ! } ! @Override ! public Object visitFunctionDef(FunctionDef node) throws Exception { ! registerInContext(node); ! return super.visitFunctionDef(node); ! } } --- 16,38 ---- public class GlobalFunctionDefVisitor extends AbstractContextVisitor<FunctionDefAdapter> { ! public GlobalFunctionDefVisitor(ModuleAdapter module, AbstractScopeNode<?> parent) { ! super(module, parent); ! } ! @Override ! protected FunctionDefAdapter createAdapter(AbstractScopeNode<?> parent, SimpleNode node) { ! return new FunctionDefAdapter(moduleAdapter, parent, (FunctionDef) node, moduleAdapter.getEndLineDelimiter()); ! } ! @Override ! public void visit(SimpleNode node) throws Exception { ! super.visit(node); ! } ! @Override ! public Object visitFunctionDef(FunctionDef node) throws Exception { ! registerInContext(node); ! return super.visitFunctionDef(node); ! } } Index: LocalAttributeVisitor.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/ast/visitors/context/LocalAttributeVisitor.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** LocalAttributeVisitor.java 20 Oct 2007 19:30:59 -0000 1.2 --- LocalAttributeVisitor.java 27 Sep 2008 20:00:47 -0000 1.3 *************** *** 15,42 **** public class LocalAttributeVisitor extends GlobalAttributeVisitor { ! private boolean inLocalScope; ! public LocalAttributeVisitor(ModuleAdapter module, AbstractScopeNode<?> parent) { ! super(module, parent); ! inLocalScope = false; ! } ! @Override ! public void traverse(SimpleNode node) throws Exception { ! if (nodeHelper.isClassDef(node)) { ! ClassDef classDef = (ClassDef) node; ! visit(classDef.body); ! } else ! super.traverse(node); ! } ! @Override ! public Object visitClassDef(ClassDef node) throws Exception { ! if (inLocalScope) ! return null; ! else { ! inLocalScope = true; ! return super.visitClassDef(node); ! } ! } } --- 15,42 ---- public class LocalAttributeVisitor extends GlobalAttributeVisitor { ! private boolean inLocalScope; ! public LocalAttributeVisitor(ModuleAdapter module, AbstractScopeNode<?> parent) { ! super(module, parent); ! inLocalScope = false; ! } ! @Override ! public void traverse(SimpleNode node) throws Exception { ! if (nodeHelper.isClassDef(node)) { ! ClassDef classDef = (ClassDef) node; ! visit(classDef.body); ! } else ! super.traverse(node); ! } ! @Override ! public Object visitClassDef(ClassDef node) throws Exception { ! if (inLocalScope) ! return null; ! else { ! inLocalScope = true; ! return super.visitClassDef(node); ! } ! } } Index: PropertyVisitor.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/ast/visitors/context/PropertyVisitor.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** PropertyVisitor.java 20 Oct 2007 19:30:59 -0000 1.4 --- PropertyVisitor.java 27 Sep 2008 20:00:47 -0000 1.5 *************** *** 21,68 **** public class PropertyVisitor extends AbstractContextVisitor<PropertyAdapter> { ! public PropertyVisitor(ModuleAdapter module, AbstractScopeNode<?> parent) { ! super(module, parent); ! } ! @Override ! protected PropertyAdapter createAdapter(AbstractScopeNode<?> parent, SimpleNode node) { ! return new PropertyAdapter(moduleAdapter, parent, node, moduleAdapter.getEndLineDelimiter()); ! } ! @Override ! public Object visitCall(Call node) throws Exception { ! if (nodeHelper.isAssign(stack.peek())) { ! registerInContext(stack.peek()); ! } ! return null; ! } ! @Override ! public Object visitAssign(Assign node) throws Exception { ! if (nodeHelper.isPropertyAssign(node)) { ! stack.push(node); ! visit(node.value); ! stack.pop(); ! } ! return null; ! } ! @Override ! public Object visitFunctionDef(FunctionDef node) throws Exception { ! return null; ! } ! /** ! * Traverse class body only ! */ ! @Override ! public Object visitClassDef(ClassDef node) throws Exception { ! AbstractNodeAdapter<? extends SimpleNode> context = before(node); ! pushParent(context); ! visit(node.body); ! parents.pop(); ! after(); ! return null; ! } } --- 21,68 ---- public class PropertyVisitor extends AbstractContextVisitor<PropertyAdapter> { ! public PropertyVisitor(ModuleAdapter module, AbstractScopeNode<?> parent) { ! super(module, parent); ! } ! @Override ! protected PropertyAdapter createAdapter(AbstractScopeNode<?> parent, SimpleNode node) { ! return new PropertyAdapter(moduleAdapter, parent, node, moduleAdapter.getEndLineDelimiter()); ! } ! @Override ! public Object visitCall(Call node) throws Exception { ! if (nodeHelper.isAssign(stack.peek())) { ! registerInContext(stack.peek()); ! } ! return null; ! } ! @Override ! public Object visitAssign(Assign node) throws Exception { ! if (nodeHelper.isPropertyAssign(node)) { ! stack.push(node); ! visit(node.value); ! stack.pop(); ! } ! return null; ! } ! @Override ! public Object visitFunctionDef(FunctionDef node) throws Exception { ! return null; ! } ! /** ! * Traverse class body only ! */ ! @Override ! public Object visitClassDef(ClassDef node) throws Exception { ! AbstractNodeAdapter<? extends SimpleNode> context = before(node); ! pushParent(context); ! visit(node.body); ! parents.pop(); ! after(); ! return null; ! } } Index: GlobalAttributeVisitor.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/ast/visitors/context/GlobalAttributeVisitor.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** GlobalAttributeVisitor.java 20 Oct 2007 19:30:59 -0000 1.4 --- GlobalAttributeVisitor.java 27 Sep 2008 20:00:47 -0000 1.5 *************** *** 30,170 **** public class GlobalAttributeVisitor extends AbstractContextVisitor<SimpleAdapter> { ! private SortedSet<String> uniqueAttributes; ! private FunctionDef lastFunctionDef; ! public GlobalAttributeVisitor(ModuleAdapter module, AbstractScopeNode<?> parent) { ! super(module, parent); ! uniqueAttributes = new TreeSet<String>(); ! } ! @Override ! protected void registerInContext(SimpleNode node) { ! addUniqueOnly(node); ! } ! private void addUniqueOnly(SimpleNode node) { ! if (!(uniqueAttributes.contains(getUniqueID(node)))) { ! uniqueAttributes.add(getUniqueID(node)); ! if (!(moduleAdapter.isImport(nodeHelper.getName(node)))) ! super.registerInContext(node); ! } ! } ! private String getUniqueID(SimpleNode node) { ! String parentName = nodeHelper.getName(parents.peek().getASTNode()); ! String nodeName = nodeHelper.getName(node); ! return parentName + nodeName; ! } ! protected boolean isInAttribute() { ! for (SimpleNode node : stack) { ! if (nodeHelper.isAttribute(node)) ! return true; ! } ! return false; ! } ! @Override ! public Object visitImport(Import node) throws Exception { ! return null; ! } ! @Override ! public Object visitImportFrom(ImportFrom node) throws Exception { ! return null; ! } ! @Override ! public Object visitName(Name node) throws Exception { ! if (nodeHelper.isSelf(node.id)) ! return null; ! if (isInClassDef()) { ! if (!isInFunctionDef()) { ! if (!(moduleAdapter.isGlobal(nodeHelper.getName(node)))) { ! registerInContext(node); ! } ! } else if (lastFunctionDef != null) { ! for (stmtType stmt : lastFunctionDef.body) { ! if (nodeHelper.isClassDef(stmt)) { ! if (stmt.equals(parents.peek().getASTNode())) { ! registerInContext(node); ! } ! } ! } ! } ! } ! return null; ! } ! @Override ! public Object visitNameTok(NameTok node) throws Exception { ! if (isParentClassDecl() && isInAttribute()) { ! if (nodeHelper.isAttribute(stack.peek())) { ! registerInContext(node); ! } ! } ! return super.visitNameTok(node); ! } ! @Override ! public Object visitAttribute(Attribute node) throws Exception { ! before(node); ! if (isParentClassDecl()) { ! if (nodeHelper.isName(node.value)) { ! SimpleNode parent = parents.peek().getASTNode(); ! if (nodeHelper.isFullyQualified(node.value, parent)) { ! if (nodeHelper.isNameTok(node.attr)) ! visit(node.attr); ! } ! } ! } ! after(); ! return null; ! } ! @Override ! public Object visitCall(Call node) throws Exception { ! // ignore name! ! visit(node.args); ! visit(node.keywords); ! visit(node.starargs); ! visit(node.kwargs); ! return null; ! } ! @Override ! public Object visitFunctionDef(FunctionDef node) throws Exception { ! lastFunctionDef = node; ! // Track by class only (avoid function tracking) ! updateASTContext(node); ! return null; ! } ! @Override ! public Object visitClassDef(ClassDef node) throws Exception { ! AbstractNodeAdapter<? extends SimpleNode> context = before(node); ! pushParent(context); ! visit(node.body); ! parents.pop(); ! after(); ! return null; ! } ! @Override ! public Object visitAssign(Assign node) throws Exception { ! if (nodeHelper.isPropertyAssign(node)) ! return null; ! before(node); ! visit(node.targets); ! after(); ! return null; ! } ! @Override ! protected SimpleAdapter createAdapter(AbstractScopeNode<?> parent, SimpleNode node) { ! return new SimpleAdapter(moduleAdapter, parent, node, moduleAdapter.getEndLineDelimiter()); ! } } --- 30,170 ---- public class GlobalAttributeVisitor extends AbstractContextVisitor<SimpleAdapter> { ! private SortedSet<String> uniqueAttributes; ! private FunctionDef lastFunctionDef; ! public GlobalAttributeVisitor(ModuleAdapter module, AbstractScopeNode<?> parent) { ! super(module, parent); ! uniqueAttributes = new TreeSet<String>(); ! } ! @Override ! protected void registerInContext(SimpleNode node) { ! addUniqueOnly(node); ! } ! private void addUniqueOnly(SimpleNode node) { ! if (!(uniqueAttributes.contains(getUniqueID(node)))) { ! uniqueAttributes.add(getUniqueID(node)); ! if (!(moduleAdapter.isImport(nodeHelper.getName(node)))) ! super.registerInContext(node); ! } ! } ! private String getUniqueID(SimpleNode node) { ! String parentName = nodeHelper.getName(parents.peek().getASTNode()); ! String nodeName = nodeHelper.getName(node); ! return parentName + nodeName; ! } ! protected boolean isInAttribute() { ! for (SimpleNode node : stack) { ! if (nodeHelper.isAttribute(node)) ! return true; ! } ! return false; ! } ! @Override ! public Object visitImport(Import node) throws Exception { ! return null; ! } ! @Override ! public Object visitImportFrom(ImportFrom node) throws Exception { ! return null; ! } ! @Override ! public Object visitName(Name node) throws Exception { ! if (nodeHelper.isSelf(node.id)) ! return null; ! if (isInClassDef()) { ! if (!isInFunctionDef()) { ! if (!(moduleAdapter.isGlobal(nodeHelper.getName(node)))) { ! registerInContext(node); ! } ! } else if (lastFunctionDef != null) { ! for (stmtType stmt : lastFunctionDef.body) { ! if (nodeHelper.isClassDef(stmt)) { ! if (stmt.equals(parents.peek().getASTNode())) { ! registerInContext(node); ! } ! } ! } ! } ! } ! return null; ! } ! @Override ! public Object visitNameTok(NameTok node) throws Exception { ! if (isParentClassDecl() && isInAttribute()) { ! if (nodeHelper.isAttribute(stack.peek())) { ! registerInContext(node); ! } ! } ! return super.visitNameTok(node); ! } ! @Override ! public Object visitAttribute(Attribute node) throws Exception { ! before(node); ! if (isParentClassDecl()) { ! if (nodeHelper.isName(node.value)) { ! SimpleNode parent = parents.peek().getASTNode(); ! if (nodeHelper.isFullyQualified(node.value, parent)) { ! if (nodeHelper.isNameTok(node.attr)) ! visit(node.attr); ! } ! } ! } ! after(); ! return null; ! } ! @Override ! public Object visitCall(Call node) throws Exception { ! // ignore name! ! visit(node.args); ! visit(node.keywords); ! visit(node.starargs); ! visit(node.kwargs); ! return null; ! } ! @Override ! public Object visitFunctionDef(FunctionDef node) throws Exception { ! lastFunctionDef = node; ! // Track by class only (avoid function tracking) ! updateASTContext(node); ! return null; ! } ! @Override ! public Object visitClassDef(ClassDef node) throws Exception { ! AbstractNodeAdapter<? extends SimpleNode> context = before(node); ! pushParent(context); ! visit(node.body); ! parents.pop(); ! after(); ! return null; ! } ! @Override ! public Object visitAssign(Assign node) throws Exception { ! if (nodeHelper.isPropertyAssign(node)) ! return null; ! before(node); ! visit(node.targets); ! after(); ! return null; ! } ! @Override ! protected SimpleAdapter createAdapter(AbstractScopeNode<?> parent, SimpleNode node) { ! return new SimpleAdapter(moduleAdapter, parent, node, moduleAdapter.getEndLineDelimiter()); ! } } Index: ScopeVariablesVisitor.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/ast/visitors/context/ScopeVariablesVisitor.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** ScopeVariablesVisitor.java 20 Oct 2007 19:30:59 -0000 1.4 --- ScopeVariablesVisitor.java 27 Sep 2008 20:00:47 -0000 1.5 *************** *** 22,90 **** public class ScopeVariablesVisitor extends AbstractContextVisitor<SimpleAdapter> { ! public ScopeVariablesVisitor(ModuleAdapter module, AbstractScopeNode<?> parent) { ! super(module, parent); ! } ! @Override ! public void visit(SimpleNode node) throws Exception { ! if (nodeHelper.isClassDef(node)) ! return; ! if (nodeHelper.isFunctionDef(node)) ! return; ! super.visit(node); ! } ! @Override ! public void traverse(SimpleNode node) throws Exception { ! if (nodeHelper.isClassDef(node)) ! return; ! if (nodeHelper.isFunctionDef(node)) ! return; ! super.traverse(node); ! } ! @Override ! public Object visitImport(Import node) throws Exception { ! return null; ! } ! @Override ! public Object visitImportFrom(ImportFrom node) throws Exception { ! return null; ! } ! @Override ! protected SimpleAdapter createAdapter(AbstractScopeNode<?> parent, SimpleNode node) { ! return new SimpleAdapter(this.moduleAdapter, parent, node, moduleAdapter.getEndLineDelimiter()); ! } ! @Override ! public Object visitAttribute(Attribute node) throws Exception { ! visit(node.value); // could be a local variable if not self ! return null; ! } ! @Override ! public Object visitClassDef(ClassDef node) throws Exception { ! visit(node.body); ! return null; ! } ! @Override ! public Object visitModule(Module node) throws Exception { ! visit(node.body); ! return null; ! } ! @Override ! public Object visitName(Name node) throws Exception { ! if (node.id.compareTo(NodeHelper.KEYWORD_SELF) == 0) ! return null; ! registerInContext(node); ! return null; ! } } --- 22,90 ---- public class ScopeVariablesVisitor extends AbstractContextVisitor<SimpleAdapter> { ! public ScopeVariablesVisitor(ModuleAdapter module, AbstractScopeNode<?> parent) { ! super(module, parent); ! } ! @Override ! public void visit(SimpleNode node) throws Exception { ! if (nodeHelper.isClassDef(node)) ! return; ! if (nodeHelper.isFunctionDef(node)) ! return; ! super.visit(node); ! } ! @Override ! public void traverse(SimpleNode node) throws Exception { ! if (nodeHelper.isClassDef(node)) ! return; ! if (nodeHelper.isFunctionDef(node)) ! return; ! super.traverse(node); ! } ! @Override ! public Object visitImport(Import node) throws Exception { ! return null; ! } ! @Override ! public Object visitImportFrom(ImportFrom node) throws Exception { ! return null; ! } ! @Override ! protected SimpleAdapter createAdapter(AbstractScopeNode<?> parent, SimpleNode node) { ! return new SimpleAdapter(this.moduleAdapter, parent, node, moduleAdapter.getEndLineDelimiter()); ! } ! @Override ! public Object visitAttribute(Attribute node) throws Exception { ! visit(node.value); // could be a local variable if not self ! return null; ! } ! @Override ! public Object visitClassDef(ClassDef node) throws Exception { ! visit(node.body); ! return null; ! } ! @Override ! public Object visitModule(Module node) throws Exception { ! visit(node.body); ! return null; ! } ! @Override ! public Object visitName(Name node) throws Exception { ! if (node.id.compareTo(NodeHelper.KEYWORD_SELF) == 0) ! return null; ! registerInContext(node); ! return null; ! } } |
From: Fabio Z. <fa...@us...> - 2008-09-27 20:01:40
|
Update of /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/core/edit In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv21605/src/org/python/pydev/refactoring/core/edit Modified Files: AbstractReplaceEdit.java AbstractTextEdit.java AbstractInsertEdit.java Log Message: Synching to latest changes: Pydev <ul> <li><strong>Editor</strong>: Cursor settings no longer overridden</li> <li><strong>Code-completion</strong>: If __all__ is defined with runtime elements (and not only in a single assign statement), it's ignored for code-completion purposes</li> <li><strong>Debugger</strong>: Pythonpath the same in debug and regular modes (sys.path[0] is the same directory as the file run)</li> <li><strong>Debugger</strong>: Persist choices done in the debugger when files from the debugger are not found</li> <li><strong>Interpreter config</strong>: "email" automatically added to the "forced builtins"</li> <li><strong>Parser</strong>: Correctly recognizing absolute import with 3 or more levels</li> <li><strong>Syntax check</strong>: Option to do only on active editor</li> </ul> Also: tabs changed for spaces Index: AbstractReplaceEdit.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/core/edit/AbstractReplaceEdit.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** AbstractReplaceEdit.java 20 Oct 2007 19:31:04 -0000 1.5 --- AbstractReplaceEdit.java 27 Sep 2008 20:00:51 -0000 1.6 *************** *** 15,33 **** public abstract class AbstractReplaceEdit extends AbstractTextEdit { ! public AbstractReplaceEdit(IRefactoringRequest req) { ! super(req); ! } ! @Override ! public TextEdit getEdit() { ! return new ReplaceEdit(getOffset(), getReplaceLength(), getFormatedNode()); ! } ! protected String getFormatedNode() { ! String source = RewriterVisitor.createSourceFromAST(getEditNode(), newLineDelim); ! return source.trim(); ! } ! protected abstract int getReplaceLength(); } --- 15,33 ---- public abstract class AbstractReplaceEdit extends AbstractTextEdit { ! public AbstractReplaceEdit(IRefactoringRequest req) { ! super(req); ! } ! @Override ! public TextEdit getEdit() { ! return new ReplaceEdit(getOffset(), getReplaceLength(), getFormatedNode()); ! } ! protected String getFormatedNode() { ! String source = RewriterVisitor.createSourceFromAST(getEditNode(), newLineDelim); ! return source.trim(); ! } ! protected abstract int getReplaceLength(); } Index: AbstractTextEdit.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/core/edit/AbstractTextEdit.java,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** AbstractTextEdit.java 14 Jun 2008 22:14:34 -0000 1.6 --- AbstractTextEdit.java 27 Sep 2008 20:00:51 -0000 1.7 *************** *** 20,93 **** public abstract class AbstractTextEdit { ! private final String WHITESPACE = " "; ! protected ModuleAdapter moduleAdapter; ! protected IASTNodeAdapter<? extends SimpleNode> offsetAdapter; ! protected NodeHelper nodeHelper; protected String newLineDelim; ! public AbstractTextEdit(IRefactoringRequest req) { ! String newLineDelim = req.getNewLineDelim(); ! this.moduleAdapter = req.getOffsetNode().getModule(); ! this.offsetAdapter = req.getOffsetNode(); ! this.nodeHelper = new NodeHelper(newLineDelim); ! this.newLineDelim = newLineDelim; ! } ! protected abstract SimpleNode getEditNode(); ! public abstract TextEdit getEdit(); ! protected String getFormatedNode() { ! SimpleNode node = getEditNode(); ! String source = RewriterVisitor.createSourceFromAST(node, newLineDelim); ! return getIndentedSource(node, source, getIndent()); ! } ! private String getIndentedSource(SimpleNode node, String source, int indent) { ! StringBuilder indented = new StringBuilder(); ! String indentation = getIndentation(indent); ! indented.append(newLineDelim + indentation); ! source = source.replaceAll(REPLACE_PATTERN(), newLineDelim + indentation); ! source = source.trim(); ! indented.append(source); ! indented.append(newLineDelim); ! if (nodeHelper.isFunctionDef(node)) ! indented.append(newLineDelim); ! return indented.toString(); ! } ! private String REPLACE_PATTERN() { ! return "\\r\\n|\\n|\\r"; ! } ! protected String getIndentation(int indent) { ! FastStringBuffer buf = new FastStringBuffer(); ! while (indent > 1) { ! buf.append(WHITESPACE); ! indent--; ! } ! return buf.toString(); ! } ! protected String getCapitalString(String name) { ! StringBuilder sb = new StringBuilder(name); ! sb.replace(0, 1, name.substring(0, 1).toUpperCase()); ! return sb.toString(); ! } ! public abstract int getOffsetStrategy(); ! public int getOffset() { ! return moduleAdapter.getOffset(offsetAdapter, getOffsetStrategy()); ! } ! public int getIndent() { ! return offsetAdapter.getNodeBodyIndent(); ! } } --- 20,93 ---- public abstract class AbstractTextEdit { ! private final String WHITESPACE = " "; ! protected ModuleAdapter moduleAdapter; ! protected IASTNodeAdapter<? extends SimpleNode> offsetAdapter; ! protected NodeHelper nodeHelper; protected String newLineDelim; ! public AbstractTextEdit(IRefactoringRequest req) { ! String newLineDelim = req.getNewLineDelim(); ! this.moduleAdapter = req.getOffsetNode().getModule(); ! this.offsetAdapter = req.getOffsetNode(); ! this.nodeHelper = new NodeHelper(newLineDelim); ! this.newLineDelim = newLineDelim; ! } ! protected abstract SimpleNode getEditNode(); ! public abstract TextEdit getEdit(); ! protected String getFormatedNode() { ! SimpleNode node = getEditNode(); ! String source = RewriterVisitor.createSourceFromAST(node, newLineDelim); ! return getIndentedSource(node, source, getIndent()); ! } ! private String getIndentedSource(SimpleNode node, String source, int indent) { ! StringBuilder indented = new StringBuilder(); ! String indentation = getIndentation(indent); ! indented.append(newLineDelim + indentation); ! source = source.replaceAll(REPLACE_PATTERN(), newLineDelim + indentation); ! source = source.trim(); ! indented.append(source); ! indented.append(newLineDelim); ! if (nodeHelper.isFunctionDef(node)) ! indented.append(newLineDelim); ! return indented.toString(); ! } ! private String REPLACE_PATTERN() { ! return "\\r\\n|\\n|\\r"; ! } ! protected String getIndentation(int indent) { ! FastStringBuffer buf = new FastStringBuffer(); ! while (indent > 1) { ! buf.append(WHITESPACE); ! indent--; ! } ! return buf.toString(); ! } ! protected String getCapitalString(String name) { ! StringBuilder sb = new StringBuilder(name); ! sb.replace(0, 1, name.substring(0, 1).toUpperCase()); ! return sb.toString(); ! } ! public abstract int getOffsetStrategy(); ! public int getOffset() { ! return moduleAdapter.getOffset(offsetAdapter, getOffsetStrategy()); ! } ! public int getIndent() { ! return offsetAdapter.getNodeBodyIndent(); ! } } Index: AbstractInsertEdit.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/src/org/python/pydev/refactoring/core/edit/AbstractInsertEdit.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** AbstractInsertEdit.java 20 Oct 2007 19:31:04 -0000 1.2 --- AbstractInsertEdit.java 27 Sep 2008 20:00:51 -0000 1.3 *************** *** 14,25 **** public abstract class AbstractInsertEdit extends AbstractTextEdit { ! public AbstractInsertEdit(IRefactoringRequest req) { ! super(req); ! } ! @Override ! public TextEdit getEdit() { ! return new InsertEdit(getOffset(), getFormatedNode()); ! } } --- 14,25 ---- public abstract class AbstractInsertEdit extends AbstractTextEdit { ! public AbstractInsertEdit(IRefactoringRequest req) { ! super(req); ! } ! @Override ! public TextEdit getEdit() { ! return new InsertEdit(getOffset(), getFormatedNode()); ! } } |
Update of /cvsroot/pydev/org.python.pydev.refactoring/tests/org/python/pydev/refactoring/tests/adapter In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv21605/tests/org/python/pydev/refactoring/tests/adapter Modified Files: CodeCompletionASTManagerStub.java AllTests.java FunctionDefAdapterTestSuite.java FunctionDefAdapterTestCase.java ClassDefAdapterTestSuite.java ClassDefAdapterTestCase.java ModuleAdapterTestConfig.java HierarchyTestCase.java ModuleAdapterTestSuite.java PythonNatureStub.java ModuleAdapterTestCase.java Log Message: Synching to latest changes: Pydev <ul> <li><strong>Editor</strong>: Cursor settings no longer overridden</li> <li><strong>Code-completion</strong>: If __all__ is defined with runtime elements (and not only in a single assign statement), it's ignored for code-completion purposes</li> <li><strong>Debugger</strong>: Pythonpath the same in debug and regular modes (sys.path[0] is the same directory as the file run)</li> <li><strong>Debugger</strong>: Persist choices done in the debugger when files from the debugger are not found</li> <li><strong>Interpreter config</strong>: "email" automatically added to the "forced builtins"</li> <li><strong>Parser</strong>: Correctly recognizing absolute import with 3 or more levels</li> <li><strong>Syntax check</strong>: Option to do only on active editor</li> </ul> Also: tabs changed for spaces Index: ClassDefAdapterTestSuite.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/tests/org/python/pydev/refactoring/tests/adapter/ClassDefAdapterTestSuite.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** ClassDefAdapterTestSuite.java 20 Oct 2007 19:31:00 -0000 1.4 --- ClassDefAdapterTestSuite.java 27 Sep 2008 20:00:48 -0000 1.5 *************** *** 14,30 **** public class ClassDefAdapterTestSuite extends AbstractIOTestSuite { ! public static Test suite() { ! TESTDIR = "tests" + File.separator + "python" + File.separator + "adapter" + File.separator + "classdef"; ! ClassDefAdapterTestSuite testSuite = new ClassDefAdapterTestSuite(); ! testSuite.createTests(); testSuite.addTest(new HierarchyTestCase("testHierarchyWithBuiltins")); ! return testSuite; ! } ! @Override ! protected IInputOutputTestCase createTestCase(String testCaseName) { ! return new ClassDefAdapterTestCase(testCaseName); ! } } --- 14,30 ---- public class ClassDefAdapterTestSuite extends AbstractIOTestSuite { ! public static Test suite() { ! TESTDIR = "tests" + File.separator + "python" + File.separator + "adapter" + File.separator + "classdef"; ! ClassDefAdapterTestSuite testSuite = new ClassDefAdapterTestSuite(); ! testSuite.createTests(); testSuite.addTest(new HierarchyTestCase("testHierarchyWithBuiltins")); ! return testSuite; ! } ! @Override ! protected IInputOutputTestCase createTestCase(String testCaseName) { ! return new ClassDefAdapterTestCase(testCaseName); ! } } Index: HierarchyTestCase.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/tests/org/python/pydev/refactoring/tests/adapter/HierarchyTestCase.java,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** HierarchyTestCase.java 5 Feb 2008 13:07:01 -0000 1.7 --- HierarchyTestCase.java 27 Sep 2008 20:00:48 -0000 1.8 *************** *** 71,76 **** HashSet<String> actual = new HashSet<String>(); for (IClassDefAdapter adapter : baseClasses) { ! actual.add(adapter.getName()); ! } HashSet<String> expected = new HashSet<String>(); expected.add("MyList2"); --- 71,76 ---- HashSet<String> actual = new HashSet<String>(); for (IClassDefAdapter adapter : baseClasses) { ! actual.add(adapter.getName()); ! } HashSet<String> expected = new HashSet<String>(); expected.add("MyList2"); *************** *** 78,82 **** expected.add("MyListBase"); ! assertEquals(expected, actual); } --- 78,82 ---- expected.add("MyListBase"); ! assertEquals(expected, actual); } Index: CodeCompletionASTManagerStub.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/tests/org/python/pydev/refactoring/tests/adapter/CodeCompletionASTManagerStub.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** CodeCompletionASTManagerStub.java 31 Jul 2008 01:48:12 -0000 1.4 --- CodeCompletionASTManagerStub.java 27 Sep 2008 20:00:48 -0000 1.5 *************** *** 26,153 **** public class CodeCompletionASTManagerStub implements ICodeCompletionASTManager { ! public void changePythonPath(String pythonpath, IProject project, ! IProgressMonitor monitor, String defaultSelectedInterpreter) { ! throw new RuntimeException("Not implemented"); ! } ! public Tuple3<IModule, String, IToken> findOnImportedMods( ! ICompletionState state, IModule current) ! throws CompletionRecursionException { ! throw new RuntimeException("Not implemented"); ! } ! public Tuple3<IModule, String, IToken> findOnImportedMods( ! IToken[] importedModules, ICompletionState state, ! String currentModuleName) throws CompletionRecursionException { ! throw new RuntimeException("Not implemented"); ! } ! public IToken[] findTokensOnImportedMods(IToken[] importedModules, ! ICompletionState state, IModule current) ! throws CompletionRecursionException { ! throw new RuntimeException("Not implemented"); ! } ! public List<IToken> getBuiltinCompletions(ICompletionState state, ! List<IToken> completions) { ! throw new RuntimeException("Not implemented"); ! } ! public IToken[] getCompletionsForImport(ImportInfo original, ! ICompletionRequest request) throws CompletionRecursionException { ! throw new RuntimeException("Not implemented"); ! } ! public IToken[] getCompletionsForModule(IModule module, ! ICompletionState state) throws CompletionRecursionException { ! return new IToken[] { ! new SourceToken(new Name("True", Name.Store), "True", "", "", ! "__builtin__"), ! new SourceToken(new Name("False", Name.Store), "False", "", "", ! "__builtin__"), }; ! } ! public IToken[] getCompletionsForModule(IModule module, ! ICompletionState state, boolean searchSameLevelMods) ! throws CompletionRecursionException { ! throw new RuntimeException("Not implemented"); ! } ! public IToken[] getCompletionsForModule(IModule module, ! ICompletionState state, boolean searchSameLevelMods, ! boolean lookForArgumentCompletion) ! throws CompletionRecursionException { ! throw new RuntimeException("Not implemented"); ! } ! public IToken[] getCompletionsForToken(File file, IDocument doc, ! ICompletionState state) throws CompletionRecursionException { ! throw new RuntimeException("Not implemented"); ! } ! public IToken[] getCompletionsForToken(IDocument doc, ICompletionState state) ! throws CompletionRecursionException { ! throw new RuntimeException("Not implemented"); ! } ! public List<IToken> getCompletionsForWildImport(ICompletionState state, ! IModule current, List<IToken> completions, IToken wildImport) { ! throw new RuntimeException("Not implemented"); ! } ! public List<IToken> getGlobalCompletions(IToken[] globalTokens, ! IToken[] importedModules, IToken[] wildImportedModules, ! ICompletionState state, IModule current) { ! throw new RuntimeException("Not implemented"); ! } ! public IModule getModule(String name, IPythonNature nature, ! boolean dontSearchInit, boolean lookingForRelative) { ! throw new RuntimeException("Not implemented"); ! } ! public IModule getModule(String name, IPythonNature nature, ! boolean dontSearchInit) { ! throw new RuntimeException("Not implemented"); ! } ! public IModulesManager getModulesManager() { ! throw new RuntimeException("Not implemented"); ! } ! public IPythonNature getNature() { ! throw new RuntimeException("Not implemented"); ! } ! public IToken getRepInModule(IModule module, String tokName, ! IPythonNature nature) throws CompletionRecursionException { ! throw new RuntimeException("Not implemented"); ! } ! public void rebuildModule(File file, IDocument doc, IProject project, ! IProgressMonitor monitor, IPythonNature nature) { ! throw new RuntimeException("Not implemented"); ! } ! public void removeModule(File file, IProject project, ! IProgressMonitor monitor) { ! throw new RuntimeException("Not implemented"); ! } ! public IToken resolveImport(ICompletionState state, IToken imported) ! throws CompletionRecursionException { ! throw new RuntimeException("Not implemented"); ! } ! public void setProject(IProject project, IPythonNature nature, boolean restoreDeltas) { ! throw new RuntimeException("Not implemented"); ! } ! public void getCompletionsForClassInLocalScope(IModule module, ! ICompletionState state, boolean searchSameLevelMods, ! boolean lookForArgumentCompletion, List<String> lookForClass, ! HashSet<IToken> hashSet) throws CompletionRecursionException { ! throw new RuntimeException("Not implemented"); ! } } --- 26,153 ---- public class CodeCompletionASTManagerStub implements ICodeCompletionASTManager { ! public void changePythonPath(String pythonpath, IProject project, ! IProgressMonitor monitor, String defaultSelectedInterpreter) { ! throw new RuntimeException("Not implemented"); ! } ! public Tuple3<IModule, String, IToken> findOnImportedMods( ! ICompletionState state, IModule current) ! throws CompletionRecursionException { ! throw new RuntimeException("Not implemented"); ! } ! public Tuple3<IModule, String, IToken> findOnImportedMods( ! IToken[] importedModules, ICompletionState state, ! String currentModuleName) throws CompletionRecursionException { ! throw new RuntimeException("Not implemented"); ! } ! public IToken[] findTokensOnImportedMods(IToken[] importedModules, ! ICompletionState state, IModule current) ! throws CompletionRecursionException { ! throw new RuntimeException("Not implemented"); ! } ! public List<IToken> getBuiltinCompletions(ICompletionState state, ! List<IToken> completions) { ! throw new RuntimeException("Not implemented"); ! } ! public IToken[] getCompletionsForImport(ImportInfo original, ! ICompletionRequest request) throws CompletionRecursionException { ! throw new RuntimeException("Not implemented"); ! } ! public IToken[] getCompletionsForModule(IModule module, ! ICompletionState state) throws CompletionRecursionException { ! return new IToken[] { ! new SourceToken(new Name("True", Name.Store), "True", "", "", ! "__builtin__"), ! new SourceToken(new Name("False", Name.Store), "False", "", "", ! "__builtin__"), }; ! } ! public IToken[] getCompletionsForModule(IModule module, ! ICompletionState state, boolean searchSameLevelMods) ! throws CompletionRecursionException { ! throw new RuntimeException("Not implemented"); ! } ! public IToken[] getCompletionsForModule(IModule module, ! ICompletionState state, boolean searchSameLevelMods, ! boolean lookForArgumentCompletion) ! throws CompletionRecursionException { ! throw new RuntimeException("Not implemented"); ! } ! public IToken[] getCompletionsForToken(File file, IDocument doc, ! ICompletionState state) throws CompletionRecursionException { ! throw new RuntimeException("Not implemented"); ! } ! public IToken[] getCompletionsForToken(IDocument doc, ICompletionState state) ! throws CompletionRecursionException { ! throw new RuntimeException("Not implemented"); ! } ! public boolean getCompletionsForWildImport(ICompletionState state, ! IModule current, List<IToken> completions, IToken wildImport) { ! throw new RuntimeException("Not implemented"); ! } ! public List<IToken> getGlobalCompletions(IToken[] globalTokens, ! IToken[] importedModules, IToken[] wildImportedModules, ! ICompletionState state, IModule current) { ! throw new RuntimeException("Not implemented"); ! } ! public IModule getModule(String name, IPythonNature nature, ! boolean dontSearchInit, boolean lookingForRelative) { ! throw new RuntimeException("Not implemented"); ! } ! public IModule getModule(String name, IPythonNature nature, ! boolean dontSearchInit) { ! throw new RuntimeException("Not implemented"); ! } ! public IModulesManager getModulesManager() { ! throw new RuntimeException("Not implemented"); ! } ! public IPythonNature getNature() { ! throw new RuntimeException("Not implemented"); ! } ! public IToken getRepInModule(IModule module, String tokName, ! IPythonNature nature) throws CompletionRecursionException { ! throw new RuntimeException("Not implemented"); ! } ! public void rebuildModule(File file, IDocument doc, IProject project, ! IProgressMonitor monitor, IPythonNature nature) { ! throw new RuntimeException("Not implemented"); ! } ! public void removeModule(File file, IProject project, ! IProgressMonitor monitor) { ! throw new RuntimeException("Not implemented"); ! } ! public IToken resolveImport(ICompletionState state, IToken imported) ! throws CompletionRecursionException { ! throw new RuntimeException("Not implemented"); ! } ! public void setProject(IProject project, IPythonNature nature, boolean restoreDeltas) { ! throw new RuntimeException("Not implemented"); ! } ! public void getCompletionsForClassInLocalScope(IModule module, ! ICompletionState state, boolean searchSameLevelMods, ! boolean lookForArgumentCompletion, List<String> lookForClass, ! HashSet<IToken> hashSet) throws CompletionRecursionException { ! throw new RuntimeException("Not implemented"); ! } } Index: ModuleAdapterTestConfig.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/tests/org/python/pydev/refactoring/tests/adapter/ModuleAdapterTestConfig.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** ModuleAdapterTestConfig.java 20 Oct 2007 19:31:00 -0000 1.2 --- ModuleAdapterTestConfig.java 27 Sep 2008 20:00:48 -0000 1.3 *************** *** 10,14 **** public class ModuleAdapterTestConfig { ! List<String> resolveNames = new ArrayList<String>(); } --- 10,14 ---- public class ModuleAdapterTestConfig { ! List<String> resolveNames = new ArrayList<String>(); } Index: FunctionDefAdapterTestSuite.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/tests/org/python/pydev/refactoring/tests/adapter/FunctionDefAdapterTestSuite.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** FunctionDefAdapterTestSuite.java 20 Oct 2007 19:31:00 -0000 1.3 --- FunctionDefAdapterTestSuite.java 27 Sep 2008 20:00:48 -0000 1.4 *************** *** 14,29 **** public class FunctionDefAdapterTestSuite extends AbstractIOTestSuite { ! public static Test suite() { ! TESTDIR = "tests" + File.separator + "python" + File.separator + "adapter" + File.separator + "functiondef"; ! FunctionDefAdapterTestSuite testSuite = new FunctionDefAdapterTestSuite(); ! testSuite.createTests(); ! return testSuite; ! } ! @Override ! protected IInputOutputTestCase createTestCase(String testCaseName) { ! return new FunctionDefAdapterTestCase(testCaseName); ! } } --- 14,29 ---- public class FunctionDefAdapterTestSuite extends AbstractIOTestSuite { ! public static Test suite() { ! TESTDIR = "tests" + File.separator + "python" + File.separator + "adapter" + File.separator + "functiondef"; ! FunctionDefAdapterTestSuite testSuite = new FunctionDefAdapterTestSuite(); ! testSuite.createTests(); ! return testSuite; ! } ! @Override ! protected IInputOutputTestCase createTestCase(String testCaseName) { ! return new FunctionDefAdapterTestCase(testCaseName); ! } } Index: ModuleAdapterTestSuite.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/tests/org/python/pydev/refactoring/tests/adapter/ModuleAdapterTestSuite.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** ModuleAdapterTestSuite.java 20 Oct 2007 19:31:00 -0000 1.3 --- ModuleAdapterTestSuite.java 27 Sep 2008 20:00:48 -0000 1.4 *************** *** 14,29 **** public class ModuleAdapterTestSuite extends AbstractIOTestSuite { ! public static Test suite() { ! TESTDIR = "tests" + File.separator + "python" + File.separator + "adapter" + File.separator + "module"; ! ModuleAdapterTestSuite testSuite = new ModuleAdapterTestSuite(); ! testSuite.createTests(); ! return testSuite; ! } ! @Override ! protected IInputOutputTestCase createTestCase(String testCaseName) { ! return new ModuleAdapterTestCase(testCaseName); ! } } --- 14,29 ---- public class ModuleAdapterTestSuite extends AbstractIOTestSuite { ! public static Test suite() { ! TESTDIR = "tests" + File.separator + "python" + File.separator + "adapter" + File.separator + "module"; ! ModuleAdapterTestSuite testSuite = new ModuleAdapterTestSuite(); ! testSuite.createTests(); ! return testSuite; ! } ! @Override ! protected IInputOutputTestCase createTestCase(String testCaseName) { ! return new ModuleAdapterTestCase(testCaseName); ! } } Index: FunctionDefAdapterTestCase.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/tests/org/python/pydev/refactoring/tests/adapter/FunctionDefAdapterTestCase.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** FunctionDefAdapterTestCase.java 20 Oct 2007 19:31:00 -0000 1.5 --- FunctionDefAdapterTestCase.java 27 Sep 2008 20:00:48 -0000 1.6 *************** *** 16,56 **** public class FunctionDefAdapterTestCase extends AbstractIOTestCase { ! public FunctionDefAdapterTestCase(String name) { ! super(name); ! } ! @Override ! public void runTest() throws Throwable { ! StringBuffer buffer = new StringBuffer(); ! ModuleAdapter module = VisitorFactory.createModuleAdapter(null, null, new Document(getSource()), new PythonNatureStub()); ! List<IClassDefAdapter> classes = module.getClasses(); ! assertTrue(classes.size() > 0); ! buffer.append("# ClassName FunctionName hasArg hasVarArg hasKwArg ArgumentsOnly\n"); ! for (IClassDefAdapter adapter : module.getClasses()) { ! printFunction(buffer, adapter); ! } ! this.setTestGenerated(buffer.toString().trim()); ! assertEquals(getExpected(), getGenerated()); ! } ! private void printFunction(StringBuffer buffer, IClassDefAdapter adapter) { ! final String DOUBLETAB = " "; ! buffer.append("# " + adapter.getName() + "\n"); ! for (FunctionDefAdapter function : adapter.getFunctions()) { ! buffer.append("# "); ! buffer.append(function.getName() + DOUBLETAB + function.getArguments().hasArg() + DOUBLETAB ! + function.getArguments().hasVarArg() + DOUBLETAB + function.getArguments().hasKwArg() + DOUBLETAB ! + function.getArguments().getArgOnly()); ! buffer.append("\n"); ! } ! buffer.append("\n"); ! } ! @Override ! public String getExpected() { ! return getResult(); ! } } --- 16,56 ---- public class FunctionDefAdapterTestCase extends AbstractIOTestCase { ! public FunctionDefAdapterTestCase(String name) { ! super(name); ! } ! @Override ! public void runTest() throws Throwable { ! StringBuffer buffer = new StringBuffer(); ! ModuleAdapter module = VisitorFactory.createModuleAdapter(null, null, new Document(getSource()), new PythonNatureStub()); ! List<IClassDefAdapter> classes = module.getClasses(); ! assertTrue(classes.size() > 0); ! buffer.append("# ClassName FunctionName hasArg hasVarArg hasKwArg ArgumentsOnly\n"); ! for (IClassDefAdapter adapter : module.getClasses()) { ! printFunction(buffer, adapter); ! } ! this.setTestGenerated(buffer.toString().trim()); ! assertEquals(getExpected(), getGenerated()); ! } ! private void printFunction(StringBuffer buffer, IClassDefAdapter adapter) { ! final String DOUBLETAB = " "; ! buffer.append("# " + adapter.getName() + "\n"); ! for (FunctionDefAdapter function : adapter.getFunctions()) { ! buffer.append("# "); ! buffer.append(function.getName() + DOUBLETAB + function.getArguments().hasArg() + DOUBLETAB ! + function.getArguments().hasVarArg() + DOUBLETAB + function.getArguments().hasKwArg() + DOUBLETAB ! + function.getArguments().getArgOnly()); ! buffer.append("\n"); ! } ! buffer.append("\n"); ! } ! @Override ! public String getExpected() { ! return getResult(); ! } } Index: PythonNatureStub.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/tests/org/python/pydev/refactoring/tests/adapter/PythonNatureStub.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** PythonNatureStub.java 28 Feb 2008 01:44:42 -0000 1.4 --- PythonNatureStub.java 27 Sep 2008 20:00:48 -0000 1.5 *************** *** 20,138 **** public class PythonNatureStub implements IPythonNature{ ! public ICodeCompletionASTManager getAstManager() { ! return new CodeCompletionASTManagerStub(); ! } ! public IToken[] getBuiltinCompletions() { ! throw new RuntimeException("Not implemented"); ! } ! public IModule getBuiltinMod() { ! throw new RuntimeException("Not implemented"); ! } ! public File getCompletionsCacheDir() { ! throw new RuntimeException("Not implemented"); ! } ! public String getDefaultVersion() { ! throw new RuntimeException("Not implemented"); ! } ! public IPythonPathNature getPythonPathNature() { ! throw new RuntimeException("Not implemented"); ! } ! public int getRelatedId() throws CoreException { ! throw new RuntimeException("Not implemented"); ! } ! public IInterpreterManager getRelatedInterpreterManager() { ! throw new RuntimeException("Not implemented"); ! } ! public String getVersion() throws CoreException { ! throw new RuntimeException("Not implemented"); ! } ! public boolean isJython() throws CoreException { ! throw new RuntimeException("Not implemented"); ! } ! public boolean isPython() throws CoreException { ! throw new RuntimeException("Not implemented"); ! } ! public void rebuildPath() { ! throw new RuntimeException("Not implemented"); ! } ! public void rebuildPath(String defaultSelectedInterpreter, IProgressMonitor monitor) { ! throw new RuntimeException("Not implemented"); ! } ! public String resolveModule(File file) { ! throw new RuntimeException("Not implemented"); ! } ! public void saveAstManager() { ! throw new RuntimeException("Not implemented"); ! } ! public void setBuiltinCompletions(IToken[] toks) { ! throw new RuntimeException("Not implemented"); ! } ! public void setBuiltinMod(IModule mod) { ! throw new RuntimeException("Not implemented"); ! } ! public void setVersion(String version) throws CoreException { ! throw new RuntimeException("Not implemented"); ! } ! public void configure() throws CoreException { ! throw new RuntimeException("Not implemented"); ! } ! public void deconfigure() throws CoreException { ! throw new RuntimeException("Not implemented"); ! } ! public IProject getProject() { ! throw new RuntimeException("Not implemented"); ! } ! public void setProject(IProject project) { ! throw new RuntimeException("Not implemented"); ! } ! public int getGrammarVersion() { ! throw new RuntimeException("Not implemented"); ! } ! public void endRequests() { ! throw new RuntimeException("Not implemented"); ! } ! public boolean isResourceInPythonpath(IResource resource) { ! throw new RuntimeException("Not implemented"); ! } ! public boolean isResourceInPythonpath(String resource) { ! throw new RuntimeException("Not implemented"); ! } ! public String resolveModule(String fileAbsolutePath) { ! throw new RuntimeException("Not implemented"); ! } ! public String resolveModule(IResource resource) { ! throw new RuntimeException("Not implemented"); ! } ! public boolean startRequests() { ! throw new RuntimeException("Not implemented"); ! } } --- 20,138 ---- public class PythonNatureStub implements IPythonNature{ ! public ICodeCompletionASTManager getAstManager() { ! return new CodeCompletionASTManagerStub(); ! } ! public IToken[] getBuiltinCompletions() { ! throw new RuntimeException("Not implemented"); ! } ! public IModule getBuiltinMod() { ! throw new RuntimeException("Not implemented"); ! } ! public File getCompletionsCacheDir() { ! throw new RuntimeException("Not implemented"); ! } ! public String getDefaultVersion() { ! throw new RuntimeException("Not implemented"); ! } ! public IPythonPathNature getPythonPathNature() { ! throw new RuntimeException("Not implemented"); ! } ! public int getRelatedId() throws CoreException { ! throw new RuntimeException("Not implemented"); ! } ! public IInterpreterManager getRelatedInterpreterManager() { ! throw new RuntimeException("Not implemented"); ! } ! public String getVersion() throws CoreException { ! throw new RuntimeException("Not implemented"); ! } ! public boolean isJython() throws CoreException { ! throw new RuntimeException("Not implemented"); ! } ! public boolean isPython() throws CoreException { ! throw new RuntimeException("Not implemented"); ! } ! public void rebuildPath() { ! throw new RuntimeException("Not implemented"); ! } ! public void rebuildPath(String defaultSelectedInterpreter, IProgressMonitor monitor) { ! throw new RuntimeException("Not implemented"); ! } ! public String resolveModule(File file) { ! throw new RuntimeException("Not implemented"); ! } ! public void saveAstManager() { ! throw new RuntimeException("Not implemented"); ! } ! public void setBuiltinCompletions(IToken[] toks) { ! throw new RuntimeException("Not implemented"); ! } ! public void setBuiltinMod(IModule mod) { ! throw new RuntimeException("Not implemented"); ! } ! public void setVersion(String version) throws CoreException { ! throw new RuntimeException("Not implemented"); ! } ! public void configure() throws CoreException { ! throw new RuntimeException("Not implemented"); ! } ! public void deconfigure() throws CoreException { ! throw new RuntimeException("Not implemented"); ! } ! public IProject getProject() { ! throw new RuntimeException("Not implemented"); ! } ! public void setProject(IProject project) { ! throw new RuntimeException("Not implemented"); ! } ! public int getGrammarVersion() { ! throw new RuntimeException("Not implemented"); ! } ! public void endRequests() { ! throw new RuntimeException("Not implemented"); ! } ! public boolean isResourceInPythonpath(IResource resource) { ! throw new RuntimeException("Not implemented"); ! } ! public boolean isResourceInPythonpath(String resource) { ! throw new RuntimeException("Not implemented"); ! } ! public String resolveModule(String fileAbsolutePath) { ! throw new RuntimeException("Not implemented"); ! } ! public String resolveModule(IResource resource) { ! throw new RuntimeException("Not implemented"); ! } ! public boolean startRequests() { ! throw new RuntimeException("Not implemented"); ! } } Index: AllTests.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/tests/org/python/pydev/refactoring/tests/adapter/AllTests.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** AllTests.java 20 Oct 2007 19:31:00 -0000 1.3 --- AllTests.java 27 Sep 2008 20:00:48 -0000 1.4 *************** *** 10,22 **** public class AllTests { ! public static Test suite() { ! TestSuite suite = new TestSuite("Test for org.python.pydev.refactoring.tests.adapter"); ! // $JUnit-BEGIN$ ! suite.addTest(ClassDefAdapterTestSuite.suite()); ! suite.addTest(FunctionDefAdapterTestSuite.suite()); ! suite.addTest(ModuleAdapterTestSuite.suite()); ! // $JUnit-END$ ! return suite; ! } } --- 10,22 ---- public class AllTests { ! public static Test suite() { ! TestSuite suite = new TestSuite("Test for org.python.pydev.refactoring.tests.adapter"); ! // $JUnit-BEGIN$ ! suite.addTest(ClassDefAdapterTestSuite.suite()); ! suite.addTest(FunctionDefAdapterTestSuite.suite()); ! suite.addTest(ModuleAdapterTestSuite.suite()); ! // $JUnit-END$ ! return suite; ! } } Index: ClassDefAdapterTestCase.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/tests/org/python/pydev/refactoring/tests/adapter/ClassDefAdapterTestCase.java,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** ClassDefAdapterTestCase.java 5 Feb 2008 13:07:01 -0000 1.6 --- ClassDefAdapterTestCase.java 27 Sep 2008 20:00:48 -0000 1.7 *************** *** 16,80 **** public class ClassDefAdapterTestCase extends AbstractIOTestCase { ! private CompletionEnvironmentSetupHelper setupHelper; public ClassDefAdapterTestCase(String name) { ! super(name); ! } ! @Override ! public void runTest() throws Throwable { setupHelper = new CompletionEnvironmentSetupHelper(); setupHelper.setupEnv(); try{ ! StringBuffer buffer = new StringBuffer(); ! ModuleAdapter module = setupHelper.createModuleAdapter(this); ! List<IClassDefAdapter> classes = module.getClasses(); ! assertTrue(classes.size() > 0); ! for (IClassDefAdapter adapter : classes) { ! printBaseClass(buffer, adapter); ! ! //sort them as the order is not actually guaranteed! ! IClassDefAdapter[] baseClasses = adapter.getBaseClasses().toArray(new IClassDefAdapter[0]); ! Arrays.sort(baseClasses, new Comparator<IClassDefAdapter>(){ public int compare(IClassDefAdapter o1, IClassDefAdapter o2) { return o1.getName().compareTo(o2.getName()); }} ! ); ! for (IClassDefAdapter base : baseClasses) { ! buffer.append("## " + adapter.getName()); ! printBaseDefClass(buffer, base); ! } ! } ! this.setTestGenerated(buffer.toString().trim()); ! assertEquals(getExpected(), getGenerated()); }finally{ setupHelper.tearDownEnv(); } ! } ! private void printBaseDefClass(StringBuffer buffer, IClassDefAdapter base) { ! buffer.append(" Base: " + base.getName()); ! buffer.append("\n"); ! } ! private void printBaseClass(StringBuffer buffer, IClassDefAdapter adapter) { ! buffer.append("# " + adapter.getName()); ! for (String name : adapter.getBaseClassNames()) { ! buffer.append(" " + name); ! } ! buffer.append("\n"); ! } ! @Override ! public String getExpected() { ! return getResult(); ! } } --- 16,80 ---- public class ClassDefAdapterTestCase extends AbstractIOTestCase { ! private CompletionEnvironmentSetupHelper setupHelper; public ClassDefAdapterTestCase(String name) { ! super(name); ! } ! @Override ! public void runTest() throws Throwable { setupHelper = new CompletionEnvironmentSetupHelper(); setupHelper.setupEnv(); try{ ! StringBuffer buffer = new StringBuffer(); ! ModuleAdapter module = setupHelper.createModuleAdapter(this); ! List<IClassDefAdapter> classes = module.getClasses(); ! assertTrue(classes.size() > 0); ! for (IClassDefAdapter adapter : classes) { ! printBaseClass(buffer, adapter); ! ! //sort them as the order is not actually guaranteed! ! IClassDefAdapter[] baseClasses = adapter.getBaseClasses().toArray(new IClassDefAdapter[0]); ! Arrays.sort(baseClasses, new Comparator<IClassDefAdapter>(){ public int compare(IClassDefAdapter o1, IClassDefAdapter o2) { return o1.getName().compareTo(o2.getName()); }} ! ); ! for (IClassDefAdapter base : baseClasses) { ! buffer.append("## " + adapter.getName()); ! printBaseDefClass(buffer, base); ! } ! } ! this.setTestGenerated(buffer.toString().trim()); ! assertEquals(getExpected(), getGenerated()); }finally{ setupHelper.tearDownEnv(); } ! } ! private void printBaseDefClass(StringBuffer buffer, IClassDefAdapter base) { ! buffer.append(" Base: " + base.getName()); ! buffer.append("\n"); ! } ! private void printBaseClass(StringBuffer buffer, IClassDefAdapter adapter) { ! buffer.append("# " + adapter.getName()); ! for (String name : adapter.getBaseClassNames()) { ! buffer.append(" " + name); ! } ! buffer.append("\n"); ! } ! @Override ! public String getExpected() { ! return getResult(); ! } } Index: ModuleAdapterTestCase.java =================================================================== RCS file: /cvsroot/pydev/org.python.pydev.refactoring/tests/org/python/pydev/refactoring/tests/adapter/ModuleAdapterTestCase.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** ModuleAdapterTestCase.java 20 Oct 2007 19:31:00 -0000 1.4 --- ModuleAdapterTestCase.java 27 Sep 2008 20:00:48 -0000 1.5 *************** *** 15,63 **** public class ModuleAdapterTestCase extends AbstractIOTestCase { ! public ModuleAdapterTestCase(String name) { ! super(name); ! } ! @Override ! public void runTest() throws Throwable { ! StringBuffer buffer = new StringBuffer(); ! ModuleAdapterTestConfig config = null; ! XStream xstream = new XStream(); ! xstream.alias("config", ModuleAdapterTestConfig.class); ! ModuleAdapter module = VisitorFactory.createModuleAdapter(null, null, new Document(getSource()), new PythonNatureStub()); ! if (getConfig().length() > 0) { ! config = (ModuleAdapterTestConfig) xstream.fromXML(getConfig()); ! } else { ! fail("Could not unserialize configuration"); ! return; /* explicit return, fail should already abort */ ! } ! for (String identifier : config.resolveNames) { ! for (FQIdentifier id : module.resolveFullyQualified(identifier)) { ! buffer.append("# " + identifier + " -> " + id.getFQName()); ! buffer.append("\n"); ! } ! } ! buffer.append("# Imported regular modules (Alias, Realname)"); ! for (String aliasModule : module.getRegularImportedModules().keySet()) { ! buffer.append("\n# " + aliasModule + " " + module.getRegularImportedModules().get(aliasModule)); ! } ! buffer.append("\n"); ! buffer.append("# AliasToIdentifier (Module, Realname, Alias)"); ! for (FQIdentifier identifier : module.getAliasToIdentifier()) { ! buffer.append("\n# " + identifier.getModule() + " " + identifier.getRealName() + " " + identifier.getAlias()); ! } ! this.setTestGenerated(buffer.toString().trim()); ! assertEquals(getExpected(), getGenerated()); ! } ! @Override ! public String getExpected() { ! return getResult(); ! } } --- 15,63 ---- public class ModuleAdapterTestCase extends AbstractIOTestCase { ! public ModuleAdapterTestCase(String name) { ! super(name); ! } ! @Override ! public void runTest() throws Throwable { ! StringBuffer buffer = new StringBuffer(); ! ModuleAdapterTestConfig config = null; ! XStream xstream = new XStream(); ! xstream.alias("config", ModuleAdapterTestConfig.class); ! ModuleAdapter module = VisitorFactory.createModuleAdapter(null, null, new Document(getSource()), new PythonNatureStub()); ! if (getConfig().length() > 0) { ! config = (ModuleAdapterTestConfig) xstream.fromXML(getConfig()); ! } else { ! fail("Could not unserialize configuration"); ! return; /* explicit return, fail should already abort */ ! } ! for (String identifier : config.resolveNames) { ! for (FQIdentifier id : module.resolveFullyQualified(identifier)) { ! buffer.append("# " + identifier + " -> " + id.getFQName()); ! buffer.append("\n"); ! } ! } ! buffer.append("# Imported regular modules (Alias, Realname)"); ! for (String aliasModule : module.getRegularImportedModules().keySet()) { ! buffer.append("\n# " + aliasModule + " " + module.getRegularImportedModules().get(aliasModule)); ! } ! buffer.append("\n"); ! buffer.append("# AliasToIdentifier (Module, Realname, Alias)"); ! for (FQIdentifier identifier : module.getAliasToIdentifier()) { ! buffer.append("\n# " + identifier.getModule() + " " + identifier.getRealName() + " " + identifier.getAlias()); ! } ! this.setTestGenerated(buffer.toString().trim()); ! assertEquals(getExpected(), getGenerated()); ! } ! @Override ! public String getExpected() { ! return getResult(); ! } } |