use of org.python.pydev.ast.interpreter_managers.JythonInterpreterManager in project gda-core by openGDA.
the class ScriptProjectCreator method createInterpreter.
/**
* We programmatically create a Jython Interpreter so that the user does not have to.
*/
private static void createInterpreter(IProgressMonitor monitor) throws Exception {
logger.debug("Stating creation of Jython interpreter");
final IPreferenceStore preferenceStore = GDAClientActivator.getDefault().getPreferenceStore();
// Horrible Hack warning: This code is copied from parts of Pydev to set up the interpreter and save it.
// Code copies from Pydev when the user chooses a Jython interpreter - these are the defaults.
final Path interpreterPath = Paths.get(BundleUtils.getBundleLocation(JYTHON_BUNDLE).getAbsolutePath());
final String executable = interpreterPath.resolve(JYTHON_JAR).toString();
if (!(new File(executable)).exists())
throw new Exception("Jython jar not found :" + executable);
final File script = CorePlugin.getScriptWithinPySrc("interpreterInfo.py");
if (!script.exists()) {
throw new RuntimeException("The file specified does not exist: " + script);
}
monitor.subTask("Creating interpreter");
// gets the info for the python side
String encoding = null;
Tuple<String, String> outTup = new SimpleJythonRunner().runAndGetOutputWithJar(FileUtils.getFileAbsolutePath(script), executable, null, null, null, monitor, encoding);
InterpreterInfo info = null;
try {
// HACK Otherwise Pydev shows a dialog to the user.
ModulesManagerWithBuild.IN_TESTS = true;
info = InterpreterInfo.fromString(outTup.o1, false);
} catch (Exception e) {
logger.error("Something went wrong creating the InterpreterInfo.", e);
} finally {
ModulesManagerWithBuild.IN_TESTS = false;
}
if (info == null) {
// cancelled
return;
}
// the executable is the jar itself
info.executableOrJar = executable;
// we have to find the jars before we restore the compiled libs
if (preferenceStore.getBoolean(PreferenceConstants.GDA_PYDEV_ADD_DEFAULT_JAVA_JARS)) {
List<File> jars = JavaVmLocationFinder.findDefaultJavaJars();
for (File jar : jars) {
info.libs.add(FileUtils.getFileAbsolutePath(jar));
}
}
List<String> allScriptProjectFolders = JythonServerFacade.getInstance().getAllScriptProjectFolders();
for (String s : allScriptProjectFolders) {
info.libs.add(s);
}
// java, java.lang, etc should be found now
info.restoreCompiledLibs(monitor);
info.setName(INTERPRETER_NAME);
final JythonInterpreterManager man = (JythonInterpreterManager) InterpreterManagersAPI.getJythonInterpreterManager();
HashSet<String> set = new HashSet<>();
set.add(INTERPRETER_NAME);
man.setInfos(new IInterpreterInfo[] { info }, set, monitor);
logger.info("Jython interpreter registered: {}", INTERPRETER_NAME);
}
use of org.python.pydev.ast.interpreter_managers.JythonInterpreterManager 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();
}
use of org.python.pydev.ast.interpreter_managers.JythonInterpreterManager in project Pydev by fabioz.
the class AbstractWorkbenchTestCase method configureInterpreters.
protected static void configureInterpreters() {
if (!interpretersConfigured) {
interpretersConfigured = true;
InterpreterInfo.configurePathsCallback = new ICallback<Boolean, Tuple<List<String>, List<String>>>() {
@Override
public Boolean call(Tuple<List<String>, List<String>> arg) {
return Boolean.TRUE;
}
};
IEclipsePreferences node = PydevPrefs.getEclipsePreferences();
InterpreterManagersAPI.setJythonInterpreterManager(new JythonInterpreterManager(node));
InterpreterManagersAPI.setPythonInterpreterManager(new PythonInterpreterManager(node));
ProjectModulesManager.IN_TESTS = true;
NullProgressMonitor monitor = new NullProgressMonitor();
createJythonInterpreterManager(monitor);
createPythonInterpreterManager(monitor);
}
}
use of org.python.pydev.ast.interpreter_managers.JythonInterpreterManager in project Pydev by fabioz.
the class JythonCodeCompletionTestsBase method setInterpreterManager.
@Override
protected void setInterpreterManager(String path) {
AbstractInterpreterManager interpreterManager = new JythonInterpreterManager(this.getPreferences());
InterpreterInfo info;
info = (InterpreterInfo) interpreterManager.createInterpreterInfo(TestDependent.JYTHON_JAR_LOCATION, new NullProgressMonitor(), false);
if (!info.executableOrJar.equals(TestDependent.JYTHON_JAR_LOCATION)) {
throw new RuntimeException("expected same");
}
if (path != null) {
info = new InterpreterInfo(info.getVersion(), TestDependent.JYTHON_JAR_LOCATION, PythonPathHelper.parsePythonPathFromStr(path, new ArrayList<String>()));
}
interpreterManager.setInfos(new IInterpreterInfo[] { info }, null, null);
InterpreterManagersAPI.setJythonInterpreterManager(interpreterManager);
}
Aggregations