SSHRemotePlugin/src/main/java/com/example/plugin/OpenRemoteTerminalAction.java

88 lines
3.0 KiB
Java

package com.example.plugin;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.terminal.JBTerminalWidget;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentFactory;
import com.jcraft.jsch.ChannelShell;
import com.jediterm.terminal.TtyConnector;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.terminal.JBTerminalSystemSettingsProvider;
import java.util.Optional;
public class OpenRemoteTerminalAction extends AnAction {
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
Project project = e.getProject();
if (project == null) return;
String serverId = ProjectServerMapping.getInstance()
.getServerIdForProject(project.getBasePath());
if (serverId == null) {
Messages.showErrorDialog("No server associated with this project.", "Error");
return;
}
Optional<SshServer> maybeServer =
SshServerManager.getInstance().findServer(serverId);
if (maybeServer.isEmpty()) {
Messages.showErrorDialog("Server not found.", "Error");
return;
}
SshServer server = maybeServer.get();
try {
ChannelShell shellChannel =
SftpSessionManager.getInstance(project)
.getShellChannel(server);
TtyConnector connector = new SshTtyConnector(shellChannel, server.remoteProjectPath);
ToolWindow terminalToolWindow =
ToolWindowManager.getInstance(project).getToolWindow("Terminal");
if (terminalToolWindow == null) {
Messages.showErrorDialog("Terminal tool window not found.", "Error");
return;
}
Disposable disposable =
Disposer.newDisposable(project, "Remote SSH Terminal");
JBTerminalWidget widget =
new JBTerminalWidget(
project,
new JBTerminalSystemSettingsProvider(),
disposable
);
Content content =
ContentFactory.getInstance()
.createContent(widget, "Remote: " + server.name, false);
content.setDisposer(disposable);
terminalToolWindow.getContentManager().addContent(content);
terminalToolWindow.getContentManager().setSelectedContent(content, true);
terminalToolWindow.activate(() -> widget.start(connector), true);
} catch (Exception ex) {
Messages.showErrorDialog(
"Failed to open terminal: " + ex.getMessage(),
"Error"
);
}
}
}