use of org.python.pydev.shared_core.progress.CancelException in project Pydev by fabioz.
the class InterpreterInfo method fromStringOld.
/**
* Format we receive should be:
*
* Executable:python.exe|lib1|lib2|lib3@dll1|dll2|dll3$forcedBuitin1|forcedBuiltin2^envVar1|envVar2@PYDEV_STRING_SUBST_VARS@PropertiesObjectAsString
*
* or
*
* Version2.5Executable:python.exe|lib1|lib2|lib3@dll1|dll2|dll3$forcedBuitin1|forcedBuiltin2^envVar1|envVar2@PYDEV_STRING_SUBST_VARS@PropertiesObjectAsString
* (added only when version 2.5 was added, so, if the string does not have it, it is regarded as 2.4)
*
* or
*
* Name:MyInterpreter:EndName:Version2.5Executable:python.exe|lib1|lib2|lib3@dll1|dll2|dll3$forcedBuitin1|forcedBuiltin2^envVar1|envVar2@PYDEV_STRING_SUBST_VARS@PropertiesObjectAsString
*
* Symbols ': @ $'
*/
private static InterpreterInfo fromStringOld(String received, boolean askUserInOutPath) {
Tuple<String, String> predefCompsPath = StringUtils.splitOnFirst(received, "@PYDEV_PREDEF_COMPS_PATHS@");
received = predefCompsPath.o1;
// Note that the new lines are important for the string substitution, so, we must remove it before removing new lines
Tuple<String, String> stringSubstitutionVarsSplit = StringUtils.splitOnFirst(received, "@PYDEV_STRING_SUBST_VARS@");
received = stringSubstitutionVarsSplit.o1;
received = received.replaceAll("\n", "").replaceAll("\r", "");
String name = null;
if (received.startsWith("Name:")) {
int endNameIndex = received.indexOf(":EndName:");
if (endNameIndex != -1) {
name = received.substring("Name:".length(), endNameIndex);
received = received.substring(endNameIndex + ":EndName:".length());
}
}
Tuple<String, String> envVarsSplit = StringUtils.splitOnFirst(received, '^');
Tuple<String, String> forcedSplit = StringUtils.splitOnFirst(envVarsSplit.o1, '$');
Tuple<String, String> libsSplit = StringUtils.splitOnFirst(forcedSplit.o1, '@');
String exeAndLibs = libsSplit.o1;
// if not found in the string, the grammar version is regarded as 2.4
String version = "2.4";
String[] exeAndLibs1 = exeAndLibs.split("\\|");
String exeAndVersion = exeAndLibs1[0];
String lowerExeAndVersion = exeAndVersion.toLowerCase();
if (lowerExeAndVersion.startsWith("version")) {
int execut = lowerExeAndVersion.indexOf("executable");
version = exeAndVersion.substring(0, execut).substring(7);
exeAndVersion = exeAndVersion.substring(7 + version.length());
}
String executable = exeAndVersion.substring(exeAndVersion.indexOf(":") + 1, exeAndVersion.length());
List<String> selection = new ArrayList<String>();
List<String> toAsk = new ArrayList<String>();
for (int i = 1; i < exeAndLibs1.length; i++) {
// start at 1 (0 is exe)
String trimmed = exeAndLibs1[i].trim();
if (trimmed.length() > 0) {
if (trimmed.endsWith("OUT_PATH")) {
trimmed = trimmed.substring(0, trimmed.length() - 8);
if (askUserInOutPath) {
toAsk.add(trimmed);
} else {
// Change 2.0.1: if not asked, it's included by default!
selection.add(trimmed);
}
} else if (trimmed.endsWith("INS_PATH")) {
trimmed = trimmed.substring(0, trimmed.length() - 8);
if (askUserInOutPath) {
toAsk.add(trimmed);
selection.add(trimmed);
} else {
selection.add(trimmed);
}
} else {
selection.add(trimmed);
}
}
}
try {
selection = filterUserSelection(selection, toAsk);
} catch (CancelException e) {
return null;
}
ArrayList<String> l1 = new ArrayList<String>();
if (libsSplit.o2.length() > 1) {
fillList(libsSplit, l1);
}
ArrayList<String> l2 = new ArrayList<String>();
if (forcedSplit.o2.length() > 1) {
fillList(forcedSplit, l2);
}
ArrayList<String> l3 = new ArrayList<String>();
if (envVarsSplit.o2.length() > 1) {
fillList(envVarsSplit, l3);
}
Properties p4 = null;
if (stringSubstitutionVarsSplit.o2.length() > 1) {
p4 = PropertiesHelper.createPropertiesFromString(stringSubstitutionVarsSplit.o2);
}
InterpreterInfo info = new InterpreterInfo(version, executable, selection, l1, l2, l3, p4);
if (predefCompsPath.o2.length() > 1) {
List<String> split = StringUtils.split(predefCompsPath.o2, '|');
for (String s : split) {
s = s.trim();
if (s.length() > 0) {
info.addPredefinedCompletionsPath(s);
}
}
}
info.setName(name);
return info;
}
use of org.python.pydev.shared_core.progress.CancelException in project Pydev by fabioz.
the class InterpreterInfo method fromString.
/**
* @param received
* String to parse
* @param askUserInOutPath
* true to prompt user about which paths to include.
* @param userSpecifiedExecutable the path the the executable as specified by the user, or null to use that in received
* @return new interpreter info
*/
public static InterpreterInfo fromString(String received, boolean askUserInOutPath, String userSpecifiedExecutable) {
if (received.toLowerCase().indexOf("executable") == -1) {
throw new RuntimeException("Unable to recreate the Interpreter info (Its format changed. Please, re-create your Interpreter information).Contents found:" + received);
}
received = received.trim();
int startXml = received.indexOf("<xml>");
int endXML = received.indexOf("</xml>");
if (startXml == -1 || endXML == -1) {
return fromStringOld(received, askUserInOutPath);
} else {
received = received.substring(startXml, endXML + "</xml>".length());
DocumentBuilder parser;
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setFeature("http://xml.org/sax/features/namespaces", false);
factory.setFeature("http://xml.org/sax/features/validation", false);
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
parser = factory.newDocumentBuilder();
Document document = parser.parse(new InputSource(new StringReader(received)));
NodeList childNodes = document.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node item = childNodes.item(i);
String nodeName = item.getNodeName();
if (!("xml".equals(nodeName))) {
continue;
}
NodeList xmlNodes = item.getChildNodes();
boolean fromPythonBackend = false;
String infoExecutable = null;
String infoName = null;
String infoVersion = null;
String pipenvTargetDir = null;
boolean activateCondaEnv = false;
List<String> selection = new ArrayList<String>();
List<String> toAsk = new ArrayList<String>();
List<String> forcedLibs = new ArrayList<String>();
List<String> envVars = new ArrayList<String>();
List<String> predefinedPaths = new ArrayList<String>();
Properties stringSubstitutionVars = new Properties();
DefaultPathsForInterpreterInfo defaultPaths = new DefaultPathsForInterpreterInfo();
for (int j = 0; j < xmlNodes.getLength(); j++) {
Node xmlChild = xmlNodes.item(j);
String name = xmlChild.getNodeName();
String data = xmlChild.getTextContent().trim();
if ("version".equals(name)) {
infoVersion = data;
} else if ("name".equals(name)) {
infoName = data;
} else if ("executable".equals(name)) {
infoExecutable = data;
} else if ("pipenv_target_dir".equals(name)) {
pipenvTargetDir = data;
} else if ("activate_conda".equals(name)) {
activateCondaEnv = data.equals("true");
} else if ("lib".equals(name)) {
NamedNodeMap attributes = xmlChild.getAttributes();
Node pathIncludeItem = attributes.getNamedItem("path");
if (pathIncludeItem != null) {
if (defaultPaths.exists(data)) {
// The python backend is expected to put path='ins' or path='out'
// While our own toString() is not expected to do that.
// This is probably not a very good heuristic, but it maps the current state of affairs.
fromPythonBackend = true;
if (askUserInOutPath) {
toAsk.add(data);
}
// Select only if path is not child of a root path
if (defaultPaths.selectByDefault(data)) {
selection.add(data);
}
}
} else {
// If not specified, included by default (i.e.: if the path="ins" or path="out" is not
// given, this string was generated internally and not from the python backend, meaning
// that we want to keep it exactly as the user selected).
selection.add(data);
}
} else if ("forced_lib".equals(name)) {
forcedLibs.add(data);
} else if ("env_var".equals(name)) {
envVars.add(data);
} else if ("string_substitution_var".equals(name)) {
NodeList stringSubstitutionVarNode = xmlChild.getChildNodes();
Node keyNode = getNode(stringSubstitutionVarNode, "key");
Node valueNode = getNode(stringSubstitutionVarNode, "value");
stringSubstitutionVars.put(keyNode.getTextContent().trim(), valueNode.getTextContent().trim());
} else if ("predefined_completion_path".equals(name)) {
predefinedPaths.add(data);
} else if ("#text".equals(name)) {
if (data.length() > 0) {
Log.log("Unexpected text content: " + xmlChild.getTextContent());
}
} else {
Log.log("Unexpected node: " + name + " Text content: " + xmlChild.getTextContent());
}
}
if (fromPythonBackend) {
// Ok, when the python backend generated the interpreter information, go on and fill it with
// additional entries (i.e.: not only when we need to ask the user), as this information may
// be later used to check if the interpreter information is valid or missing paths.
AdditionalEntries additionalEntries = new AdditionalEntries();
Collection<String> additionalLibraries = additionalEntries.getAdditionalLibraries();
if (askUserInOutPath) {
addUnique(toAsk, additionalLibraries);
}
addUnique(selection, additionalLibraries);
addUnique(forcedLibs, additionalEntries.getAdditionalBuiltins());
// Load environment variables
Map<String, String> existingEnv = new HashMap<String, String>();
Collection<String> additionalEnvVariables = additionalEntries.getAdditionalEnvVariables();
for (String var : additionalEnvVariables) {
Tuple<String, String> sp = StringUtils.splitOnFirst(var, '=');
existingEnv.put(sp.o1, sp.o2);
}
for (String var : envVars) {
Tuple<String, String> sp = StringUtils.splitOnFirst(var, '=');
existingEnv.put(sp.o1, sp.o2);
}
envVars.clear();
Set<Entry<String, String>> set = existingEnv.entrySet();
for (Entry<String, String> entry : set) {
envVars.add(entry.getKey() + "=" + entry.getValue());
}
// Additional string substitution variables
Map<String, String> additionalStringSubstitutionVariables = additionalEntries.getAdditionalStringSubstitutionVariables();
Set<Entry<String, String>> entrySet = additionalStringSubstitutionVariables.entrySet();
for (Entry<String, String> entry : entrySet) {
if (!stringSubstitutionVars.containsKey(entry.getKey())) {
stringSubstitutionVars.setProperty(entry.getKey(), entry.getValue());
}
}
if (infoVersion != null && !stringSubstitutionVars.containsKey("PY")) {
stringSubstitutionVars.setProperty("PY", StringUtils.replaceAll(infoVersion, ".", ""));
}
}
try {
selection = filterUserSelection(selection, toAsk);
} catch (CancelException e) {
return null;
}
if (userSpecifiedExecutable != null) {
infoExecutable = userSpecifiedExecutable;
}
InterpreterInfo info = new InterpreterInfo(infoVersion, infoExecutable, selection, new ArrayList<String>(), forcedLibs, envVars, stringSubstitutionVars);
info.setName(infoName);
info.setActivateCondaEnv(activateCondaEnv);
info.pipenvTargetDir = pipenvTargetDir;
for (String s : predefinedPaths) {
info.addPredefinedCompletionsPath(s);
}
return info;
}
throw new RuntimeException("Could not find 'xml' node as root of the document.");
} catch (Exception e) {
Log.log("Error loading: " + received, e);
// What can we do about that?
throw new RuntimeException(e);
}
}
}
use of org.python.pydev.shared_core.progress.CancelException in project Pydev by fabioz.
the class PydevPlugin method start.
@SuppressWarnings({ "rawtypes", "restriction" })
@Override
public void start(BundleContext context) throws Exception {
this.isAlive = true;
super.start(context);
// Setup extensions in dependencies
// Setup extensions in dependencies
// Setup extensions in dependencies
// Setup extensions in dependencies (could actually be done as extension points, but done like this for
// ease of implementation right now).
AbstractTemplateCodeCompletion.getTemplateContextType = () -> TemplateHelper.getContextTypeRegistry().getContextType(PyContextType.PY_COMPLETIONS_CONTEXT_TYPE);
CompletionProposalFactory.set(new DefaultCompletionProposalFactory());
ProjectModulesManager.createJavaProjectModulesManagerIfPossible = (IProject project) -> JavaProjectModulesManagerCreator.createJavaProjectModulesManagerIfPossible(project);
ModulesManager.createModuleFromJar = (EmptyModuleForZip emptyModuleForZip, IPythonNature nature) -> JythonModulesManagerUtils.createModuleFromJar(emptyModuleForZip, nature);
CorePlugin.pydevStatelocation = Platform.getStateLocation(getBundle()).toFile();
PyLintPreferences.createPyLintStream = ((IAdaptable projectAdaptable) -> {
if (PyLintPreferences.useConsole(projectAdaptable)) {
IOConsoleOutputStream console = MessageConsoles.getConsoleOutputStream("PyLint", UIConstants.PY_LINT_ICON);
return ((string) -> {
console.write(string);
});
} else {
return null;
}
});
Flake8Preferences.createFlake8Stream = ((IAdaptable projectAdaptable) -> {
if (Flake8Preferences.useFlake8Console(projectAdaptable)) {
IOConsoleOutputStream console = MessageConsoles.getConsoleOutputStream("Flake8", UIConstants.FLAKE8_ICON);
return ((string) -> {
console.write(string);
});
} else {
return null;
}
});
MypyPreferences.createMypyStream = ((IAdaptable projectAdaptable) -> {
if (MypyPreferences.useMypyConsole(projectAdaptable)) {
IOConsoleOutputStream console = MessageConsoles.getConsoleOutputStream("Mypy", UIConstants.MYPY_ICON);
return ((string) -> {
console.write(string);
});
} else {
return null;
}
});
JavaVmLocationFinder.callbackJavaJars = () -> {
try {
IVMInstall defaultVMInstall = JavaRuntime.getDefaultVMInstall();
LibraryLocation[] libraryLocations = JavaRuntime.getLibraryLocations(defaultVMInstall);
ArrayList<File> jars = new ArrayList<File>();
for (LibraryLocation location : libraryLocations) {
jars.add(location.getSystemLibraryPath().toFile());
}
return jars;
} catch (Throwable e) {
JythonModulesManagerUtils.tryRethrowAsJDTNotAvailableException(e);
throw new RuntimeException("Should never get here", e);
}
};
JavaVmLocationFinder.callbackJavaExecutable = () -> {
try {
IVMInstall defaultVMInstall = JavaRuntime.getDefaultVMInstall();
File installLocation = defaultVMInstall.getInstallLocation();
return StandardVMType.findJavaExecutable(installLocation);
} catch (Throwable e) {
JythonModulesManagerUtils.tryRethrowAsJDTNotAvailableException(e);
throw new RuntimeException("Should never get here", e);
}
};
PyLinkedModeCompletionProposal.goToLinkedModeHandler = (PyLinkedModeCompletionProposal proposal, ITextViewer viewer, int offset, IDocument doc, int exitPos, int iPar, List<Integer> offsetsAndLens) -> {
LinkedModeModel model = new LinkedModeModel();
for (int i = 0; i < offsetsAndLens.size(); i++) {
Integer offs = offsetsAndLens.get(i);
i++;
Integer len = offsetsAndLens.get(i);
if (i == 1) {
proposal.firstParameterLen = len;
}
int location = offset + iPar + offs + 1;
LinkedPositionGroup group = new LinkedPositionGroup();
ProposalPosition proposalPosition = new ProposalPosition(doc, location, len, 0, new ICompletionProposal[0]);
group.addPosition(proposalPosition);
model.addGroup(group);
}
model.forceInstall();
final LinkedModeUI ui = new EditorLinkedModeUI(model, viewer);
// set it to request the ctx info from the completion processor
ui.setDoContextInfo(true);
ui.setExitPosition(viewer, exitPos, 0, Integer.MAX_VALUE);
Runnable r = new Runnable() {
@Override
public void run() {
ui.enter();
}
};
RunInUiThread.async(r);
};
/**
* Given a passed tree, selects the elements on the tree (and returns the selected elements in a flat list).
*/
SyncSystemModulesManager.selectElementsInDialog = (final DataAndImageTreeNode root, List<TreeNode> initialSelection) -> {
List<TreeNode> selectElements = SelectNDialog.selectElements(root, new TreeNodeLabelProvider() {
@Override
public org.eclipse.swt.graphics.Image getImage(Object element) {
DataAndImageTreeNode n = (DataAndImageTreeNode) element;
return ImageCache.asImage(n.image);
}
@Override
public String getText(Object element) {
TreeNode n = (TreeNode) element;
Object data = n.getData();
if (data == null) {
return "null";
}
if (data instanceof IInterpreterInfo) {
IInterpreterInfo iInterpreterInfo = (IInterpreterInfo) data;
return iInterpreterInfo.getNameForUI();
}
return data.toString();
}
}, "System PYTHONPATH changes detected", "Please check which interpreters and paths should be updated.", true, initialSelection);
return selectElements;
};
InterpreterInfo.selectLibraries = new IPythonSelectLibraries() {
@Override
public List<String> select(List<String> selection, List<String> toAsk) throws CancelException {
// true == OK, false == CANCELLED
boolean result = true;
PythonSelectionLibrariesDialog runnable = new PythonSelectionLibrariesDialog(selection, toAsk, true);
try {
RunInUiThread.sync(runnable);
} catch (NoClassDefFoundError e) {
} catch (UnsatisfiedLinkError e) {
// this means that we're running unit-tests, so, we don't have to do anything about it
// as 'l' is already ok.
}
result = runnable.getOkResult();
if (result == false) {
// Canceled by the user
throw new CancelException();
}
return runnable.getSelection();
}
};
org.python.pydev.shared_core.log.ToLogFile.afterOnToLogFile = (final String buffer) -> {
final Runnable r = new Runnable() {
@Override
public void run() {
synchronized (org.python.pydev.shared_core.log.ToLogFile.lock) {
try {
// Print to console view (must be in UI thread).
IOConsoleOutputStream c = org.python.pydev.shared_ui.log.ToLogFile.getConsoleOutputStream();
c.write(buffer.toString());
c.write(System.lineSeparator());
} catch (Throwable e) {
Log.log(e);
}
}
}
};
RunInUiThread.async(r, true);
return null;
};
AbstractInterpreterManager.configWhenInterpreterNotAvailable = (manager) -> {
// If we got here, the interpreter is not properly configured, let's try to auto-configure it
if (PyDialogHelpers.getAskAgainInterpreter(manager)) {
configureInterpreterJob.addInterpreter(manager);
configureInterpreterJob.schedule(50);
}
return null;
};
AbstractInterpreterManager.errorCreatingInterpreterInfo = (title, reason) -> {
try {
final Display disp = Display.getDefault();
disp.asyncExec(new Runnable() {
@Override
public void run() {
ErrorDialog.openError(null, title, "Unable to get information on interpreter!", new Status(Status.ERROR, PydevPlugin.getPluginID(), 0, reason, null));
}
});
} catch (Throwable e) {
// ignore error communication error
}
return null;
};
try {
resourceBundle = ResourceBundle.getBundle("org.python.pydev.PyDevPluginResources");
} catch (MissingResourceException x) {
resourceBundle = null;
}
final IEclipsePreferences preferences = PydevPrefs.getEclipsePreferences();
// set them temporarily
// setPythonInterpreterManager(new StubInterpreterManager(true));
// setJythonInterpreterManager(new StubInterpreterManager(false));
// changed: the interpreter manager is always set in the initialization (initialization
// has some problems if that's not done).
InterpreterManagersAPI.setPythonInterpreterManager(new PythonInterpreterManager(preferences));
InterpreterManagersAPI.setJythonInterpreterManager(new JythonInterpreterManager(preferences));
InterpreterManagersAPI.setIronpythonInterpreterManager(new IronpythonInterpreterManager(preferences));
// This is usually fast, but in lower end machines it could be a bit slow, so, let's do it in a job to make sure
// that the plugin is properly initialized without any delays.
startSynchSchedulerJob.schedule(1000);
// restore the nature for all python projects -- that's done when the project is set now.
// new Job("PyDev: Restoring projects python nature"){
//
// protected IStatus run(IProgressMonitor monitor) {
// try{
//
// IProject[] projects = getWorkspace().getRoot().getProjects();
// for (int i = 0; i < projects.length; i++) {
// IProject project = projects[i];
// try {
// if (project.isOpen() && project.hasNature(PythonNature.PYTHON_NATURE_ID)) {
// PythonNature.addNature(project, monitor, null, null);
// }
// } catch (Exception e) {
// PydevPlugin.log(e);
// }
// }
// }catch(Throwable t){
// t.printStackTrace();
// }
// return Status.OK_STATUS;
// }
//
// }.schedule();
}
Aggregations