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 <KActionCollection>
10 #include <KIO/DesktopExecParser>
12 #include <KIO/JobUiDelegate>
13 #include <KJobWidgets>
14 #include <KLocalizedString>
15 #include <KMessageWidget>
16 #include <KMountPoint>
17 #include <KParts/ReadOnlyPart>
18 #include <KPluginFactory>
19 #include <KProtocolInfo>
21 #include <KXMLGUIBuilder>
22 #include <KXMLGUIFactory>
23 #include <kde_terminal_interface.h>
26 #include <QDesktopServices>
31 #include <QVBoxLayout>
33 TerminalPanel::TerminalPanel(QWidget
* parent
) :
35 m_clearTerminal(true),
36 m_mostLocalUrlJob(nullptr),
39 m_terminalWidget(nullptr),
40 m_konsolePartMissingMessage(nullptr),
41 m_konsolePart(nullptr),
42 m_konsolePartCurrentDirectory(),
43 m_sendCdToTerminalHistory(),
44 m_kiofuseInterface(QStringLiteral("org.kde.KIOFuse"),
45 QStringLiteral("/org/kde/KIOFuse"),
46 QDBusConnection::sessionBus())
48 m_layout
= new QVBoxLayout(this);
49 m_layout
->setContentsMargins(0, 0, 0, 0);
52 TerminalPanel::~TerminalPanel()
56 void TerminalPanel::goHome()
58 sendCdToTerminal(QDir::homePath(), HistoryPolicy::SkipHistory
);
61 QString
TerminalPanel::currentWorkingDirectory()
64 return m_terminal
->currentWorkingDirectory();
69 void TerminalPanel::terminalExited()
72 Q_EMIT
hideTerminalPanel();
75 bool TerminalPanel::isHiddenInVisibleWindow() const
78 && parentWidget()->isHidden();
81 void TerminalPanel::dockVisibilityChanged()
83 // Only react when the DockWidget itself (not some parent) is hidden. This way we don't
84 // respond when e.g. Dolphin is minimized.
85 if (isHiddenInVisibleWindow() && m_terminal
&& !hasProgramRunning()) {
86 // Make sure that the following "cd /" command will not affect the view.
87 disconnect(m_konsolePart
, SIGNAL(currentDirectoryChanged(QString
)),
88 this, SLOT(slotKonsolePartCurrentDirectoryChanged(QString
)));
90 // Make sure this terminal does not prevent unmounting any removable drives
91 changeDir(QUrl::fromLocalFile(QStringLiteral("/")));
93 // Because we have disconnected from the part's currentDirectoryChanged()
94 // signal, we have to update m_konsolePartCurrentDirectory manually. If this
95 // was not done, showing the panel again might not set the part's working
96 // directory correctly.
97 m_konsolePartCurrentDirectory
= '/';
101 QString
TerminalPanel::runningProgramName() const
103 return m_terminal
? m_terminal
->foregroundProcessName() : QString();
106 KActionCollection
*TerminalPanel::actionCollection()
108 // m_terminal is the only reference reset to nullptr in case the terminal is
110 if (m_terminal
&& m_konsolePart
&& m_terminalWidget
) {
111 const auto guiClients
= m_konsolePart
->childClients();
112 for (auto *client
: guiClients
) {
113 if (client
->actionCollection()->associatedWidgets().contains(m_terminalWidget
)) {
114 return client
->actionCollection();
121 bool TerminalPanel::hasProgramRunning() const
123 return m_terminal
&& (m_terminal
->foregroundProcessId() != -1);
126 bool TerminalPanel::urlChanged()
128 if (!url().isValid()) {
132 const bool sendInput
= m_terminal
&& !hasProgramRunning() && isVisible();
140 void TerminalPanel::showEvent(QShowEvent
* event
)
142 if (event
->spontaneous()) {
143 Panel::showEvent(event
);
148 m_clearTerminal
= true;
149 KPluginFactory
*factory
= KPluginFactory::loadFactory(KPluginMetaData(QStringLiteral("konsolepart"))).plugin
;
150 m_konsolePart
= factory
? (factory
->create
<KParts::ReadOnlyPart
>(this)) : nullptr;
152 connect(m_konsolePart
, &KParts::ReadOnlyPart::destroyed
, this, &TerminalPanel::terminalExited
);
153 m_terminalWidget
= m_konsolePart
->widget();
154 setFocusProxy(m_terminalWidget
);
155 m_layout
->addWidget(m_terminalWidget
);
156 if (m_konsolePartMissingMessage
) {
157 m_layout
->removeWidget(m_konsolePartMissingMessage
);
159 m_terminal
= qobject_cast
<TerminalInterface
*>(m_konsolePart
);
161 // needed to collect the correct KonsolePart actionCollection
162 // namely the one of the single inner terminal and not the outer KonsolePart
163 if (!m_konsolePart
->factory() && m_terminalWidget
) {
164 if (!m_konsolePart
->clientBuilder()) {
165 m_konsolePart
->setClientBuilder(new KXMLGUIBuilder(m_terminalWidget
));
168 auto factory
= new KXMLGUIFactory(m_konsolePart
->clientBuilder(), this);
169 factory
->addClient(m_konsolePart
);
171 // Prevents the KXMLGui warning about removing the client
172 connect(m_terminalWidget
, &QObject::destroyed
, this, [factory
, this] {
173 factory
->removeClient(m_konsolePart
);
177 } else if (!m_konsolePartMissingMessage
) {
178 const auto konsoleInstallUrl
= QUrl("appstream://org.kde.konsole.desktop");
179 const auto konsoleNotInstalledText
= i18n("Terminal cannot be shown because Konsole is not installed. "
180 "Please install it and then reopen the panel.");
181 m_konsolePartMissingMessage
= new KMessageWidget(konsoleNotInstalledText
, this);
182 m_konsolePartMissingMessage
->setCloseButtonVisible(false);
183 m_konsolePartMissingMessage
->hide();
184 if (KIO::DesktopExecParser::hasSchemeHandler(konsoleInstallUrl
)) {
185 auto installKonsoleAction
= new QAction(i18n("Install Konsole"), this);
186 connect(installKonsoleAction
, &QAction::triggered
, [konsoleInstallUrl
]() {
187 QDesktopServices::openUrl(konsoleInstallUrl
);
189 m_konsolePartMissingMessage
->addAction(installKonsoleAction
);
191 m_layout
->addWidget(m_konsolePartMissingMessage
);
192 m_layout
->addStretch();
193 QTimer::singleShot(0, m_konsolePartMissingMessage
, &KMessageWidget::animatedShow
);
195 m_konsolePartMissingMessage
->animatedShow();
199 m_terminal
->showShellInDir(url().toLocalFile());
200 if(!hasProgramRunning()) {
203 m_terminalWidget
->setFocus();
204 connect(m_konsolePart
, SIGNAL(currentDirectoryChanged(QString
)),
205 this, SLOT(slotKonsolePartCurrentDirectoryChanged(QString
)));
208 Panel::showEvent(event
);
211 void TerminalPanel::changeDir(const QUrl
& url
)
213 delete m_mostLocalUrlJob
;
214 m_mostLocalUrlJob
= nullptr;
216 if (url
.isLocalFile()) {
217 sendCdToTerminal(url
.toLocalFile());
221 // Try stat'ing the url; note that mostLocalUrl only works with ":local" protocols
222 if (KProtocolInfo::protocolClass(url
.scheme()) == QLatin1String(":local")) {
223 m_mostLocalUrlJob
= KIO::mostLocalUrl(url
, KIO::HideProgressInfo
);
224 if (m_mostLocalUrlJob
->uiDelegate()) {
225 KJobWidgets::setWindow(m_mostLocalUrlJob
, this);
227 connect(m_mostLocalUrlJob
, &KIO::StatJob::result
, this, &TerminalPanel::slotMostLocalUrlResult
);
231 // Last chance, try KIOFuse
232 sendCdToTerminalKIOFuse(url
);
235 void TerminalPanel::sendCdToTerminal(const QString
& dir
, HistoryPolicy addToHistory
)
237 if (dir
== m_konsolePartCurrentDirectory
) {
238 m_clearTerminal
= false;
243 if (!m_clearTerminal
) {
244 // The TerminalV2 interface does not provide a way to delete the
245 // current line before sending a new input. This is mandatory,
246 // otherwise sending a 'cd x' to a existing 'rm -rf *' might
247 // result in data loss. As workaround SIGINT is sent.
248 const int processId
= m_terminal
->terminalProcessId();
250 kill(processId
, SIGINT
);
255 m_terminal
->sendInput(" cd " + KShell::quoteArg(dir
) + '\n');
257 // We want to ignore the currentDirectoryChanged(QString) signal, which we will receive after
258 // the directory change, because this directory change is not caused by a "cd" command that the
259 // user entered in the panel. Therefore, we have to remember 'dir'. Note that it could also be
260 // a symbolic link -> remember the 'canonical' path.
261 if (addToHistory
== HistoryPolicy::AddToHistory
)
262 m_sendCdToTerminalHistory
.enqueue(QDir(dir
).canonicalPath());
264 if (m_clearTerminal
) {
265 m_terminal
->sendInput(QStringLiteral(" clear\n"));
266 m_clearTerminal
= false;
270 void TerminalPanel::sendCdToTerminalKIOFuse(const QUrl
&url
) {
271 // URL isn't local, only hope for the terminal to be in sync with the
272 // DolphinView is to mount the remote URL in KIOFuse and point to it.
273 // If we can't do that for any reason, silently fail.
274 auto reply
= m_kiofuseInterface
.mountUrl(url
.toString());
275 QDBusPendingCallWatcher
* watcher
= new QDBusPendingCallWatcher(reply
, this);
276 QObject::connect(watcher
, &QDBusPendingCallWatcher::finished
, this, [=] (QDBusPendingCallWatcher
* watcher
) {
277 watcher
->deleteLater();
278 if (!reply
.isError()) {
279 // Successfully mounted, point to the KIOFuse equivalent path.
280 sendCdToTerminal(reply
.value());
285 void TerminalPanel::slotMostLocalUrlResult(KJob
* job
)
287 KIO::StatJob
* statJob
= static_cast<KIO::StatJob
*>(job
);
288 const QUrl url
= statJob
->mostLocalUrl();
289 if (url
.isLocalFile()) {
290 sendCdToTerminal(url
.toLocalFile());
292 sendCdToTerminalKIOFuse(url
);
295 m_mostLocalUrlJob
= nullptr;
298 void TerminalPanel::slotKonsolePartCurrentDirectoryChanged(const QString
& dir
)
300 m_konsolePartCurrentDirectory
= QDir(dir
).canonicalPath();
302 // Only emit a changeUrl signal if the directory change was caused by the user inside the
303 // terminal, and not by sendCdToTerminal(QString).
304 while (!m_sendCdToTerminalHistory
.empty()) {
305 if (m_konsolePartCurrentDirectory
== m_sendCdToTerminalHistory
.dequeue()) {
310 // User may potentially be browsing inside a KIOFuse mount.
311 // If so lets try and change the DolphinView to point to the remote URL equivalent.
312 // instead of into the KIOFuse mount itself (which can cause performance issues!)
313 const QUrl
url(QUrl::fromLocalFile(dir
));
315 KMountPoint::Ptr mountPoint
= KMountPoint::currentMountPoints().findByPath(m_konsolePartCurrentDirectory
);
316 if (mountPoint
&& mountPoint
->mountType() != QStringLiteral("fuse.kio-fuse")) {
317 // Not in KIOFUse mount, so just switch to the corresponding URL.
318 Q_EMIT
changeUrl(url
);
322 auto reply
= m_kiofuseInterface
.remoteUrl(m_konsolePartCurrentDirectory
);
323 QDBusPendingCallWatcher
* watcher
= new QDBusPendingCallWatcher(reply
, this);
324 QObject::connect(watcher
, &QDBusPendingCallWatcher::finished
, this, [=] (QDBusPendingCallWatcher
* watcher
) {
325 watcher
->deleteLater();
326 if (reply
.isError()) {
327 // KIOFuse errored out... just show the normal URL
328 Q_EMIT
changeUrl(url
);
330 // Our location happens to be in a KIOFuse mount and is mounted.
331 // Let's change the DolphinView to point to the remote URL equivalent.
332 Q_EMIT
changeUrl(QUrl::fromUserInput(reply
.value()));
337 bool TerminalPanel::terminalHasFocus() const
339 if (m_terminalWidget
) {
340 return m_terminalWidget
->hasFocus();