2 * SPDX-FileCopyrightText: 2007-2010 Peter Penz <peter.penz19@gmail.com>
4 * SPDX-License-Identifier: GPL-2.0-or-later
7 #include "terminalpanel.h"
9 #include <KIO/DesktopExecParser>
11 #include <KIO/JobUiDelegate>
12 #include <KJobWidgets>
13 #include <KLocalizedString>
14 #include <KMessageWidget>
15 #include <KMountPoint>
16 #include <KParts/ReadOnlyPart>
17 #include <KPluginFactory>
18 #include <KPluginLoader>
19 #include <KProtocolInfo>
22 #include <kde_terminal_interface.h>
25 #include <QDesktopServices>
30 #include <QVBoxLayout>
32 TerminalPanel::TerminalPanel(QWidget
* parent
) :
34 m_clearTerminal(true),
35 m_mostLocalUrlJob(nullptr),
38 m_terminalWidget(nullptr),
39 m_konsolePartMissingMessage(nullptr),
40 m_konsolePart(nullptr),
41 m_konsolePartCurrentDirectory(),
42 m_sendCdToTerminalHistory(),
43 m_kiofuseInterface(QStringLiteral("org.kde.KIOFuse"),
44 QStringLiteral("/org/kde/KIOFuse"),
45 QDBusConnection::sessionBus())
47 m_layout
= new QVBoxLayout(this);
48 m_layout
->setContentsMargins(0, 0, 0, 0);
51 TerminalPanel::~TerminalPanel()
55 void TerminalPanel::goHome()
57 sendCdToTerminal(QDir::homePath(), HistoryPolicy::SkipHistory
);
60 QString
TerminalPanel::currentWorkingDirectory()
63 return m_terminal
->currentWorkingDirectory();
68 void TerminalPanel::terminalExited()
71 emit
hideTerminalPanel();
74 bool TerminalPanel::isHiddenInVisibleWindow() const
77 && parentWidget()->isHidden();
80 void TerminalPanel::dockVisibilityChanged()
82 // Only react when the DockWidget itself (not some parent) is hidden. This way we don't
83 // respond when e.g. Dolphin is minimized.
84 if (isHiddenInVisibleWindow() && m_terminal
&& !hasProgramRunning()) {
85 // Make sure that the following "cd /" command will not affect the view.
86 disconnect(m_konsolePart
, SIGNAL(currentDirectoryChanged(QString
)),
87 this, SLOT(slotKonsolePartCurrentDirectoryChanged(QString
)));
89 // Make sure this terminal does not prevent unmounting any removable drives
90 changeDir(QUrl::fromLocalFile(QStringLiteral("/")));
92 // Because we have disconnected from the part's currentDirectoryChanged()
93 // signal, we have to update m_konsolePartCurrentDirectory manually. If this
94 // was not done, showing the panel again might not set the part's working
95 // directory correctly.
96 m_konsolePartCurrentDirectory
= '/';
100 QString
TerminalPanel::runningProgramName() const
102 return m_terminal
? m_terminal
->foregroundProcessName() : QString();
105 bool TerminalPanel::hasProgramRunning() const
107 return m_terminal
&& (m_terminal
->foregroundProcessId() != -1);
110 bool TerminalPanel::urlChanged()
112 if (!url().isValid()) {
116 const bool sendInput
= m_terminal
&& !hasProgramRunning() && isVisible();
124 void TerminalPanel::showEvent(QShowEvent
* event
)
126 if (event
->spontaneous()) {
127 Panel::showEvent(event
);
132 m_clearTerminal
= true;
133 KPluginFactory
* factory
= nullptr;
134 KService::Ptr service
= KService::serviceByDesktopName(QStringLiteral("konsolepart"));
136 factory
= KPluginLoader(service
->library()).factory();
138 m_konsolePart
= factory
? (factory
->create
<KParts::ReadOnlyPart
>(this)) : nullptr;
140 connect(m_konsolePart
, &KParts::ReadOnlyPart::destroyed
, this, &TerminalPanel::terminalExited
);
141 m_terminalWidget
= m_konsolePart
->widget();
142 setFocusProxy(m_terminalWidget
);
143 m_layout
->addWidget(m_terminalWidget
);
144 if (m_konsolePartMissingMessage
) {
145 m_layout
->removeWidget(m_konsolePartMissingMessage
);
147 m_terminal
= qobject_cast
<TerminalInterface
*>(m_konsolePart
);
148 } else if (!m_konsolePartMissingMessage
) {
149 const auto konsoleInstallUrl
= QUrl("appstream://org.kde.konsole.desktop");
150 const auto konsoleNotInstalledText
= i18n("Terminal cannot be shown because Konsole is not installed. "
151 "Please install it and then reopen the panel.");
152 m_konsolePartMissingMessage
= new KMessageWidget(konsoleNotInstalledText
, this);
153 m_konsolePartMissingMessage
->setCloseButtonVisible(false);
154 m_konsolePartMissingMessage
->hide();
155 if (KIO::DesktopExecParser::hasSchemeHandler(konsoleInstallUrl
)) {
156 auto installKonsoleAction
= new QAction(i18n("Install Konsole"), this);
157 connect(installKonsoleAction
, &QAction::triggered
, [konsoleInstallUrl
]() {
158 QDesktopServices::openUrl(konsoleInstallUrl
);
160 m_konsolePartMissingMessage
->addAction(installKonsoleAction
);
162 m_layout
->addWidget(m_konsolePartMissingMessage
);
163 m_layout
->addStretch();
164 QTimer::singleShot(0, m_konsolePartMissingMessage
, &KMessageWidget::animatedShow
);
166 m_konsolePartMissingMessage
->animatedShow();
170 m_terminal
->showShellInDir(url().toLocalFile());
171 if(!hasProgramRunning()) {
174 m_terminalWidget
->setFocus();
175 connect(m_konsolePart
, SIGNAL(currentDirectoryChanged(QString
)),
176 this, SLOT(slotKonsolePartCurrentDirectoryChanged(QString
)));
179 Panel::showEvent(event
);
182 void TerminalPanel::changeDir(const QUrl
& url
)
184 delete m_mostLocalUrlJob
;
185 m_mostLocalUrlJob
= nullptr;
187 if (url
.isLocalFile()) {
188 sendCdToTerminal(url
.toLocalFile());
192 // Try stat'ing the url; note that mostLocalUrl only works with ":local" protocols
193 if (KProtocolInfo::protocolClass(url
.scheme()) == QLatin1String(":local")) {
194 m_mostLocalUrlJob
= KIO::mostLocalUrl(url
, KIO::HideProgressInfo
);
195 if (m_mostLocalUrlJob
->uiDelegate()) {
196 KJobWidgets::setWindow(m_mostLocalUrlJob
, this);
198 connect(m_mostLocalUrlJob
, &KIO::StatJob::result
, this, &TerminalPanel::slotMostLocalUrlResult
);
202 // Last chance, try KIOFuse
203 sendCdToTerminalKIOFuse(url
);
206 void TerminalPanel::sendCdToTerminal(const QString
& dir
, HistoryPolicy addToHistory
)
208 if (dir
== m_konsolePartCurrentDirectory
) {
209 m_clearTerminal
= false;
214 if (!m_clearTerminal
) {
215 // The TerminalV2 interface does not provide a way to delete the
216 // current line before sending a new input. This is mandatory,
217 // otherwise sending a 'cd x' to a existing 'rm -rf *' might
218 // result in data loss. As workaround SIGINT is sent.
219 const int processId
= m_terminal
->terminalProcessId();
221 kill(processId
, SIGINT
);
226 m_terminal
->sendInput(" cd " + KShell::quoteArg(dir
) + '\n');
228 // We want to ignore the currentDirectoryChanged(QString) signal, which we will receive after
229 // the directory change, because this directory change is not caused by a "cd" command that the
230 // user entered in the panel. Therefore, we have to remember 'dir'. Note that it could also be
231 // a symbolic link -> remember the 'canonical' path.
232 if (addToHistory
== HistoryPolicy::AddToHistory
)
233 m_sendCdToTerminalHistory
.enqueue(QDir(dir
).canonicalPath());
235 if (m_clearTerminal
) {
236 m_terminal
->sendInput(QStringLiteral(" clear\n"));
237 m_clearTerminal
= false;
241 void TerminalPanel::sendCdToTerminalKIOFuse(const QUrl
&url
) {
242 // URL isn't local, only hope for the terminal to be in sync with the
243 // DolphinView is to mount the remote URL in KIOFuse and point to it.
244 // If we can't do that for any reason, silently fail.
245 auto reply
= m_kiofuseInterface
.mountUrl(url
.toString());
246 QDBusPendingCallWatcher
* watcher
= new QDBusPendingCallWatcher(reply
, this);
247 QObject::connect(watcher
, &QDBusPendingCallWatcher::finished
, this, [=] (QDBusPendingCallWatcher
* watcher
) {
248 watcher
->deleteLater();
249 if (!reply
.isError()) {
250 // Successfully mounted, point to the KIOFuse equivalent path.
251 sendCdToTerminal(reply
.value());
256 void TerminalPanel::slotMostLocalUrlResult(KJob
* job
)
258 KIO::StatJob
* statJob
= static_cast<KIO::StatJob
*>(job
);
259 const QUrl url
= statJob
->mostLocalUrl();
260 if (url
.isLocalFile()) {
261 sendCdToTerminal(url
.toLocalFile());
263 sendCdToTerminalKIOFuse(url
);
266 m_mostLocalUrlJob
= nullptr;
269 void TerminalPanel::slotKonsolePartCurrentDirectoryChanged(const QString
& dir
)
271 m_konsolePartCurrentDirectory
= QDir(dir
).canonicalPath();
273 // Only emit a changeUrl signal if the directory change was caused by the user inside the
274 // terminal, and not by sendCdToTerminal(QString).
275 while (!m_sendCdToTerminalHistory
.empty()) {
276 if (m_konsolePartCurrentDirectory
== m_sendCdToTerminalHistory
.dequeue()) {
281 // User may potentially be browsing inside a KIOFuse mount.
282 // If so lets try and change the DolphinView to point to the remote URL equivalent.
283 // instead of into the KIOFuse mount itself (which can cause performance issues!)
284 const QUrl
url(QUrl::fromLocalFile(dir
));
286 KMountPoint::Ptr mountPoint
= KMountPoint::currentMountPoints().findByPath(m_konsolePartCurrentDirectory
);
287 if (mountPoint
&& mountPoint
->mountType() != QStringLiteral("fuse.kio-fuse")) {
288 // Not in KIOFUse mount, so just switch to the corresponding URL.
293 auto reply
= m_kiofuseInterface
.remoteUrl(m_konsolePartCurrentDirectory
);
294 QDBusPendingCallWatcher
* watcher
= new QDBusPendingCallWatcher(reply
, this);
295 QObject::connect(watcher
, &QDBusPendingCallWatcher::finished
, this, [=] (QDBusPendingCallWatcher
* watcher
) {
296 watcher
->deleteLater();
297 if (reply
.isError()) {
298 // KIOFuse errored out... just show the normal URL
301 // Our location happens to be in a KIOFuse mount and is mounted.
302 // Let's change the DolphinView to point to the remote URL equivalent.
303 emit
changeUrl(QUrl::fromUserInput(reply
.value()));
308 bool TerminalPanel::terminalHasFocus() const
310 if (m_terminalWidget
) {
311 return m_terminalWidget
->hasFocus();