use of org.python.pydev.ui.dialogs.TreeSelectionDialog in project Pydev by fabioz.
the class SelectTestTreeContentProvider method run.
@Override
public void run(IAction action) {
PyEdit pyEdit = getPyEdit();
final Tuple<String, IInterpreterManager> launchConfigurationTypeAndInterpreterManager = this.getLaunchConfigurationTypeAndInterpreterManager(pyEdit, true);
Shell shell = EditorUtils.getShell();
final DialogMemento memento = new DialogMemento(shell, "org.python.pydev.debug.ui.actions.RunEditorAsCustomUnitTestAction");
SimpleNode ast = pyEdit.getAST();
final ShiftListener shiftListener = new ShiftListener();
Display d = shell.getDisplay();
d.addFilter(SWT.KeyDown, shiftListener);
d.addFilter(SWT.KeyUp, shiftListener);
try {
final TreeSelectionDialog dialog = new TreeSelectionDialog(shell, new SelectTestLabelProvider(), new SelectTestTreeContentProvider(pyEdit)) {
private Label labelShiftToDebug;
@Override
public boolean close() {
memento.writeSettings(getShell());
return super.close();
}
@Override
public Control createDialogArea(Composite parent) {
memento.readSettings();
Control ret = super.createDialogArea(parent);
ret.addTraverseListener(new TraverseListener() {
@Override
public void keyTraversed(TraverseEvent e) {
if (e.detail == SWT.TRAVERSE_RETURN) {
okPressed();
}
}
});
return ret;
}
/* (non-Javadoc)
* @see org.python.pydev.ui.dialogs.TreeSelectionDialog#createButtonBar(org.eclipse.swt.widgets.Composite)
*/
@Override
protected Control createButtonBar(Composite parent) {
Composite buttonBar = new Composite(parent, 0);
GridLayout layout = new GridLayout();
layout.numColumns = 2;
buttonBar.setLayout(layout);
GridData data = new GridData();
data.horizontalAlignment = SWT.FILL;
data.grabExcessHorizontalSpace = true;
buttonBar.setLayoutData(data);
Link configTestRunner = new Link(buttonBar, SWT.PUSH);
configTestRunner.setText(" <a>Configure test runner</a>");
configTestRunner.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
PyUnitPrefsPage2.showPage();
}
});
data = new GridData();
data.horizontalAlignment = GridData.BEGINNING;
data.grabExcessHorizontalSpace = true;
configTestRunner.setLayoutData(data);
labelShiftToDebug = new Label(buttonBar, 0);
labelShiftToDebug.setText("Run: Normal (Press Shift to Debug)");
data = new GridData();
data.horizontalAlignment = GridData.END;
data.grabExcessHorizontalSpace = true;
labelShiftToDebug.setLayoutData(data);
shiftListener.onChanged.registerListener(new ICallbackListener<Boolean>() {
@Override
public Object call(Boolean shiftPressed) {
if (shiftPressed) {
labelShiftToDebug.setText("Run: Debug (Release Shift for Normal)");
} else {
labelShiftToDebug.setText("Run: Normal (Press Shift to Debug)");
}
labelShiftToDebug.getParent().layout(true);
return null;
}
});
Tree tree = getTreeViewer().getTree();
Menu menu = new Menu(tree.getShell(), SWT.POP_UP);
MenuItem runItem = new MenuItem(menu, SWT.PUSH);
final TreeSelectionDialog outerDialog = this;
runItem.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
ILaunchConfiguration conf = null;
IStructuredSelection selection = (IStructuredSelection) getTreeViewer().getSelection();
IEditorInput editorInput = pyEdit.getEditorInput();
IFile resource = editorInput != null ? editorInput.getAdapter(IFile.class) : null;
FileOrResource[] fileOrResource;
if (resource != null) {
fileOrResource = new FileOrResource[] { new FileOrResource(resource) };
} else {
fileOrResource = new FileOrResource[] { new FileOrResource(pyEdit.getEditorFile()) };
}
String testNames = getFullArgumentsRepresentation(selection.toArray());
UnittestLaunchShortcut shortcut = new UnittestLaunchShortcut(launchConfigurationTypeAndInterpreterManager, testNames);
List<ILaunchConfiguration> configurations = shortcut.findExistingLaunchConfigurations(fileOrResource);
boolean newConfiguration = false;
if (configurations.isEmpty()) {
conf = shortcut.createDefaultLaunchConfiguration(fileOrResource);
newConfiguration = true;
} else {
// assume that there's only one matching configuration
conf = configurations.get(0);
}
int retVal = DebugUITools.openLaunchConfigurationDialog(shell, conf, shiftListener.shiftPressed ? IDebugUIConstants.ID_DEBUG_LAUNCH_GROUP : IDebugUIConstants.ID_RUN_LAUNCH_GROUP, null);
if (retVal == Window.CANCEL && newConfiguration) {
// user cancelled operation on newly created configuration
try {
conf.delete();
} catch (CoreException e1) {
// ignore
}
}
if (retVal == Window.OK) {
outerDialog.cancel();
}
}
});
runItem.setText("Customize run configuration...");
tree.setMenu(menu);
return buttonBar;
}
@Override
protected Point getInitialSize() {
return memento.getInitialSize(super.getInitialSize(), getShell());
}
@Override
protected Point getInitialLocation(Point initialSize) {
return memento.getInitialLocation(initialSize, super.getInitialLocation(initialSize), getShell());
}
/*
* @see SelectionStatusDialog#computeResult()
*/
@Override
@SuppressWarnings("unchecked")
protected void computeResult() {
doFinalUpdateBeforeComputeResult();
IStructuredSelection selection = (IStructuredSelection) getTreeViewer().getSelection();
List<Object> list = selection.toList();
if (list.size() > 0) {
setResult(list);
} else {
Tree tree = getTreeViewer().getTree();
TreeItem[] items = tree.getItems();
list = new ArrayList<Object>();
// Now, if he didn't select anything, let's create tests with all that is currently filtered
// in the interface
createListWithLeafs(items, list);
setResult(list);
}
}
private void createListWithLeafs(TreeItem[] items, List<Object> leafObjectsList) {
for (TreeItem item : items) {
TreeItem[] children = item.getItems();
if (children.length == 0) {
leafObjectsList.add(item.getData());
} else {
createListWithLeafs(children, leafObjectsList);
}
}
}
};
dialog.setTitle("PyDev: Select tests to run");
dialog.setMessage("Select the tests to run (press enter to run tests shown/selected)");
PySelection ps = pyEdit.createPySelection();
String selectedText;
try {
selectedText = ps.getSelectedText();
} catch (BadLocationException e) {
selectedText = "";
}
if (selectedText.length() > 0 && PyStringUtils.isValidIdentifier(selectedText, false)) {
// Space in the end == exact match
dialog.setInitialFilter(selectedText + " ");
} else {
dialog.setInitialFilter("test");
}
dialog.setAllowMultiple(true);
dialog.setInput(ast);
int open = dialog.open();
if (open != Window.OK) {
return;
}
Object[] result = dialog.getResult();
final String arguments = getFullArgumentsRepresentation(result);
AbstractLaunchShortcut shortcut = new UnittestLaunchShortcut(launchConfigurationTypeAndInterpreterManager, arguments);
if (shiftListener.shiftPressed) {
shortcut.launch(pyEdit, "debug");
} else {
shortcut.launch(pyEdit, "run");
}
} finally {
d.removeFilter(SWT.KeyDown, shiftListener);
d.removeFilter(SWT.KeyUp, shiftListener);
}
}
use of org.python.pydev.ui.dialogs.TreeSelectionDialog in project Pydev by fabioz.
the class OrganizeImports method beforePerformArrangeImports.
/**
* That's where everything happens.
*
* Important: if the document is in a rewrite session, trying to highlight a given session does not work
* (so, we cannot be in a rewrite session in this case).
*/
@Override
public boolean beforePerformArrangeImports(final PySelection ps, final PyEdit edit, IFile f) {
if ((!AnalysisPreferences.doAutoImportOnOrganizeImports(edit)) || edit == null) {
return true;
}
didChange = false;
ArrayList<MarkerAnnotationAndPosition> undefinedVariablesMarkers = getUndefinedVariableMarkers(edit);
// sort them
TreeMap<Integer, MarkerAnnotationAndPosition> map = new TreeMap<Integer, MarkerAnnotationAndPosition>();
for (MarkerAnnotationAndPosition marker : undefinedVariablesMarkers) {
if (marker.position == null) {
continue;
}
int start = marker.position.offset;
map.put(start, marker);
}
// create the participant that'll help (will not force a reparse)
final UndefinedVariableFixParticipant variableFixParticipant = new UndefinedVariableFixParticipant(false);
// These are the completions to apply. We must apply them all at once after finishing it because we can't do
// it one by one during the processing because that'd make markers change.
final List<ICompletionProposalExtension2> completionsToApply = new ArrayList<ICompletionProposalExtension2>();
// keeps the strings we've already treated.
final HashSet<String> treatedVars = new HashSet<String>();
// variable to hold whether we should keep on choosing the imports
final Boolean[] keepGoing = new Boolean[] { true };
final IDialogSettings dialogSettings = AnalysisUiPlugin.getDialogSettings();
// analyse the markers (one by one)
for (final MarkerAnnotationAndPosition marker : map.values()) {
if (!keepGoing[0]) {
break;
}
try {
final int start = marker.position.offset;
final int end = start + marker.position.length;
if (start >= 0 && end > start) {
IDocument doc = ps.getDoc();
ArrayList<ICompletionProposalHandle> props = new ArrayList<ICompletionProposalHandle>();
try {
String string = doc.get(start, end - start);
if (treatedVars.contains(string)) {
continue;
}
variableFixParticipant.addProps(marker, null, null, ps, start, edit.getPythonNature(), edit, props);
if (props.size() > 0) {
// Sorting proposals on Ctrl+Shift+O.
ProposalsComparator proposalsComparator = new ProposalsComparator("", new ProposalsComparator.CompareContext(edit.getPythonNature()));
props.sort(proposalsComparator);
edit.selectAndReveal(start, end - start);
treatedVars.add(string);
Shell activeShell = Display.getCurrent().getActiveShell();
// Changed from ElementListSelectionDialog so that we can control the sorting.
TreeSelectionDialog dialog = new TreeSelectionDialog(activeShell, new LabelProvider() {
// get the image and text for each completion
@Override
public Image getImage(Object element) {
CtxInsensitiveImportComplProposal comp = ((CtxInsensitiveImportComplProposal) element);
return comp.getImage();
}
@Override
public String getText(Object element) {
CtxInsensitiveImportComplProposal comp = ((CtxInsensitiveImportComplProposal) element);
return comp.getDisplayString();
}
}, new ListContentProvider()) {
// override things to return the last position of the dialog correctly
@Override
protected Control createContents(Composite parent) {
Control ret = super.createContents(parent);
org.python.pydev.plugin.PydevPlugin.setCssId(parent, "py-add-imports-dialog", true);
return ret;
}
@Override
public boolean isHelpAvailable() {
return false;
}
@Override
protected void updateStatus(IStatus status) {
super.updateStatus(status);
PydevPlugin.fixSelectionStatusDialogStatusLineColor(this, this.getDialogArea().getBackground());
}
/**
* @see org.eclipse.ui.dialogs.SelectionDialog#getDialogBoundsSettings()
*/
@Override
protected IDialogSettings getDialogBoundsSettings() {
IDialogSettings section = dialogSettings.getSection(DIALOG_SETTINGS);
if (section == null) {
section = dialogSettings.addNewSection(DIALOG_SETTINGS);
}
return section;
}
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.Dialog#getInitialSize()
*/
@Override
protected Point getInitialSize() {
IDialogSettings settings = getDialogBoundsSettings();
if (settings != null) {
try {
// $NON-NLS-1$
int width = settings.getInt("DIALOG_WIDTH");
// $NON-NLS-1$
int height = settings.getInt("DIALOG_HEIGHT");
if (width > 0 & height > 0) {
return new Point(width, height);
}
} catch (NumberFormatException nfe) {
// make the default return
}
}
return new Point(300, 300);
}
};
dialog.setTitle("Choose import");
dialog.setMessage("Which import should be added?");
dialog.setInput(props);
dialog.setInitialSelection(props.get(0));
int returnCode = dialog.open();
if (returnCode == Window.OK) {
ICompletionProposalExtension2 firstResult = (ICompletionProposalExtension2) dialog.getFirstResult();
completionsToApply.add(firstResult);
} else if (returnCode == Window.CANCEL) {
keepGoing[0] = false;
continue;
}
}
} catch (Exception e) {
Log.log(e);
}
}
} catch (Exception e) {
Log.log(e);
}
}
for (ICompletionProposalExtension2 comp : completionsToApply) {
// the offset is not used in this case, because the actual completion does nothing,
int offset = 0;
// we'll only add the import.
comp.apply(edit.getPySourceViewer(), ' ', 0, offset);
didChange = true;
}
return true;
}
Aggregations