From 37759a5e1e1dfb7c2b3d3e28e9e8399ce39e9251 Mon Sep 17 00:00:00 2001 From: UNV Date: Wed, 5 Nov 2025 22:23:57 +0300 Subject: [PATCH] Replacing deprecated CommonDataKeys and LangDataKeys. Refactoring. --- .../com/jetbrains/pyqt/CompileQrcAction.java | 167 ++++----- .../python/impl/actions/CleanPycAction.java | 127 +++---- .../impl/actions/CreatePackageAction.java | 164 +++++---- .../console/PyOpenDebugConsoleAction.java | 94 ++--- .../impl/console/PydevConsoleRunnerImpl.java | 344 +++++++++--------- .../impl/console/RunPythonConsoleAction.java | 70 ++-- .../hierarchy/PyTypeHierachyProvider.java | 66 ++-- .../packaging/PyManagePackagesAction.java | 28 +- .../setupPy/CreateSetupPyAction.java | 185 +++++----- .../setupPy/SetupTaskChooserAction.java | 120 +++--- .../classes/PyClassRefactoringHandler.java | 149 ++++---- .../jetbrains/python/rest/RestPythonUtil.java | 59 ++- .../sphinx/RunSphinxQuickStartAction.java | 70 ++-- 13 files changed, 827 insertions(+), 816 deletions(-) diff --git a/python-impl/src/main/java/com/jetbrains/pyqt/CompileQrcAction.java b/python-impl/src/main/java/com/jetbrains/pyqt/CompileQrcAction.java index 6c2827f0..882310be 100644 --- a/python-impl/src/main/java/com/jetbrains/pyqt/CompileQrcAction.java +++ b/python-impl/src/main/java/com/jetbrains/pyqt/CompileQrcAction.java @@ -13,20 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.jetbrains.pyqt; import consulo.execution.RunContentExecutor; import consulo.execution.process.ProcessTerminatedListener; import consulo.fileChooser.FileChooserDescriptorFactory; -import consulo.language.editor.CommonDataKeys; -import consulo.language.editor.LangDataKeys; import consulo.module.Module; import consulo.process.ExecutionException; import consulo.process.ProcessHandler; import consulo.process.ProcessHandlerBuilder; import consulo.process.cmd.GeneralCommandLine; import consulo.project.Project; +import consulo.ui.annotation.RequiredUIAccess; import consulo.ui.ex.action.AnAction; import consulo.ui.ex.action.AnActionEvent; import consulo.ui.ex.awt.DialogWrapper; @@ -41,95 +39,98 @@ * @author yole */ public class CompileQrcAction extends AnAction { - @Override - public void actionPerformed(AnActionEvent e) { - Project project = e.getData(CommonDataKeys.PROJECT); - VirtualFile[] vFiles = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY); - assert vFiles != null; - Module module = e.getData(LangDataKeys.MODULE); - String path = QtFileType.findQtTool(module, "pyrcc4"); - if (path == null) { - path = QtFileType.findQtTool(module, "pyside-rcc"); - } - if (path == null) { - Messages.showErrorDialog(project, "Could not find pyrcc4 or pyside-rcc for selected Python interpreter", "Compile .qrc file"); - return; - } - CompileQrcDialog dialog = new CompileQrcDialog(project, vFiles); - dialog.show(); - if (dialog.getExitCode() != DialogWrapper.OK_EXIT_CODE) { - return; - } + @Override + @RequiredUIAccess + public void actionPerformed(AnActionEvent e) { + Project project = e.getData(Project.KEY); + VirtualFile[] vFiles = e.getRequiredData(VirtualFile.KEY_OF_ARRAY); + Module module = e.getData(Module.KEY); + String path = QtFileType.findQtTool(module, "pyrcc4"); + if (path == null) { + path = QtFileType.findQtTool(module, "pyside-rcc"); + } + if (path == null) { + Messages.showErrorDialog(project, "Could not find pyrcc4 or pyside-rcc for selected Python interpreter", "Compile .qrc file"); + return; + } + CompileQrcDialog dialog = new CompileQrcDialog(project, vFiles); + dialog.show(); + if (dialog.getExitCode() != DialogWrapper.OK_EXIT_CODE) { + return; + } - GeneralCommandLine cmdLine = new GeneralCommandLine(); - cmdLine.setPassParentEnvironment(true); - cmdLine.setExePath(path); - cmdLine.addParameters("-o", dialog.getOutputPath()); - for (VirtualFile vFile : vFiles) { - cmdLine.addParameter(vFile.getPath()); - } - try { - ProcessHandler process = ProcessHandlerBuilder.create(cmdLine).build(); - ProcessTerminatedListener.attach(process); - new RunContentExecutor(project, process) - .withTitle("Compile .qrc") - .run(); + GeneralCommandLine cmdLine = new GeneralCommandLine(); + cmdLine.setPassParentEnvironment(true); + cmdLine.setExePath(path); + cmdLine.addParameters("-o", dialog.getOutputPath()); + for (VirtualFile vFile : vFiles) { + cmdLine.addParameter(vFile.getPath()); + } + try { + ProcessHandler process = ProcessHandlerBuilder.create(cmdLine).build(); + ProcessTerminatedListener.attach(process); + new RunContentExecutor(project, process) + .withTitle("Compile .qrc") + .run(); + } + catch (ExecutionException ex) { + Messages.showErrorDialog(project, "Error running " + path + ": " + ex.getMessage(), "Compile .qrc file"); + } } - catch (ExecutionException ex) { - Messages.showErrorDialog(project, "Error running " + path + ": " + ex.getMessage(), "Compile .qrc file"); - } - } - - @Override - public void update(AnActionEvent e) { - Module module = e.getData(LangDataKeys.MODULE); - VirtualFile[] vFiles = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY); - e.getPresentation().setVisible(module != null && filesAreQrc(vFiles)); - } - private static boolean filesAreQrc(VirtualFile[] vFiles) { - if (vFiles == null || vFiles.length == 0) { - return false; + @Override + public void update(AnActionEvent e) { + Module module = e.getData(Module.KEY); + VirtualFile[] vFiles = e.getData(VirtualFile.KEY_OF_ARRAY); + e.getPresentation().setVisible(module != null && filesAreQrc(vFiles)); } - for (VirtualFile vFile : vFiles) { - if (!FileUtil.extensionEquals(vFile.getName(), "qrc")) { - return false; - } + + private static boolean filesAreQrc(VirtualFile[] vFiles) { + if (vFiles == null || vFiles.length == 0) { + return false; + } + for (VirtualFile vFile : vFiles) { + if (!FileUtil.extensionEquals(vFile.getName(), "qrc")) { + return false; + } + } + return true; } - return true; - } - public static class CompileQrcDialog extends DialogWrapper { - private JPanel myPanel; - private TextFieldWithBrowseButton myOutputFileField; + public static class CompileQrcDialog extends DialogWrapper { + private JPanel myPanel; + private TextFieldWithBrowseButton myOutputFileField; - protected CompileQrcDialog(Project project, VirtualFile[] vFiles) { - super(project); - if (vFiles.length == 1) { - setTitle("Compile " + vFiles[0].getName()); - } - else { - setTitle("Compile " + vFiles.length + " .qrc files"); - } - myOutputFileField.addBrowseFolderListener("Select output path:", - null, - project, - FileChooserDescriptorFactory.createSingleLocalFileDescriptor()); - init(); - } + protected CompileQrcDialog(Project project, VirtualFile[] vFiles) { + super(project); + if (vFiles.length == 1) { + setTitle("Compile " + vFiles[0].getName()); + } + else { + setTitle("Compile " + vFiles.length + " .qrc files"); + } + myOutputFileField.addBrowseFolderListener( + "Select output path:", + null, + project, + FileChooserDescriptorFactory.createSingleLocalFileDescriptor() + ); + init(); + } - @Override - protected JComponent createCenterPanel() { - return myPanel; - } + @Override + protected JComponent createCenterPanel() { + return myPanel; + } - public String getOutputPath() { - return myOutputFileField.getText(); - } + public String getOutputPath() { + return myOutputFileField.getText(); + } - @Override - public JComponent getPreferredFocusedComponent() { - return myOutputFileField; + @Override + @RequiredUIAccess + public JComponent getPreferredFocusedComponent() { + return myOutputFileField; + } } - } } diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/actions/CleanPycAction.java b/python-impl/src/main/java/com/jetbrains/python/impl/actions/CleanPycAction.java index 3bf58566..29cb88e4 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/actions/CleanPycAction.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/actions/CleanPycAction.java @@ -13,25 +13,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.jetbrains.python.impl.actions; import com.jetbrains.python.PyNames; import consulo.application.Application; import consulo.application.progress.ProgressManager; import consulo.application.util.AsyncFileService; -import consulo.application.util.function.Processor; -import consulo.language.editor.LangDataKeys; import consulo.language.psi.PsiDirectory; import consulo.language.psi.PsiElement; import consulo.project.Project; -import consulo.project.ui.wm.StatusBar; -import consulo.project.ui.wm.WindowManager; +import consulo.ui.annotation.RequiredUIAccess; import consulo.ui.ex.action.AnAction; import consulo.ui.ex.action.AnActionEvent; import consulo.util.io.FileUtil; - import jakarta.annotation.Nullable; + import java.io.File; import java.util.ArrayList; import java.util.List; @@ -39,73 +35,60 @@ /** * @author yole */ -public class CleanPycAction extends AnAction -{ - private static void collectPycFiles(File directory, final List pycFiles) - { - FileUtil.processFilesRecursively(directory, new Processor() - { - @Override - public boolean process(File file) - { - if(file.getParentFile().getName().equals(PyNames.PYCACHE) || - FileUtil.extensionEquals(file.getName(), "pyc") || - FileUtil.extensionEquals(file.getName(), "pyo")) - { - pycFiles.add(file); - } - return true; - } - }); - } +public class CleanPycAction extends AnAction { + private static void collectPycFiles(File directory, List pycFiles) { + FileUtil.processFilesRecursively( + directory, + file -> { + if (file.getParentFile().getName().equals(PyNames.PYCACHE) + || FileUtil.extensionEquals(file.getName(), "pyc") + || FileUtil.extensionEquals(file.getName(), "pyo")) { + pycFiles.add(file); + } + return true; + } + ); + } - private static boolean isAllDirectories(@Nullable PsiElement[] elements) - { - if(elements == null || elements.length == 0) - { - return false; - } - for(PsiElement element : elements) - { - if(!(element instanceof PsiDirectory)) - { - return false; - } - } - return true; - } + private static boolean isAllDirectories(@Nullable PsiElement[] elements) { + if (elements == null || elements.length == 0) { + return false; + } + for (PsiElement element : elements) { + if (!(element instanceof PsiDirectory)) { + return false; + } + } + return true; + } - @Override - public void actionPerformed(AnActionEvent e) - { - final PsiElement[] elements = e.getData(LangDataKeys.PSI_ELEMENT_ARRAY); - if(elements == null) - { - return; - } - List pycFiles = new ArrayList(); - ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() - { - @Override - public void run() - { - for(PsiElement element : elements) - { - PsiDirectory dir = (PsiDirectory) element; - collectPycFiles(new File(dir.getVirtualFile().getPath()), pycFiles); - } - Application.get().getInstance(AsyncFileService.class).asyncDelete(pycFiles); - } - }, "Cleaning up .py files...", false, e.getData(Project.KEY)); - } + @Override + @RequiredUIAccess + public void actionPerformed(AnActionEvent e) { + PsiElement[] elements = e.getData(PsiElement.KEY_OF_ARRAY); + if (elements == null) { + return; + } + List pycFiles = new ArrayList<>(); + ProgressManager.getInstance().runProcessWithProgressSynchronously( + () -> { + for (PsiElement element : elements) { + PsiDirectory dir = (PsiDirectory) element; + collectPycFiles(new File(dir.getVirtualFile().getPath()), pycFiles); + } + Application.get().getInstance(AsyncFileService.class).asyncDelete(pycFiles); + }, + "Cleaning up .py files...", + false, + e.getData(Project.KEY) + ); + } - @Override - public void update(AnActionEvent e) - { - if(e.getPresentation().isVisible()) - { - final PsiElement[] elements = e.getData(LangDataKeys.PSI_ELEMENT_ARRAY); - e.getPresentation().setEnabled(isAllDirectories(elements)); - } - } + @Override + public void update(AnActionEvent e) { + if (e.getPresentation().isVisible()) { + PsiElement[] elements = e.getData(PsiElement.KEY_OF_ARRAY); + e.getPresentation().setEnabled(isAllDirectories(elements)); + } + } } diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/actions/CreatePackageAction.java b/python-impl/src/main/java/com/jetbrains/python/impl/actions/CreatePackageAction.java index a9def002..d0024903 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/actions/CreatePackageAction.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/actions/CreatePackageAction.java @@ -13,18 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.jetbrains.python.impl.actions; import com.jetbrains.python.PyNames; import consulo.fileTemplate.FileTemplate; import consulo.fileTemplate.FileTemplateManager; import consulo.fileTemplate.FileTemplateUtil; -import consulo.ide.IdeBundle; import consulo.ide.IdeView; import consulo.ide.impl.idea.ide.actions.CreateDirectoryOrPackageHandler; +import consulo.ide.localize.IdeLocalize; import consulo.ide.util.DirectoryChooserUtil; -import consulo.language.editor.CommonDataKeys; import consulo.language.psi.PsiDirectory; import consulo.language.psi.PsiFile; import consulo.language.psi.PsiFileFactory; @@ -34,98 +32,112 @@ import consulo.platform.base.icon.PlatformIconGroup; import consulo.project.Project; import consulo.python.module.extension.PyModuleExtension; +import consulo.ui.annotation.RequiredUIAccess; import consulo.ui.ex.action.AnActionEvent; import consulo.ui.ex.action.DumbAwareAction; import consulo.ui.ex.awt.Messages; +import consulo.ui.ex.awt.UIUtil; import consulo.ui.image.Image; +import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; /** * @author yole */ public class CreatePackageAction extends DumbAwareAction { - private static final Logger LOG = Logger.getInstance(CreatePackageAction.class); + private static final Logger LOG = Logger.getInstance(CreatePackageAction.class); - @Override - public void actionPerformed(AnActionEvent e) { - final IdeView view = e.getData(IdeView.KEY); - if (view == null) { - return; - } - final Project project = e.getData(CommonDataKeys.PROJECT); - final PsiDirectory directory = DirectoryChooserUtil.getOrChooseDirectory(view); + @Override + @RequiredUIAccess + public void actionPerformed(AnActionEvent e) { + IdeView view = e.getData(IdeView.KEY); + if (view == null) { + return; + } + final Project project = e.getData(Project.KEY); + final PsiDirectory directory = DirectoryChooserUtil.getOrChooseDirectory(view); - if (directory == null) return; - CreateDirectoryOrPackageHandler validator = new CreateDirectoryOrPackageHandler(project, directory, consulo.ide.impl.actions.CreateDirectoryOrPackageType.Package, ".") { - @Override - protected void createDirectories(String subDirName) { - super.createDirectories(subDirName); - PsiFileSystemItem element = getCreatedElement(); - if (element instanceof PsiDirectory) { - createInitPyInHierarchy((PsiDirectory)element, directory); + if (directory == null) { + return; + } + CreateDirectoryOrPackageHandler validator = + new CreateDirectoryOrPackageHandler(project, directory, consulo.ide.impl.actions.CreateDirectoryOrPackageType.Package, ".") { + @RequiredUIAccess + @Override + protected void createDirectories(String subDirName) { + super.createDirectories(subDirName); + PsiFileSystemItem element = getCreatedElement(); + if (element instanceof PsiDirectory) { + createInitPyInHierarchy((PsiDirectory) element, directory); + } + } + }; + Messages.showInputDialog( + project, + IdeLocalize.promptEnterANewPackageName().get(), + IdeLocalize.titleNewPackage().get(), + UIUtil.getQuestionIcon(), + "", + validator + ); + PsiFileSystemItem result = validator.getCreatedElement(); + if (result != null) { + view.selectElement(result); } - } - }; - Messages.showInputDialog(project, IdeBundle.message("prompt.enter.a.new.package.name"), - IdeBundle.message("title.new.package"), - Messages.getQuestionIcon(), "", validator); - final PsiFileSystemItem result = validator.getCreatedElement(); - if (result != null) { - view.selectElement(result); } - } - public static void createInitPyInHierarchy(PsiDirectory created, PsiDirectory ancestor) { - do { - createInitPy(created); - created = created.getParent(); - } while(created != null && created != ancestor); - } - - private static void createInitPy(PsiDirectory directory) { - final FileTemplateManager fileTemplateManager = FileTemplateManager.getInstance(directory.getProject()); - final FileTemplate template = fileTemplateManager.getInternalTemplate("Python Script"); - if (directory.findFile(PyNames.INIT_DOT_PY) != null) { - return; - } - if (template != null) { - try { - FileTemplateUtil.createFromTemplate(template, PyNames.INIT_DOT_PY, fileTemplateManager.getDefaultVariables(), directory); - } - catch (Exception e) { - LOG.error(e); - } - } - else { - final PsiFile file = PsiFileFactory.getInstance(directory.getProject()).createFileFromText(PyNames.INIT_DOT_PY, ""); - directory.add(file); + public static void createInitPyInHierarchy(PsiDirectory created, PsiDirectory ancestor) { + do { + createInitPy(created); + created = created.getParent(); + } + while (created != null && created != ancestor); } - } - @Override - public void update(AnActionEvent e) { - boolean enabled = isEnabled(e) && e.getPresentation().isEnabled(); - e.getPresentation().setVisible(enabled); - e.getPresentation().setEnabled(enabled); - } + @RequiredUIAccess + private static void createInitPy(PsiDirectory directory) { + FileTemplateManager fileTemplateManager = FileTemplateManager.getInstance(directory.getProject()); + FileTemplate template = fileTemplateManager.getInternalTemplate("Python Script"); + if (directory.findFile(PyNames.INIT_DOT_PY) != null) { + return; + } + if (template != null) { + try { + FileTemplateUtil.createFromTemplate(template, PyNames.INIT_DOT_PY, fileTemplateManager.getDefaultVariables(), directory); + } + catch (Exception e) { + LOG.error(e); + } + } + else { + PsiFile file = PsiFileFactory.getInstance(directory.getProject()).createFileFromText(PyNames.INIT_DOT_PY, ""); + directory.add(file); + } + } - @Nullable - @Override - protected Image getTemplateIcon() { - return PlatformIconGroup.nodesPackage(); - } + @Override + public void update(@Nonnull AnActionEvent e) { + boolean enabled = isEnabled(e) && e.getPresentation().isEnabled(); + e.getPresentation().setEnabledAndVisible(enabled); + } - private static boolean isEnabled(AnActionEvent e) { - Project project = e.getData(Project.KEY); - final IdeView ideView = e.getData(IdeView.KEY); - if (project == null || ideView == null) { - return false; + @Nullable + @Override + protected Image getTemplateIcon() { + return PlatformIconGroup.nodesPackage(); } - final PsiDirectory[] directories = ideView.getDirectories(); - if (directories.length == 0) { - return false; + + private static boolean isEnabled(AnActionEvent e) { + Project project = e.getData(Project.KEY); + IdeView ideView = e.getData(IdeView.KEY); + if (project == null || ideView == null) { + return false; + } + PsiDirectory[] directories = ideView.getDirectories(); + if (directories.length == 0) { + return false; + } + Module module = e.getData(Module.KEY); + return module != null && module.getExtension(PyModuleExtension.class) != null; } - Module module = e.getData(Module.KEY); - return module != null && module.getExtension(PyModuleExtension.class) != null; - } } diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/console/PyOpenDebugConsoleAction.java b/python-impl/src/main/java/com/jetbrains/python/impl/console/PyOpenDebugConsoleAction.java index 2bcdccf0..6abdc3b9 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/console/PyOpenDebugConsoleAction.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/console/PyOpenDebugConsoleAction.java @@ -21,9 +21,9 @@ import consulo.execution.ExecutionHelper; import consulo.execution.icon.ExecutionIconGroup; import consulo.execution.ui.RunContentDescriptor; -import consulo.language.editor.CommonDataKeys; import consulo.process.ProcessHandler; import consulo.project.Project; +import consulo.ui.annotation.RequiredUIAccess; import consulo.ui.ex.action.AnAction; import consulo.ui.ex.action.AnActionEvent; import jakarta.annotation.Nonnull; @@ -35,53 +35,65 @@ * @author traff */ public class PyOpenDebugConsoleAction extends AnAction implements DumbAware { + public PyOpenDebugConsoleAction() { + super(); + getTemplatePresentation().setIcon(ExecutionIconGroup.console()); + } - public PyOpenDebugConsoleAction() { - super(); - getTemplatePresentation().setIcon(ExecutionIconGroup.console()); - } - - @Override - public void update(final AnActionEvent e) { - e.getPresentation().setVisible(false); - e.getPresentation().setEnabled(true); - final Project project = e.getData(CommonDataKeys.PROJECT); - if (project != null) { - e.getPresentation().setVisible(getConsoles(project).size() > 0); + @Override + public void update(AnActionEvent e) { + e.getPresentation().setVisible(false); + e.getPresentation().setEnabled(true); + Project project = e.getData(Project.KEY); + if (project != null) { + e.getPresentation().setVisible(getConsoles(project).size() > 0); + } } - } - @Override - public void actionPerformed(final AnActionEvent e) { - final Project project = e.getData(CommonDataKeys.PROJECT); - if (project != null) { - selectRunningProcess(e.getDataContext(), project, view -> { - view.enableConsole(false); - ApplicationIdeFocusManager.getInstance().getInstanceForProject(project).requestFocus(view.getPydevConsoleView().getComponent(), true); - }); + @Override + @RequiredUIAccess + public void actionPerformed(AnActionEvent e) { + Project project = e.getData(Project.KEY); + if (project != null) { + selectRunningProcess(e.getDataContext(), project, view -> { + view.enableConsole(false); + ApplicationIdeFocusManager.getInstance() + .getInstanceForProject(project) + .requestFocus(view.getPydevConsoleView().getComponent(), true); + }); + } } - } - private static void selectRunningProcess(@Nonnull DataContext dataContext, - @Nonnull Project project, - final Consumer consumer) { - Collection consoles = getConsoles(project); + private static void selectRunningProcess( + @Nonnull DataContext dataContext, + @Nonnull Project project, + Consumer consumer + ) { + Collection consoles = getConsoles(project); - ExecutionHelper.selectContentDescriptor(dataContext, project, consoles, "Select running python process", descriptor -> { - if (descriptor != null && descriptor.getExecutionConsole() instanceof PythonDebugLanguageConsoleView) { - consumer.accept((PythonDebugLanguageConsoleView)descriptor.getExecutionConsole()); - } - }); - } + ExecutionHelper.selectContentDescriptor( + dataContext, + project, + consoles, + "Select running python process", + descriptor -> { + if (descriptor != null && descriptor.getExecutionConsole() instanceof PythonDebugLanguageConsoleView consoleView) { + consumer.accept(consoleView); + } + } + ); + } - private static Collection getConsoles(Project project) { - return ExecutionHelper.findRunningConsole(project, - dom -> dom.getExecutionConsole() instanceof PythonDebugLanguageConsoleView && isAlive(dom)); - } + private static Collection getConsoles(Project project) { + return ExecutionHelper.findRunningConsole( + project, + dom -> dom.getExecutionConsole() instanceof PythonDebugLanguageConsoleView && isAlive(dom) + ); + } - private static boolean isAlive(RunContentDescriptor dom) { - ProcessHandler processHandler = dom.getProcessHandler(); - return processHandler != null && !processHandler.isProcessTerminated(); - } + private static boolean isAlive(RunContentDescriptor dom) { + ProcessHandler processHandler = dom.getProcessHandler(); + return processHandler != null && !processHandler.isProcessTerminated(); + } } diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/console/PydevConsoleRunnerImpl.java b/python-impl/src/main/java/com/jetbrains/python/impl/console/PydevConsoleRunnerImpl.java index 29c8b717..aad496a2 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/console/PydevConsoleRunnerImpl.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/console/PydevConsoleRunnerImpl.java @@ -19,7 +19,6 @@ import com.google.common.collect.Lists; import com.jetbrains.python.console.pydev.ConsoleCommunicationListener; import com.jetbrains.python.impl.PythonHelper; -import com.jetbrains.python.impl.PythonIcons; import com.jetbrains.python.impl.console.actions.ShowVarsAction; import com.jetbrains.python.impl.debugger.PyDebugRunner; import com.jetbrains.python.impl.run.PythonCommandLineState; @@ -27,9 +26,7 @@ import com.jetbrains.python.impl.run.PythonTracebackFilter; import com.jetbrains.python.run.PythonRunParams; import consulo.annotation.access.RequiredWriteAction; -import consulo.application.AllIcons; import consulo.application.Application; -import consulo.application.ApplicationManager; import consulo.application.dumb.DumbAware; import consulo.application.progress.ProgressIndicator; import consulo.application.progress.ProgressManager; @@ -61,13 +58,13 @@ import consulo.ide.impl.idea.execution.console.ConsoleHistoryController; import consulo.ide.impl.idea.openapi.actionSystem.ex.ActionImplUtil; import consulo.ide.impl.idea.util.PathMappingSettings; -import consulo.language.editor.CommonDataKeys; -import consulo.language.editor.LangDataKeys; import consulo.language.editor.completion.lookup.LookupManager; import consulo.language.file.light.LightVirtualFile; import consulo.language.psi.PsiFile; +import consulo.localize.LocalizeValue; import consulo.logging.Logger; import consulo.module.Module; +import consulo.platform.base.icon.PlatformIconGroup; import consulo.process.ExecutionException; import consulo.process.KillableProcessHandler; import consulo.process.ProcessHandler; @@ -78,6 +75,7 @@ import consulo.process.event.ProcessEvent; import consulo.process.event.ProcessListener; import consulo.project.Project; +import consulo.python.psi.icon.PythonPsiIconGroup; import consulo.ui.annotation.RequiredUIAccess; import consulo.ui.ex.JBColor; import consulo.ui.ex.MessageCategory; @@ -118,7 +116,8 @@ import static consulo.execution.ui.console.language.AbstractConsoleRunnerWithHistory.registerActionShortcuts; /** - * @author traff, oleg + * @author traff + * @author oleg */ public class PydevConsoleRunnerImpl implements PydevConsoleRunner { public static final String WORKING_DIR_ENV = "WORKING_DIR_AND_PYTHON_PATHS"; @@ -129,6 +128,7 @@ public class PydevConsoleRunnerImpl implements PydevConsoleRunner { public static final String PYDEV_PYDEVCONSOLE_PY = "pydev/pydevconsole.py"; public static final int PORTS_WAITING_TIMEOUT = 20000; private static final String CONSOLE_FEATURE = "python.console"; + @Nonnull private final Project myProject; private final String myTitle; private final String myWorkingDir; @@ -148,20 +148,21 @@ public class PydevConsoleRunnerImpl implements PydevConsoleRunner { private final PyConsoleOptions.PyConsoleSettings myConsoleSettings; private String[] myStatementsToExecute = ArrayUtil.EMPTY_STRING_ARRAY; - private static final long APPROPRIATE_TO_WAIT = 60000; private String myConsoleTitle = null; private PythonConsoleView myConsoleView; - public PydevConsoleRunnerImpl(@Nonnull final Project project, - @Nonnull Sdk sdk, - @Nonnull final PyConsoleType consoleType, - @Nullable final String workingDir, - Map environmentVariables, - @Nonnull PyConsoleOptions.PyConsoleSettings settingsProvider, - @Nonnull Consumer rerunAction, - String... statementsToExecute) { + public PydevConsoleRunnerImpl( + @Nonnull Project project, + @Nonnull Sdk sdk, + @Nonnull PyConsoleType consoleType, + @Nullable String workingDir, + Map environmentVariables, + @Nonnull PyConsoleOptions.PyConsoleSettings settingsProvider, + @Nonnull Consumer rerunAction, + String... statementsToExecute + ) { myProject = project; mySdk = sdk; myTitle = consoleType.getTitle(); @@ -177,7 +178,7 @@ public void setConsoleTitle(String consoleTitle) { myConsoleTitle = consoleTitle; } - private List fillToolBarActions(final DefaultActionGroup toolbarActions, final RunContentDescriptor contentDescriptor) { + private List fillToolBarActions(DefaultActionGroup toolbarActions, RunContentDescriptor contentDescriptor) { //toolbarActions.add(backspaceHandlingAction); toolbarActions.add(createRerunAction()); @@ -191,10 +192,12 @@ private List fillToolBarActions(final DefaultActionGroup toolbarAction actions.add(createCloseAction(contentDescriptor)); // run action - actions.add(new ConsoleExecuteAction(myConsoleView, + actions.add(new ConsoleExecuteAction( + myConsoleView, myConsoleExecuteActionHandler, myConsoleExecuteActionHandler.getEmptyExecuteAction(), - myConsoleExecuteActionHandler)); + myConsoleExecuteActionHandler + )); // Help actions.add(CommonActionsManager.getInstance().createHelpAction("interactive_console")); @@ -220,6 +223,7 @@ private List fillToolBarActions(final DefaultActionGroup toolbarAction } @Override + @RequiredUIAccess public void open() { ToolWindow toolWindow = PythonConsoleToolWindow.getInstance(myProject).getToolWindow(); if (toolWindow != null) { @@ -247,16 +251,15 @@ public void runSync() { ExecutionHelper.showErrors(myProject, Collections.singletonList(e), "Python Console", null); } - ProgressManager.getInstance().run(new Task.Backgroundable(myProject, "Connecting to Console", false) { + ProgressManager.getInstance().run(new Task.Backgroundable(myProject, LocalizeValue.localizeTODO("Connecting to Console"), false) { @Override - public void run(@Nonnull final ProgressIndicator indicator) { - indicator.setText("Connecting to console..."); + public void run(@Nonnull ProgressIndicator indicator) { + indicator.setTextValue(LocalizeValue.localizeTODO("Connecting to console...")); connect(myStatementsToExecute); } }); } - @Override public void run() { FileDocumentManager.getInstance().saveAllDocuments(); @@ -268,30 +271,31 @@ public void run() { myGeneralCommandLine = createCommandLine(mySdk, myEnvironmentVariables, myWorkingDir, myPorts); myCommandLine = myGeneralCommandLine.getCommandLineString(); - UIUtil.invokeLaterIfNeeded(() -> ProgressManager.getInstance().run(new Task.Backgroundable(myProject, "Connecting to Console", false) { - @Override - public void run(@Nonnull final ProgressIndicator indicator) { - indicator.setText("Connecting to console..."); - try { - initAndRun(); - connect(myStatementsToExecute); - } - catch (final Exception e) { - LOG.warn("Error running console", e); - UIUtil.invokeAndWaitIfNeeded((Runnable) () -> showErrorsInConsole(e)); + UIUtil.invokeLaterIfNeeded(() -> ProgressManager.getInstance().run( + new Task.Backgroundable(myProject, LocalizeValue.localizeTODO("Connecting to Console"), false) { + @Override + public void run(@Nonnull ProgressIndicator indicator) { + indicator.setTextValue(LocalizeValue.localizeTODO("Connecting to console...")); + try { + initAndRun(); + connect(myStatementsToExecute); + } + catch (Exception e) { + LOG.warn("Error running console", e); + UIUtil.invokeAndWaitIfNeeded((Runnable) () -> showErrorsInConsole(e)); + } } } - })); + )); } private void showErrorsInConsole(Exception e) { - DefaultActionGroup actionGroup = new DefaultActionGroup(createRerunAction()); - final ActionToolbar actionToolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, actionGroup, false); + ActionToolbar actionToolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, actionGroup, false); // Runner creating - final JPanel panel = new JPanel(new BorderLayout()); + JPanel panel = new JPanel(new BorderLayout()); panel.add(actionToolbar.getComponent(), BorderLayout.WEST); NewErrorTreeViewPanelFactory panelFactory = myProject.getApplication().getInstance(NewErrorTreeViewPanelFactory.class); @@ -306,7 +310,7 @@ private void showErrorsInConsole(Exception e) { panel.add(errorViewPanel.getComponent(), BorderLayout.CENTER); - final RunContentDescriptor contentDescriptor = new RunContentDescriptor(null, myProcessHandler, panel, "Error running console"); + RunContentDescriptor contentDescriptor = new RunContentDescriptor(null, myProcessHandler, panel, "Error running console"); actionGroup.add(createCloseAction(contentDescriptor)); @@ -329,7 +333,7 @@ private static Executor getExecutor() { } private static int[] findAvailablePorts(Project project, PyConsoleType consoleType) { - final int[] ports; + int[] ports; try { // File "pydev/console/pydevconsole.py", line 223, in // port, client_port = sys.argv[1:3] @@ -342,25 +346,33 @@ private static int[] findAvailablePorts(Project project, PyConsoleType consoleTy return ports; } - protected GeneralCommandLine createCommandLine(@Nonnull final Sdk sdk, - @Nonnull final Map environmentVariables, - String workingDir, - int[] ports) { + protected GeneralCommandLine createCommandLine( + @Nonnull Sdk sdk, + @Nonnull Map environmentVariables, + String workingDir, + int[] ports + ) { return doCreateConsoleCmdLine(sdk, environmentVariables, workingDir, ports, PythonHelper.CONSOLE); } @Nonnull - protected GeneralCommandLine doCreateConsoleCmdLine(Sdk sdk, - Map environmentVariables, - String workingDir, - int[] ports, - PythonHelper helper) { - GeneralCommandLine cmd = PythonCommandLineState.createPythonCommandLine(myProject, - new PythonConsoleRunParams(myConsoleSettings, + protected GeneralCommandLine doCreateConsoleCmdLine( + Sdk sdk, + Map environmentVariables, + String workingDir, + int[] ports, + PythonHelper helper + ) { + GeneralCommandLine cmd = PythonCommandLineState.createPythonCommandLine( + myProject, + new PythonConsoleRunParams( + myConsoleSettings, workingDir, sdk, - environmentVariables), - false); + environmentVariables + ), + false + ); cmd.withWorkDirectory(myWorkingDir); ParamsGroup group = cmd.getParametersList().getParamsGroup(PythonCommandLineState.GROUP_SCRIPT); @@ -395,18 +407,14 @@ private ProcessHandler createProcess() throws ExecutionException { return handler; } - - private ProcessHandler createProcessHandler(final ProcessHandler process) { - myProcessHandler = - new PyConsoleProcessHandler(process, myConsoleView, myPydevConsoleCommunication); - + private ProcessHandler createProcessHandler(ProcessHandler process) { + myProcessHandler = new PyConsoleProcessHandler(process, myConsoleView, myPydevConsoleCommunication); return myProcessHandler; } - private void initAndRun() throws ExecutionException { // Create Server process - final ProcessHandler process = createProcess(); + ProcessHandler process = createProcess(); UIUtil.invokeLaterIfNeeded(() -> { // Init console view myConsoleView = createConsoleView(); @@ -438,11 +446,11 @@ public void processTerminated(ProcessEvent event) { protected void createContentDescriptorAndActions() { // Runner creating - final DefaultActionGroup toolbarActions = new DefaultActionGroup(); - final ActionToolbar actionToolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, toolbarActions, false); + DefaultActionGroup toolbarActions = new DefaultActionGroup(); + ActionToolbar actionToolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, toolbarActions, false); // Runner creating - final JPanel panel = new JPanel(new BorderLayout()); + JPanel panel = new JPanel(new BorderLayout()); panel.add(actionToolbar.getComponent(), BorderLayout.WEST); panel.add(myConsoleView.getComponent(), BorderLayout.CENTER); @@ -454,10 +462,10 @@ protected void createContentDescriptorAndActions() { @Override protected List getActiveConsoles(@Nonnull String consoleTitle) { PythonConsoleToolWindow toolWindow = PythonConsoleToolWindow.getInstance(myProject); - if (toolWindow != null && toolWindow.getToolWindow() != null) { + if (toolWindow.getToolWindow() != null) { return Lists.newArrayList(toolWindow.getToolWindow().getContentManager().getContents()) .stream() - .map(c -> c.getDisplayName()) + .map(Content::getDisplayName) .collect(Collectors.toList()); } else { @@ -467,14 +475,13 @@ protected List getActiveConsoles(@Nonnull String consoleTitle) { }.makeTitle(); } - final RunContentDescriptor contentDescriptor = new RunContentDescriptor(myConsoleView, myProcessHandler, panel, myConsoleTitle, null); + RunContentDescriptor contentDescriptor = new RunContentDescriptor(myConsoleView, myProcessHandler, panel, myConsoleTitle, null); contentDescriptor.setFocusComputable(() -> myConsoleView.getConsoleEditor().getContentComponent()); contentDescriptor.setAutoFocusContent(true); - // tool bar actions - final List actions = fillToolBarActions(toolbarActions, contentDescriptor); + List actions = fillToolBarActions(toolbarActions, contentDescriptor); registerActionShortcuts(actions, myConsoleView.getConsoleEditor().getComponent()); registerActionShortcuts(actions, panel); getConsoleView().addConsoleFolding(false); @@ -482,9 +489,9 @@ protected List getActiveConsoles(@Nonnull String consoleTitle) { showContentDescriptor(contentDescriptor); } - private void connect(final String[] statements2execute) { + private void connect(String[] statements2execute) { if (handshake()) { - ApplicationManager.getApplication().invokeLater(() -> { + Application.get().invokeLater(() -> { // Propagate console communication to language console final PythonConsoleView consoleView = myConsoleView; @@ -522,31 +529,29 @@ protected AnAction createRerunAction() { private AnAction createInterruptAction() { AnAction anAction = new AnAction() { - @RequiredUIAccess @Override - public void actionPerformed(@Nonnull final AnActionEvent e) { + @RequiredUIAccess + public void actionPerformed(@Nonnull AnActionEvent e) { if (myPydevConsoleCommunication.isExecuting() || myPydevConsoleCommunication.isWaitingForInput()) { myConsoleView.print("^C", ProcessOutputTypes.SYSTEM); myPydevConsoleCommunication.interrupt(); } else { Document document = myConsoleView.getConsoleEditor().getDocument(); - if (!(document.getTextLength() == 0)) { - ApplicationManager.getApplication() - .runWriteAction(() -> CommandProcessor.getInstance() - .runUndoTransparentAction(() -> document.deleteString(0, - document.getLineEndOffset( - document.getLineCount() - 1)))); + if (document.getTextLength() != 0) { + Application.get().runWriteAction(() -> CommandProcessor.getInstance().runUndoTransparentAction( + () -> document.deleteString(0, document.getLineEndOffset(document.getLineCount() - 1)) + )); } - } } - @RequiredUIAccess @Override - public void update(final AnActionEvent e) { + @RequiredUIAccess + public void update(AnActionEvent e) { EditorEx consoleEditor = myConsoleView.getConsoleEditor(); - boolean enabled = IJSwingUtilities.hasFocus(consoleEditor.getComponent()) && !consoleEditor.getSelectionModel().hasSelection(); + boolean enabled = + IJSwingUtilities.hasFocus(consoleEditor.getComponent()) && !consoleEditor.getSelectionModel().hasSelection(); e.getPresentation().setEnabled(enabled); } }; @@ -556,7 +561,7 @@ public void update(final AnActionEvent e) { } private AnAction createTabCompletionAction() { - final AnAction runCompletions = new AnAction() { + AnAction runCompletions = new AnAction() { @RequiredUIAccess @Override public void actionPerformed(@Nonnull AnActionEvent e) { @@ -594,7 +599,6 @@ public void update(@Nonnull AnActionEvent e) { return runCompletions; } - private boolean isIndentSubstring(String text) { int indentSize = myConsoleExecuteActionHandler.getPythonIndent(); return text.length() >= indentSize && CharMatcher.whitespace().matchesAllOf(text.substring(text.length() - indentSize)); @@ -634,15 +638,14 @@ private boolean handshake() { private AnAction createStopAction() { AnAction generalStopAction = ActionManager.getInstance().getAction(IdeActions.ACTION_STOP_PROGRAM); - final AnAction stopAction = new DumbAwareAction() { - @RequiredUIAccess + AnAction stopAction = new DumbAwareAction() { @Override public void update(@Nonnull AnActionEvent e) { generalStopAction.update(e); } - @RequiredUIAccess @Override + @RequiredUIAccess public void actionPerformed(@Nonnull AnActionEvent e) { e = stopConsole(e); @@ -656,15 +659,14 @@ public void actionPerformed(@Nonnull AnActionEvent e) { private AnAction createCloseAction(final RunContentDescriptor descriptor) { final AnAction generalCloseAction = new CloseAction(getExecutor(), descriptor, myProject); - final AnAction stopAction = new DumbAwareAction() { - @RequiredUIAccess + AnAction stopAction = new DumbAwareAction() { @Override public void update(@Nonnull AnActionEvent e) { generalCloseAction.update(e); } - @RequiredUIAccess @Override + @RequiredUIAccess public void actionPerformed(@Nonnull AnActionEvent e) { e = stopConsole(e); @@ -679,7 +681,7 @@ public void actionPerformed(@Nonnull AnActionEvent e) { protected void clearContent(RunContentDescriptor descriptor) { PythonConsoleToolWindow toolWindow = PythonConsoleToolWindow.getInstance(myProject); - if (toolWindow != null && toolWindow.getToolWindow() != null) { + if (toolWindow.getToolWindow() != null) { Content content = toolWindow.getToolWindow().getContentManager().findContent(descriptor.getDisplayName()); assert content != null; toolWindow.getToolWindow().getContentManager().removeContent(content, true); @@ -689,7 +691,14 @@ protected void clearContent(RunContentDescriptor descriptor) { private AnActionEvent stopConsole(AnActionEvent e) { if (myPydevConsoleCommunication != null) { e = - new AnActionEvent(e.getInputEvent(), e.getDataContext(), e.getPlace(), e.getPresentation(), e.getActionManager(), e.getModifiers()); + new AnActionEvent( + e.getInputEvent(), + e.getDataContext(), + e.getPlace(), + e.getPresentation(), + e.getActionManager(), + e.getModifiers() + ); try { closeCommunication(); // waiting for REPL communication before destroying process handler @@ -718,8 +727,8 @@ public boolean isEnabled(Editor editor, DataContext dataContext) { return mySplitLineAction.getHandler().isEnabled(editor, dataContext); } - @RequiredWriteAction @Override + @RequiredWriteAction public void executeWriteAction(Editor editor, @Nullable Caret caret, DataContext dataContext) { ((EditorWriteActionHandler) mySplitLineAction.getHandler()).executeWriteAction(editor, caret, dataContext); editor.getCaretModel().getCurrentCaret().moveCaretRelatively(0, 1, false, true); @@ -744,6 +753,7 @@ private void closeCommunication() { } @Nonnull + @RequiredUIAccess protected PydevConsoleExecuteActionHandler createExecuteActionHandler() { myConsoleExecuteActionHandler = new PydevConsoleExecuteActionHandler(myConsoleView, myProcessHandler, myPydevConsoleCommunication); myConsoleExecuteActionHandler.setEnabled(false); @@ -758,8 +768,8 @@ public PydevConsoleCommunication getPydevConsoleCommunication() { static VirtualFile getConsoleFile(PsiFile psiFile) { VirtualFile file = psiFile.getViewProvider().getVirtualFile(); - if (file instanceof LightVirtualFile) { - file = ((LightVirtualFile) file).getOriginalFile(); + if (file instanceof LightVirtualFile lightVirtualFile) { + file = lightVirtualFile.getOriginalFile(); } return file; } @@ -781,26 +791,25 @@ public PydevConsoleExecuteActionHandler getConsoleExecuteActionHandler() { return myConsoleExecuteActionHandler; } - private static class RestartAction extends AnAction { private PydevConsoleRunnerImpl myConsoleRunner; - private RestartAction(PydevConsoleRunnerImpl runner) { copyFrom(ActionManager.getInstance().getAction(IdeActions.ACTION_RERUN)); - getTemplatePresentation().setIcon(AllIcons.Actions.Restart); + getTemplatePresentation().setIcon(PlatformIconGroup.actionsRestart()); myConsoleRunner = runner; } - @RequiredUIAccess @Override + @RequiredUIAccess public void actionPerformed(@Nonnull AnActionEvent e) { myConsoleRunner.rerun(); } } private void rerun() { - new Task.Backgroundable(myProject, "Restarting Console", true) { + Application application = myProject.getApplication(); + new Task.Backgroundable(myProject, LocalizeValue.localizeTODO("Restarting Console"), true) { @Override public void run(@Nonnull ProgressIndicator indicator) { if (myProcessHandler instanceof KillableProcessHandler killableProcessHandler) { @@ -813,18 +822,21 @@ public void run(@Nonnull ProgressIndicator indicator) { myProcessHandler.waitFor(); } - Application.get().invokeLater(() -> myRerunAction.accept(myConsoleTitle), Application.get().getDefaultModalityState()); + application.invokeLater(() -> myRerunAction.accept(myConsoleTitle), application.getDefaultModalityState()); } }.queue(); } - private class ConnectDebuggerAction extends ToggleAction implements DumbAware { private boolean mySelected = false; private XDebugSession mySession = null; public ConnectDebuggerAction() { - super("Attach Debugger", "Enables tracing of code executed in console", ExecutionDebugIconGroup.actionStartdebugger()); + super( + LocalizeValue.localizeTODO("Attach Debugger"), + LocalizeValue.localizeTODO("Enables tracing of code executed in console"), + ExecutionDebugIconGroup.actionStartdebugger() + ); } @Override @@ -843,6 +855,7 @@ public void update(@Nonnull AnActionEvent e) { } @Override + @RequiredUIAccess public void setSelected(@Nonnull AnActionEvent e, boolean state) { mySelected = state; @@ -861,83 +874,88 @@ public void setSelected(@Nonnull AnActionEvent e, boolean state) { } } - private static class NewConsoleAction extends AnAction implements DumbAware { public NewConsoleAction() { - super("New Console", "Creates new python console", AllIcons.General.Add); + super( + LocalizeValue.localizeTODO("New Console"), + LocalizeValue.localizeTODO("Creates new python console"), + PlatformIconGroup.generalAdd() + ); } - @RequiredUIAccess @Override public void update(AnActionEvent e) { e.getPresentation().setEnabled(true); } - @RequiredUIAccess @Override + @RequiredUIAccess public void actionPerformed(AnActionEvent e) { PydevConsoleRunner runner = - PythonConsoleRunnerFactory.getInstance().createConsoleRunner(e.getData(CommonDataKeys.PROJECT), e.getData(LangDataKeys.MODULE)); + PythonConsoleRunnerFactory.getInstance().createConsoleRunner(e.getRequiredData(Project.KEY), e.getData(Module.KEY)); runner.run(); } } private XDebugSession connectToDebugger() throws ExecutionException { - final ServerSocket serverSocket = PythonCommandLineState.createServerSocket(); - - final XDebugSession session = XDebuggerManager.getInstance(myProject) - .startSessionAndShowTab("Python Console Debugger", - PythonIcons.Python.Python, - null, - true, - xDebugSession -> { - PythonDebugLanguageConsoleView debugConsoleView = - new PythonDebugLanguageConsoleView(myProject, mySdk); - - PyConsoleDebugProcessHandler consoleDebugProcessHandler = - new PyConsoleDebugProcessHandler(myProcessHandler); - - PyConsoleDebugProcess consoleDebugProcess = - new PyConsoleDebugProcess(xDebugSession, - serverSocket, - debugConsoleView, - consoleDebugProcessHandler); - - PythonDebugConsoleCommunication communication = - PyDebugRunner.initDebugConsoleView(myProject, - consoleDebugProcess, - debugConsoleView, - consoleDebugProcessHandler, - xDebugSession); - - communication.addCommunicationListener(new ConsoleCommunicationListener() { - @Override - public void commandExecuted(boolean more) { - xDebugSession.rebuildViews(); - } - - @Override - public void inputRequested() { - } - }); - - myPydevConsoleCommunication.setDebugCommunication(communication); - debugConsoleView.attachToProcess(consoleDebugProcessHandler); - - consoleDebugProcess.waitForNextConnection(); - - try { - consoleDebugProcess.connect(myPydevConsoleCommunication); + ServerSocket serverSocket = PythonCommandLineState.createServerSocket(); + + XDebugSession session = XDebuggerManager.getInstance(myProject).startSessionAndShowTab( + "Python Console Debugger", + PythonPsiIconGroup.python(), + null, + true, + xDebugSession -> { + PythonDebugLanguageConsoleView debugConsoleView = new PythonDebugLanguageConsoleView(myProject, mySdk); + + PyConsoleDebugProcessHandler consoleDebugProcessHandler = new PyConsoleDebugProcessHandler(myProcessHandler); + + PyConsoleDebugProcess consoleDebugProcess = new PyConsoleDebugProcess( + xDebugSession, + serverSocket, + debugConsoleView, + consoleDebugProcessHandler + ); + + PythonDebugConsoleCommunication communication = PyDebugRunner.initDebugConsoleView( + myProject, + consoleDebugProcess, + debugConsoleView, + consoleDebugProcessHandler, + xDebugSession + ); + + communication.addCommunicationListener(new ConsoleCommunicationListener() { + @Override + public void commandExecuted(boolean more) { + xDebugSession.rebuildViews(); } - catch (Exception e) { - LOG.error(e); //TODO + + @Override + public void inputRequested() { } + }); - myProcessHandler.notifyTextAvailable("\nDebugger connected.\n", - ProcessOutputTypes.STDERR); + myPydevConsoleCommunication.setDebugCommunication(communication); + debugConsoleView.attachToProcess(consoleDebugProcessHandler); - return consoleDebugProcess; - }); + consoleDebugProcess.waitForNextConnection(); + + try { + consoleDebugProcess.connect(myPydevConsoleCommunication); + } + catch (Exception e) { + LOG.error(e); //TODO + } + + myProcessHandler.notifyTextAvailable( + "\nDebugger connected.\n", + ProcessOutputTypes.STDERR + ); + + return consoleDebugProcess; + } + ); return session; } @@ -962,10 +980,12 @@ private static class PythonConsoleRunParams implements PythonRunParams { private Sdk mySdk; private Map myEnvironmentVariables; - public PythonConsoleRunParams(@Nonnull PyConsoleOptions.PyConsoleSettings consoleSettings, - @Nonnull String workingDir, - @Nonnull Sdk sdk, - @Nonnull Map envs) { + public PythonConsoleRunParams( + @Nonnull PyConsoleOptions.PyConsoleSettings consoleSettings, + @Nonnull String workingDir, + @Nonnull Sdk sdk, + @Nonnull Map envs + ) { myConsoleSettings = consoleSettings; myWorkingDir = workingDir; mySdk = sdk; diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/console/RunPythonConsoleAction.java b/python-impl/src/main/java/com/jetbrains/python/impl/console/RunPythonConsoleAction.java index 5a3896e9..c18dbf34 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/console/RunPythonConsoleAction.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/console/RunPythonConsoleAction.java @@ -15,57 +15,49 @@ */ package com.jetbrains.python.impl.console; +import consulo.python.impl.icon.PythonImplIconGroup; import consulo.ui.ex.action.AnAction; import consulo.ui.ex.action.AnActionEvent; -import consulo.language.editor.CommonDataKeys; -import consulo.language.editor.LangDataKeys; import consulo.module.Module; import consulo.application.dumb.DumbAware; import consulo.project.Project; import consulo.content.bundle.Sdk; import consulo.util.lang.Pair; import consulo.ui.annotation.RequiredUIAccess; -import com.jetbrains.python.impl.PythonIcons; import jakarta.annotation.Nonnull; /** * @author oleg */ -public class RunPythonConsoleAction extends AnAction implements DumbAware -{ - - public RunPythonConsoleAction() - { - super(); - getTemplatePresentation().setIcon(PythonIcons.Python.PythonConsole); - } - - @RequiredUIAccess - @Override - public void update(final AnActionEvent e) - { - e.getPresentation().setVisible(true); - e.getPresentation().setEnabled(false); - final Project project = e.getData(CommonDataKeys.PROJECT); - if(project != null) - { - Pair sdkAndModule = PydevConsoleRunner.findPythonSdkAndModule(project, e.getData(LangDataKeys.MODULE)); - if(sdkAndModule.first != null) - { - e.getPresentation().setEnabled(true); - } - } - } - - @RequiredUIAccess - public void actionPerformed(@Nonnull final AnActionEvent e) - { - Project project = e.getRequiredData(CommonDataKeys.PROJECT); - - PythonConsoleRunnerFactory runnerFactory = PythonConsoleRunnerFactory.getInstance(); - - PydevConsoleRunner runner = runnerFactory.createConsoleRunner(project, e.getData(LangDataKeys.MODULE)); - runner.open(); - } +public class RunPythonConsoleAction extends AnAction implements DumbAware { + public RunPythonConsoleAction() { + super(); + getTemplatePresentation().setIcon(PythonImplIconGroup.pythonPythonconsole()); + } + + @Override + @RequiredUIAccess + public void update(AnActionEvent e) { + e.getPresentation().setVisible(true); + e.getPresentation().setEnabled(false); + Project project = e.getData(Project.KEY); + if (project != null) { + Pair sdkAndModule = PydevConsoleRunner.findPythonSdkAndModule(project, e.getData(Module.KEY)); + if (sdkAndModule.first != null) { + e.getPresentation().setEnabled(true); + } + } + } + + @Override + @RequiredUIAccess + public void actionPerformed(@Nonnull AnActionEvent e) { + Project project = e.getRequiredData(Project.KEY); + + PythonConsoleRunnerFactory runnerFactory = PythonConsoleRunnerFactory.getInstance(); + + PydevConsoleRunner runner = runnerFactory.createConsoleRunner(project, e.getData(Module.KEY)); + runner.open(); + } } diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/hierarchy/PyTypeHierachyProvider.java b/python-impl/src/main/java/com/jetbrains/python/impl/hierarchy/PyTypeHierachyProvider.java index cd39e62a..2e865581 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/hierarchy/PyTypeHierachyProvider.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/hierarchy/PyTypeHierachyProvider.java @@ -13,17 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.jetbrains.python.impl.hierarchy; import com.jetbrains.python.PythonLanguage; import com.jetbrains.python.psi.PyClass; +import consulo.annotation.access.RequiredReadAction; import consulo.annotation.component.ExtensionImpl; import consulo.codeEditor.Editor; import consulo.dataContext.DataContext; import consulo.ide.impl.idea.ide.hierarchy.TypeHierarchyBrowserBase; import consulo.language.Language; -import consulo.language.editor.CommonDataKeys; import consulo.language.editor.hierarchy.HierarchyBrowser; import consulo.language.editor.hierarchy.TypeHierarchyProvider; import consulo.language.psi.PsiElement; @@ -34,41 +33,44 @@ import jakarta.annotation.Nullable; /** - * Created by IntelliJ IDEA. - * User: Alexey.Ivanov - * Date: Jul 31, 2009 - * Time: 6:00:21 PM + * @author Alexey.Ivanov + * @since 2009-07-31 */ @ExtensionImpl public class PyTypeHierachyProvider implements TypeHierarchyProvider { - @Nullable - public PsiElement getTarget(@Nonnull DataContext dataContext) { - PsiElement element = dataContext.getData(CommonDataKeys.PSI_ELEMENT); - if (element == null) { - final Editor editor = dataContext.getData(CommonDataKeys.EDITOR); - final PsiFile file = dataContext.getData(CommonDataKeys.PSI_FILE); - if (editor != null && file != null) { - element = file.findElementAt(editor.getCaretModel().getOffset()); - } - } - if (!(element instanceof PyClass)) { - element = PsiTreeUtil.getParentOfType(element, PyClass.class); + @Nullable + @Override + @RequiredReadAction + public PsiElement getTarget(@Nonnull DataContext dataContext) { + PsiElement element = dataContext.getData(PsiElement.KEY); + if (element == null) { + Editor editor = dataContext.getData(Editor.KEY); + PsiFile file = dataContext.getData(PsiFile.KEY); + if (editor != null && file != null) { + element = file.findElementAt(editor.getCaretModel().getOffset()); + } + } + if (!(element instanceof PyClass)) { + element = PsiTreeUtil.getParentOfType(element, PyClass.class); + } + return element; } - return element; - } - @Nonnull - public HierarchyBrowser createHierarchyBrowser(PsiElement target) { - return new PyTypeHierarchyBrowser((PyClass)target); - } + @Nonnull + @Override + public HierarchyBrowser createHierarchyBrowser(PsiElement target) { + return new PyTypeHierarchyBrowser((PyClass) target); + } - public void browserActivated(@Nonnull HierarchyBrowser hierarchyBrowser) { - ((PyTypeHierarchyBrowser)hierarchyBrowser).changeView(TypeHierarchyBrowserBase.TYPE_HIERARCHY_TYPE); - } + @Override + @RequiredReadAction + public void browserActivated(@Nonnull HierarchyBrowser hierarchyBrowser) { + ((PyTypeHierarchyBrowser) hierarchyBrowser).changeView(TypeHierarchyBrowserBase.TYPE_HIERARCHY_TYPE); + } - @Nonnull - @Override - public Language getLanguage() { - return PythonLanguage.INSTANCE; - } + @Nonnull + @Override + public Language getLanguage() { + return PythonLanguage.INSTANCE; + } } diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/packaging/PyManagePackagesAction.java b/python-impl/src/main/java/com/jetbrains/python/impl/packaging/PyManagePackagesAction.java index 9142705f..1519410e 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/packaging/PyManagePackagesAction.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/packaging/PyManagePackagesAction.java @@ -13,12 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.jetbrains.python.impl.packaging; +import consulo.ui.annotation.RequiredUIAccess; import consulo.ui.ex.action.AnAction; import consulo.ui.ex.action.AnActionEvent; -import consulo.language.editor.LangDataKeys; import consulo.module.Module; import consulo.content.bundle.Sdk; import com.jetbrains.python.impl.sdk.PythonSdkType; @@ -27,18 +26,19 @@ * @author yole */ public class PyManagePackagesAction extends AnAction { - @Override - public void actionPerformed(AnActionEvent e) { - Module module = e.getData(LangDataKeys.MODULE); - final Sdk sdk = PythonSdkType.findPythonSdk(module); - if (module != null && sdk != null) { - new PyManagePackagesDialog(module.getProject(), sdk).show(); + @Override + @RequiredUIAccess + public void actionPerformed(AnActionEvent e) { + Module module = e.getRequiredData(Module.KEY); + Sdk sdk = PythonSdkType.findPythonSdk(module); + if (sdk != null) { + new PyManagePackagesDialog(module.getProject(), sdk).show(); + } } - } - @Override - public void update(AnActionEvent e) { - Module module = e.getData(LangDataKeys.MODULE); - e.getPresentation().setEnabled(module != null && PythonSdkType.findPythonSdk(module) != null); - } + @Override + public void update(AnActionEvent e) { + Module module = e.getData(Module.KEY); + e.getPresentation().setEnabled(module != null && PythonSdkType.findPythonSdk(module) != null); + } } diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/packaging/setupPy/CreateSetupPyAction.java b/python-impl/src/main/java/com/jetbrains/python/impl/packaging/setupPy/CreateSetupPyAction.java index 871c5c08..684fea7b 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/packaging/setupPy/CreateSetupPyAction.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/packaging/setupPy/CreateSetupPyAction.java @@ -13,11 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.jetbrains.python.impl.packaging.setupPy; import com.jetbrains.python.impl.packaging.PyPackageUtil; import com.jetbrains.python.impl.psi.PyUtil; +import consulo.annotation.access.RequiredReadAction; import consulo.application.ApplicationPropertiesComponent; import consulo.dataContext.DataContext; import consulo.fileTemplate.AttributesDefaults; @@ -26,19 +26,18 @@ import consulo.ide.IdeView; import consulo.ide.action.ui.CreateFromTemplateDialog; import consulo.ide.impl.idea.ide.fileTemplates.actions.CreateFromTemplateAction; -import consulo.language.editor.CommonDataKeys; -import consulo.language.editor.LangDataKeys; import consulo.language.psi.PsiDirectory; import consulo.language.psi.PsiElement; import consulo.language.psi.PsiManager; +import consulo.localize.LocalizeValue; import consulo.module.Module; import consulo.module.content.ModuleRootManager; import consulo.module.content.ProjectFileIndex; +import consulo.platform.Platform; import consulo.project.Project; import consulo.ui.ex.action.AnActionEvent; import consulo.util.lang.Comparing; import consulo.util.lang.StringUtil; -import consulo.util.lang.SystemProperties; import consulo.virtualFileSystem.VirtualFile; import consulo.virtualFileSystem.util.VirtualFileUtil; @@ -48,110 +47,92 @@ /** * @author yole */ -public class CreateSetupPyAction extends CreateFromTemplateAction -{ - private static final String AUTHOR_PROPERTY = "python.packaging.author"; - private static final String EMAIL_PROPERTY = "python.packaging.author.email"; +public class CreateSetupPyAction extends CreateFromTemplateAction { + private static final String AUTHOR_PROPERTY = "python.packaging.author"; + private static final String EMAIL_PROPERTY = "python.packaging.author.email"; - public CreateSetupPyAction() - { - super(FileTemplateManager.getDefaultInstance().getInternalTemplate("Setup Script")); - getTemplatePresentation().setText("Create setup.py"); - } + public CreateSetupPyAction() { + super(FileTemplateManager.getDefaultInstance().getInternalTemplate("Setup Script")); + getTemplatePresentation().setTextValue(LocalizeValue.localizeTODO("Create setup.py")); + } - @Override - public FileTemplate getTemplate() - { - // to ensure changes are picked up, reload the template on every call (PY-6681) - return FileTemplateManager.getDefaultInstance().getInternalTemplate("Setup Script"); - } + @Override + public FileTemplate getTemplate() { + // to ensure changes are picked up, reload the template on every call (PY-6681) + return FileTemplateManager.getDefaultInstance().getInternalTemplate("Setup Script"); + } - @Override - public void update(AnActionEvent e) - { - final Module module = e.getData(LangDataKeys.MODULE); - e.getPresentation().setEnabled(module != null && PyPackageUtil.findSetupPy(module) == null); - } + @Override + public void update(AnActionEvent e) { + Module module = e.getData(Module.KEY); + e.getPresentation().setEnabled(module != null && PyPackageUtil.findSetupPy(module) == null); + } - @Override - public AttributesDefaults getAttributesDefaults(DataContext dataContext) - { - Project project = dataContext.getData(CommonDataKeys.PROJECT); - final AttributesDefaults defaults = new AttributesDefaults("setup.py").withFixedName(true); - if(project != null) - { - defaults.add("Package_name", project.getName()); - final ApplicationPropertiesComponent properties = ApplicationPropertiesComponent.getInstance(); - defaults.add("Author", properties.getValue(AUTHOR_PROPERTY, SystemProperties.getUserName())); - defaults.add("Author_Email", properties.getValue(EMAIL_PROPERTY, "")); - defaults.addPredefined("PackageList", getPackageList(dataContext)); - defaults.addPredefined("PackageDirs", getPackageDirs(dataContext)); - } - return defaults; - } + @Override + public AttributesDefaults getAttributesDefaults(DataContext dataContext) { + Project project = dataContext.getData(Project.KEY); + AttributesDefaults defaults = new AttributesDefaults("setup.py").withFixedName(true); + if (project != null) { + defaults.add("Package_name", project.getName()); + ApplicationPropertiesComponent properties = ApplicationPropertiesComponent.getInstance(); + defaults.add("Author", properties.getValue(AUTHOR_PROPERTY, Platform.current().user().name())); + defaults.add("Author_Email", properties.getValue(EMAIL_PROPERTY, "")); + defaults.addPredefined("PackageList", getPackageList(dataContext)); + defaults.addPredefined("PackageDirs", getPackageDirs(dataContext)); + } + return defaults; + } - private static String getPackageList(DataContext dataContext) - { - final Module module = dataContext.getData(LangDataKeys.MODULE); - if(module != null) - { - return "['" + StringUtil.join(PyPackageUtil.getPackageNames(module), "', '") + "']"; - } - return "[]"; - } + private static String getPackageList(DataContext dataContext) { + Module module = dataContext.getData(Module.KEY); + if (module != null) { + return "['" + StringUtil.join(PyPackageUtil.getPackageNames(module), "', '") + "']"; + } + return "[]"; + } - private static String getPackageDirs(DataContext dataContext) - { - final Module module = dataContext.getData(LangDataKeys.MODULE); - if(module != null) - { - final VirtualFile[] sourceRoots = ModuleRootManager.getInstance(module).getSourceRoots(); - if(sourceRoots.length > 0) - { - for(VirtualFile sourceRoot : sourceRoots) - { - // TODO notify if we have multiple source roots and can't build mapping automatically - final VirtualFile contentRoot = ProjectFileIndex.getInstance(module.getProject()).getContentRootForFile(sourceRoot); - if(contentRoot != null && !Comparing.equal(contentRoot, sourceRoot)) - { - final String relativePath = VirtualFileUtil.getRelativePath(sourceRoot, contentRoot, '/'); - return "\n package_dir={'': '" + relativePath + "'},"; - } - } - } - } - return ""; - } + private static String getPackageDirs(DataContext dataContext) { + Module module = dataContext.getData(Module.KEY); + if (module != null) { + VirtualFile[] sourceRoots = ModuleRootManager.getInstance(module).getSourceRoots(); + if (sourceRoots.length > 0) { + for (VirtualFile sourceRoot : sourceRoots) { + // TODO notify if we have multiple source roots and can't build mapping automatically + VirtualFile contentRoot = ProjectFileIndex.getInstance(module.getProject()).getContentRootForFile(sourceRoot); + if (contentRoot != null && !Comparing.equal(contentRoot, sourceRoot)) { + String relativePath = VirtualFileUtil.getRelativePath(sourceRoot, contentRoot, '/'); + return "\n package_dir={'': '" + relativePath + "'},"; + } + } + } + } + return ""; + } - @Override - protected PsiDirectory getTargetDirectory(DataContext dataContext, IdeView view) - { - final Module module = dataContext.getData(LangDataKeys.MODULE); - if(module != null) - { - final Collection sourceRoots = PyUtil.getSourceRoots(module); - if(sourceRoots.size() > 0) - { - return PsiManager.getInstance(module.getProject()).findDirectory(sourceRoots.iterator().next()); - } - } - return super.getTargetDirectory(dataContext, view); - } + @Override + @RequiredReadAction + protected PsiDirectory getTargetDirectory(DataContext dataContext, IdeView view) { + Module module = dataContext.getData(Module.KEY); + if (module != null) { + Collection sourceRoots = PyUtil.getSourceRoots(module); + if (sourceRoots.size() > 0) { + return PsiManager.getInstance(module.getProject()).findDirectory(sourceRoots.iterator().next()); + } + } + return super.getTargetDirectory(dataContext, view); + } - @Override - protected void elementCreated(CreateFromTemplateDialog dialog, PsiElement createdElement) - { - final ApplicationPropertiesComponent propertiesComponent = ApplicationPropertiesComponent.getInstance(); - final Properties properties = dialog.getEnteredProperties(); - final String author = properties.getProperty("Author"); - if(author != null) - { - propertiesComponent.setValue(AUTHOR_PROPERTY, author); - } - final String authorEmail = properties.getProperty("Author_Email"); - if(authorEmail != null) - { - propertiesComponent.setValue(EMAIL_PROPERTY, authorEmail); - } - } + @Override + protected void elementCreated(CreateFromTemplateDialog dialog, PsiElement createdElement) { + ApplicationPropertiesComponent propertiesComponent = ApplicationPropertiesComponent.getInstance(); + Properties properties = dialog.getEnteredProperties(); + String author = properties.getProperty("Author"); + if (author != null) { + propertiesComponent.setValue(AUTHOR_PROPERTY, author); + } + String authorEmail = properties.getProperty("Author_Email"); + if (authorEmail != null) { + propertiesComponent.setValue(EMAIL_PROPERTY, authorEmail); + } + } } diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/packaging/setupPy/SetupTaskChooserAction.java b/python-impl/src/main/java/com/jetbrains/python/impl/packaging/setupPy/SetupTaskChooserAction.java index cd9455d6..ddcec4fd 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/packaging/setupPy/SetupTaskChooserAction.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/packaging/setupPy/SetupTaskChooserAction.java @@ -20,20 +20,21 @@ import com.jetbrains.python.impl.sdk.PythonSdkType; import com.jetbrains.python.psi.PyFile; import consulo.application.Application; -import consulo.application.ApplicationManager; import consulo.ide.impl.idea.ide.actions.GotoActionBase; import consulo.ide.impl.idea.ide.util.gotoByName.ChooseByNamePopup; import consulo.ide.impl.idea.ide.util.gotoByName.ChooseByNamePopupComponent; import consulo.ide.impl.idea.ide.util.gotoByName.ListChooseByNameModel; -import consulo.language.editor.LangDataKeys; +import consulo.localize.LocalizeValue; import consulo.module.Module; import consulo.process.ExecutionException; import consulo.project.Project; +import consulo.ui.annotation.RequiredUIAccess; import consulo.ui.ex.action.AnAction; import consulo.ui.ex.action.AnActionEvent; import consulo.ui.ex.awt.Messages; import consulo.virtualFileSystem.LocalFileSystem; import consulo.virtualFileSystem.VirtualFile; +import jakarta.annotation.Nonnull; import java.util.ArrayList; import java.util.List; @@ -42,66 +43,73 @@ * @author yole */ public class SetupTaskChooserAction extends AnAction { - public SetupTaskChooserAction() { - super("Run setup.py Task..."); - } - - @Override - public void actionPerformed(AnActionEvent e) { - final Module module = e.getData(LangDataKeys.MODULE); - if (module == null) { - return; + public SetupTaskChooserAction() { + super(LocalizeValue.localizeTODO("Run setup.py Task...")); } - final Project project = module.getProject(); - final ListChooseByNameModel model = - new ListChooseByNameModel<>(project, "Enter setup.py task name", "No tasks found", SetupTaskIntrospector.getTaskList(module)); - final ChooseByNamePopup popup = ChooseByNamePopup.createPopup(project, model, GotoActionBase.getPsiContext(e)); - popup.setShowListForEmptyPattern(true); - - popup.invoke(new ChooseByNamePopupComponent.Callback() { - public void onClose() { - } - public void elementChosen(Object element) { - if (element != null) { - final SetupTask task = (SetupTask)element; - Application application = ApplicationManager.getApplication(); - application.invokeLater(() -> runSetupTask(task.getName(), module), application.getNoneModalityState()); + @Override + @RequiredUIAccess + public void actionPerformed(AnActionEvent e) { + final Module module = e.getData(Module.KEY); + if (module == null) { + return; } - } - }, Application.get().getCurrentModalityState(), false); + Project project = module.getProject(); + ListChooseByNameModel model = + new ListChooseByNameModel<>(project, "Enter setup.py task name", "No tasks found", SetupTaskIntrospector.getTaskList(module)); + ChooseByNamePopup popup = ChooseByNamePopup.createPopup(project, model, GotoActionBase.getPsiContext(e)); + popup.setShowListForEmptyPattern(true); - } + Application application = project.getApplication(); + popup.invoke( + new ChooseByNamePopupComponent.Callback() { + @Override + public void onClose() { + } - @Override - public void update(AnActionEvent e) { - final Module module = e.getData(LangDataKeys.MODULE); - e.getPresentation().setEnabled(module != null && PyPackageUtil.hasSetupPy(module) && PythonSdkType.findPythonSdk(module) != null); - } + @Override + public void elementChosen(Object element) { + if (element != null) { + SetupTask task = (SetupTask) element; + application.invokeLater(() -> runSetupTask(task.getName(), module), application.getNoneModalityState()); + } + } + }, + application.getCurrentModalityState(), + false + ); + } - public static void runSetupTask(String taskName, Module module) { - final PyFile setupPy = PyPackageUtil.findSetupPy(module); - try { - final List options = SetupTaskIntrospector.getSetupTaskOptions(module, taskName); - List parameters = new ArrayList<>(); - parameters.add(taskName); - if (options != null) { - SetupTaskDialog dialog = new SetupTaskDialog(module.getProject(), taskName, options); - if (!dialog.showAndGet()) { - return; - } - parameters.addAll(dialog.getCommandLine()); - } - final PythonTask task = new PythonTask(module, taskName); - final VirtualFile virtualFile = setupPy.getVirtualFile(); - task.setRunnerScript(virtualFile.getPath()); - task.setWorkingDirectory(virtualFile.getParent().getPath()); - task.setParameters(parameters); - task.setAfterCompletion(() -> LocalFileSystem.getInstance().refresh(true)); - task.run(null, null); + @Override + public void update(AnActionEvent e) { + Module module = e.getData(Module.KEY); + e.getPresentation().setEnabled(module != null && PyPackageUtil.hasSetupPy(module) && PythonSdkType.findPythonSdk(module) != null); } - catch (ExecutionException ee) { - Messages.showErrorDialog(module.getProject(), "Failed to run task: " + ee.getMessage(), taskName); + + @RequiredUIAccess + public static void runSetupTask(String taskName, @Nonnull Module module) { + PyFile setupPy = PyPackageUtil.findSetupPy(module); + try { + List options = SetupTaskIntrospector.getSetupTaskOptions(module, taskName); + List parameters = new ArrayList<>(); + parameters.add(taskName); + if (options != null) { + SetupTaskDialog dialog = new SetupTaskDialog(module.getProject(), taskName, options); + if (!dialog.showAndGet()) { + return; + } + parameters.addAll(dialog.getCommandLine()); + } + PythonTask task = new PythonTask(module, taskName); + VirtualFile virtualFile = setupPy.getVirtualFile(); + task.setRunnerScript(virtualFile.getPath()); + task.setWorkingDirectory(virtualFile.getParent().getPath()); + task.setParameters(parameters); + task.setAfterCompletion(() -> LocalFileSystem.getInstance().refresh(true)); + task.run(null, null); + } + catch (ExecutionException ee) { + Messages.showErrorDialog(module.getProject(), "Failed to run task: " + ee.getMessage(), taskName); + } } - } } diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/refactoring/classes/PyClassRefactoringHandler.java b/python-impl/src/main/java/com/jetbrains/python/impl/refactoring/classes/PyClassRefactoringHandler.java index 42185ab8..5ecb9e12 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/refactoring/classes/PyClassRefactoringHandler.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/refactoring/classes/PyClassRefactoringHandler.java @@ -16,100 +16,111 @@ package com.jetbrains.python.impl.refactoring.classes; import com.jetbrains.python.impl.PyBundle; -import com.jetbrains.python.psi.PyClass; import com.jetbrains.python.impl.psi.PyUtil; +import com.jetbrains.python.psi.PyClass; import consulo.codeEditor.CaretModel; import consulo.codeEditor.Editor; import consulo.codeEditor.SelectionModel; import consulo.dataContext.DataContext; import consulo.document.Document; -import consulo.language.editor.CommonDataKeys; import consulo.language.editor.refactoring.ElementsHandler; import consulo.language.editor.refactoring.action.RefactoringActionHandler; import consulo.language.editor.refactoring.util.CommonRefactoringUtil; import consulo.language.psi.PsiElement; import consulo.language.psi.PsiFile; import consulo.project.Project; - +import consulo.python.impl.localize.PyLocalize; +import consulo.ui.annotation.RequiredUIAccess; import jakarta.annotation.Nonnull; +import jakarta.annotation.Nullable; /** * @author Dennis.Ushakov */ -public abstract class PyClassRefactoringHandler implements RefactoringActionHandler, ElementsHandler -{ - public void invoke(@Nonnull Project project, Editor editor, PsiFile file, DataContext dataContext) - { - PsiElement element1 = null; - PsiElement element2 = null; - final SelectionModel selectionModel = editor.getSelectionModel(); - if(selectionModel.hasSelection()) - { - element1 = file.findElementAt(selectionModel.getSelectionStart()); - element2 = file.findElementAt(selectionModel.getSelectionEnd() - 1); - } - else - { - final CaretModel caretModel = editor.getCaretModel(); - final Document document = editor.getDocument(); - int lineNumber = document.getLineNumber(caretModel.getOffset()); - if((lineNumber >= 0) && (lineNumber < document.getLineCount())) - { - element1 = file.findElementAt(document.getLineStartOffset(lineNumber)); - element2 = file.findElementAt(document.getLineEndOffset(lineNumber) - 1); - } - } - if(element1 == null || element2 == null) - { - CommonRefactoringUtil.showErrorHint(project, editor, PyBundle.message("refactoring.introduce.selection.error"), getTitle(), "members.pull.up"); - return; - } - doRefactor(project, element1, element2, editor, file, dataContext); - } - - public void invoke(@Nonnull Project project, @Nonnull PsiElement[] elements, DataContext dataContext) - { - final PsiFile file = dataContext.getData(CommonDataKeys.PSI_FILE); - final Editor editor = dataContext.getData(CommonDataKeys.EDITOR); - doRefactor(project, elements[0], elements[elements.length - 1], editor, file, dataContext); - } - - private void doRefactor(Project project, PsiElement element1, PsiElement element2, Editor editor, PsiFile file, DataContext dataContext) - { - CommonRefactoringUtil.checkReadOnlyStatus(project, file); +public abstract class PyClassRefactoringHandler implements RefactoringActionHandler, ElementsHandler { + @Override + @RequiredUIAccess + public void invoke(@Nonnull Project project, Editor editor, PsiFile file, DataContext dataContext) { + PsiElement element1 = null; + PsiElement element2 = null; + SelectionModel selectionModel = editor.getSelectionModel(); + if (selectionModel.hasSelection()) { + element1 = file.findElementAt(selectionModel.getSelectionStart()); + element2 = file.findElementAt(selectionModel.getSelectionEnd() - 1); + } + else { + CaretModel caretModel = editor.getCaretModel(); + Document document = editor.getDocument(); + int lineNumber = document.getLineNumber(caretModel.getOffset()); + if (lineNumber >= 0 && lineNumber < document.getLineCount()) { + element1 = file.findElementAt(document.getLineStartOffset(lineNumber)); + element2 = file.findElementAt(document.getLineEndOffset(lineNumber) - 1); + } + } + if (element1 == null || element2 == null) { + CommonRefactoringUtil.showErrorHint( + project, + editor, + PyLocalize.refactoringIntroduceSelectionError().get(), + getTitle(), + "members.pull.up" + ); + return; + } + doRefactor(project, element1, element2, editor, file); + } - final PyClass clazz = PyUtil.getContainingClassOrSelf(element1); - if(!inClass(clazz, project, editor, "refactoring.pull.up.error.cannot.perform.refactoring.not.inside.class")) - { - return; - } - assert clazz != null; + @Override + @RequiredUIAccess + public void invoke(@Nonnull Project project, @Nonnull PsiElement[] elements, DataContext dataContext) { + PsiFile file = dataContext.getRequiredData(PsiFile.KEY); + Editor editor = dataContext.getData(Editor.KEY); + doRefactor(project, elements[0], elements[elements.length - 1], editor, file); + } - final PyMemberInfoStorage infoStorage = PyMembersRefactoringSupport.getSelectedMemberInfos(clazz, element1, element2); + @RequiredUIAccess + private void doRefactor( + @Nonnull Project project, + PsiElement element1, + PsiElement element2, + Editor editor, + @Nonnull PsiFile file + ) { + CommonRefactoringUtil.checkReadOnlyStatus(project, file); - doRefactorImpl(project, clazz, infoStorage, editor); - } + PyClass clazz = PyUtil.getContainingClassOrSelf(element1); + if (!inClass(clazz, project, editor, "refactoring.pull.up.error.cannot.perform.refactoring.not.inside.class")) { + return; + } + assert clazz != null; + PyMemberInfoStorage infoStorage = PyMembersRefactoringSupport.getSelectedMemberInfos(clazz, element1, element2); - protected abstract void doRefactorImpl(@Nonnull final Project project, @Nonnull final PyClass classUnderRefactoring, @Nonnull final PyMemberInfoStorage infoStorage, @Nonnull final Editor editor); + doRefactorImpl(project, clazz, infoStorage, editor); + } + protected abstract void doRefactorImpl( + @Nonnull Project project, + @Nonnull PyClass classUnderRefactoring, + @Nonnull PyMemberInfoStorage infoStorage, + @Nonnull Editor editor + ); - protected boolean inClass(PyClass clazz, Project project, Editor editor, String errorMessageId) - { - if(clazz == null) - { - CommonRefactoringUtil.showErrorHint(project, editor, PyBundle.message(errorMessageId), getTitle(), getHelpId()); - return false; - } - return true; - } + @RequiredUIAccess + protected boolean inClass(@Nullable PyClass clazz, @Nonnull Project project, Editor editor, String errorMessageId) { + if (clazz == null) { + CommonRefactoringUtil.showErrorHint(project, editor, PyBundle.message(errorMessageId), getTitle(), getHelpId()); + return false; + } + return true; + } - protected abstract String getTitle(); + protected abstract String getTitle(); - protected abstract String getHelpId(); + protected abstract String getHelpId(); - public boolean isEnabledOnElements(PsiElement[] elements) - { - return elements.length == 1 && elements[0] instanceof PyClass; - } + @Override + public boolean isEnabledOnElements(PsiElement[] elements) { + return elements.length == 1 && elements[0] instanceof PyClass; + } } diff --git a/python-rest/src/main/java/com/jetbrains/python/rest/RestPythonUtil.java b/python-rest/src/main/java/com/jetbrains/python/rest/RestPythonUtil.java index 6975b1a8..c538937e 100644 --- a/python-rest/src/main/java/com/jetbrains/python/rest/RestPythonUtil.java +++ b/python-rest/src/main/java/com/jetbrains/python/rest/RestPythonUtil.java @@ -19,9 +19,8 @@ import com.jetbrains.python.impl.sdk.PythonSdkType; import com.jetbrains.python.packaging.PyPackage; import com.jetbrains.python.packaging.PyPackageManager; +import consulo.annotation.access.RequiredReadAction; import consulo.content.bundle.Sdk; -import consulo.language.editor.CommonDataKeys; -import consulo.language.editor.LangDataKeys; import consulo.module.Module; import consulo.module.ModuleManager; import consulo.project.Project; @@ -31,38 +30,32 @@ import java.util.List; /** - * User : catherine + * @author catherine */ -public class RestPythonUtil -{ - private RestPythonUtil() - { - } +public class RestPythonUtil { + private RestPythonUtil() { + } - public static Presentation updateSphinxQuickStartRequiredAction(final AnActionEvent e) - { - final Presentation presentation = e.getPresentation(); + @RequiredReadAction + public static Presentation updateSphinxQuickStartRequiredAction(AnActionEvent e) { + Presentation presentation = e.getPresentation(); - final Project project = e.getData(CommonDataKeys.PROJECT); - if(project != null) - { - Module module = e.getData(LangDataKeys.MODULE); - if(module == null) - { - Module[] modules = ModuleManager.getInstance(project).getModules(); - module = modules.length == 0 ? null : modules[0]; - } - if(module != null) - { - final Sdk sdk = PythonSdkType.findPythonSdk(module); - if(sdk != null) - { - final List packages = PyPackageManager.getInstance(sdk).getPackages(); - final PyPackage sphinx = packages != null ? PyPackageUtil.findPackage(packages, "Sphinx") : null; - presentation.setEnabled(sphinx != null); - } - } - } - return presentation; - } + Project project = e.getData(Project.KEY); + if (project != null) { + Module module = e.getData(Module.KEY); + if (module == null) { + Module[] modules = ModuleManager.getInstance(project).getModules(); + module = modules.length == 0 ? null : modules[0]; + } + if (module != null) { + Sdk sdk = PythonSdkType.findPythonSdk(module); + if (sdk != null) { + List packages = PyPackageManager.getInstance(sdk).getPackages(); + PyPackage sphinx = packages != null ? PyPackageUtil.findPackage(packages, "Sphinx") : null; + presentation.setEnabled(sphinx != null); + } + } + } + return presentation; + } } diff --git a/python-rest/src/main/java/com/jetbrains/python/rest/sphinx/RunSphinxQuickStartAction.java b/python-rest/src/main/java/com/jetbrains/python/rest/sphinx/RunSphinxQuickStartAction.java index 5931b3b8..9d756040 100644 --- a/python-rest/src/main/java/com/jetbrains/python/rest/sphinx/RunSphinxQuickStartAction.java +++ b/python-rest/src/main/java/com/jetbrains/python/rest/sphinx/RunSphinxQuickStartAction.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.jetbrains.python.rest.sphinx; import com.jetbrains.python.rest.RestPythonUtil; @@ -21,59 +20,56 @@ import consulo.annotation.component.ActionParentRef; import consulo.annotation.component.ActionRef; import consulo.application.Application; -import consulo.application.ApplicationManager; import consulo.application.dumb.DumbAware; -import consulo.language.editor.LangDataKeys; -import consulo.language.editor.PlatformDataKeys; +import consulo.localize.LocalizeValue; import consulo.module.Module; import consulo.module.ModuleManager; import consulo.project.Project; +import consulo.ui.annotation.RequiredUIAccess; import consulo.ui.ex.action.AnAction; import consulo.ui.ex.action.AnActionEvent; import consulo.ui.ex.action.Presentation; +import jakarta.annotation.Nonnull; /** - * user : catherine + * @author catherine */ @ActionImpl(id = "RunSphinxQuickStartAction", parents = @ActionParentRef(@ActionRef(id = "ToolsMenu"))) public class RunSphinxQuickStartAction extends AnAction implements DumbAware { - public RunSphinxQuickStartAction() { - super("Sphinx quickstart", "Allows to run sphinx quick-start action", null); - } + public RunSphinxQuickStartAction() { + super(LocalizeValue.localizeTODO("Sphinx quickstart"), LocalizeValue.localizeTODO("Allows to run sphinx quick-start action")); + } - @Override - public void update(final AnActionEvent event) { - super.update(event); - RestPythonUtil.updateSphinxQuickStartRequiredAction(event); - } + @Override + public void update(@Nonnull AnActionEvent event) { + super.update(event); + RestPythonUtil.updateSphinxQuickStartRequiredAction(event); + } - @Override - public void actionPerformed(final AnActionEvent e) { - final Presentation presentation = RestPythonUtil.updateSphinxQuickStartRequiredAction(e); - assert presentation.isEnabled() && presentation.isVisible() : "Sphinx requirements for action are not satisfied"; + @Override + @RequiredUIAccess + public void actionPerformed(@Nonnull AnActionEvent e) { + Presentation presentation = RestPythonUtil.updateSphinxQuickStartRequiredAction(e); + assert presentation.isEnabled() && presentation.isVisible() : "Sphinx requirements for action are not satisfied"; - final Project project = e.getData(PlatformDataKeys.PROJECT); + Project project = e.getData(Project.KEY); - if (project == null) { - return; - } + if (project == null) { + return; + } - Module module = e.getData(LangDataKeys.MODULE); - if (module == null) { - Module[] modules = ModuleManager.getInstance(project).getModules(); - module = modules.length == 0 ? null : modules[0]; - } + Module module = e.getData(Module.KEY); + if (module == null) { + Module[] modules = ModuleManager.getInstance(project).getModules(); + module = modules.length == 0 ? null : modules[0]; + } - if (module == null) { - return; + if (module == null) { + return; + } + SphinxBaseCommand action = new SphinxBaseCommand(); + Module finalModule = module; + Application application = project.getApplication(); + application.invokeLater(() -> action.execute(finalModule), application.getNoneModalityState()); } - final SphinxBaseCommand action = new SphinxBaseCommand(); - final Module finalModule = module; - Application application = ApplicationManager.getApplication(); - application.invokeLater(new Runnable() { - public void run() { - action.execute(finalModule); - } - }, application.getNoneModalityState()); - } }