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>
11 #include <KIO/StatJob>
12 #include <KJobWidgets>
13 #include <KLocalizedString>
14 #include <KMessageWidget>
15 #include <KMountPoint>
16 #include <KParts/ReadOnlyPart>
17 #include <KPluginFactory>
18 #include <KProtocolInfo>
20 #include <KXMLGUIBuilder>
21 #include <KXMLGUIFactory>
22 #include <kde_terminal_interface.h>
25 #include <QDesktopServices>
29 #include <QVBoxLayout>
31 TerminalPanel::TerminalPanel(QWidget
*parent
)
33 , m_clearTerminal(true)
34 , m_mostLocalUrlJob(nullptr)
37 , m_terminalWidget(nullptr)
38 , m_konsolePartMissingMessage(nullptr)
39 , m_konsolePart(nullptr)
40 , m_konsolePartCurrentDirectory()
41 , m_sendCdToTerminalHistory()
42 , m_kiofuseInterface(QStringLiteral("org.kde.KIOFuse"), QStringLiteral("/org/kde/KIOFuse"), QDBusConnection::sessionBus())
44 m_layout
= new QVBoxLayout(this);
45 m_layout
->setContentsMargins(0, 0, 0, 0);
48 TerminalPanel::~TerminalPanel()
51 // Avoid when QObject cleanup, which comes after our destructor, deletes the konsolePart
52 // and subsequently calls back into our slot when the destructor has already run.
53 disconnect(m_konsolePart
, &KParts::ReadOnlyPart::destroyed
, this, &TerminalPanel::terminalExited
);
57 void TerminalPanel::goHome()
59 sendCdToTerminal(QDir::homePath(), HistoryPolicy::SkipHistory
);
62 bool TerminalPanel::currentWorkingDirectoryIsChildOf(const QString
&path
) const
65 return m_terminal
->currentWorkingDirectory().startsWith(path
);
70 void TerminalPanel::terminalExited()
73 Q_EMIT
hideTerminalPanel();
76 bool TerminalPanel::isHiddenInVisibleWindow() const
78 return parentWidget() && 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()) {
86 if (m_konsolePartMissingMessage
) {
87 m_konsolePartMissingMessage
->hide();
88 } else if (m_terminal
&& !hasProgramRunning()) {
89 // Make sure that the following "cd /" command will not affect the view.
90 disconnect(m_konsolePart
, SIGNAL(currentDirectoryChanged(QString
)), this, SLOT(slotKonsolePartCurrentDirectoryChanged(QString
)));
92 // Make sure this terminal does not prevent unmounting any removable drives
93 changeDir(QUrl::fromLocalFile(QStringLiteral("/")));
95 // Because we have disconnected from the part's currentDirectoryChanged()
96 // signal, we have to update m_konsolePartCurrentDirectory manually. If this
97 // was not done, showing the panel again might not set the part's working
98 // directory correctly.
99 m_konsolePartCurrentDirectory
= '/';
104 QString
TerminalPanel::runningProgramName() const
106 return m_terminal
? m_terminal
->foregroundProcessName() : QString();
109 KActionCollection
*TerminalPanel::actionCollection()
111 // m_terminal is the only reference reset to nullptr in case the terminal is
113 if (m_terminal
&& m_konsolePart
&& m_terminalWidget
) {
114 const auto guiClients
= m_konsolePart
->childClients();
115 for (auto *client
: guiClients
) {
116 if (client
->actionCollection()->associatedWidgets().contains(m_terminalWidget
)) {
117 return client
->actionCollection();
124 bool TerminalPanel::hasProgramRunning() const
126 return m_terminal
&& (m_terminal
->foregroundProcessId() != -1);
129 bool TerminalPanel::urlChanged()
131 if (!url().isValid()) {
135 const bool sendInput
= m_terminal
&& !hasProgramRunning() && isVisible();
143 void TerminalPanel::showEvent(QShowEvent
*event
)
145 if (event
->spontaneous()) {
146 Panel::showEvent(event
);
151 m_clearTerminal
= true;
152 KPluginFactory
*factory
= KPluginFactory::loadFactory(KPluginMetaData(QStringLiteral("kf6/parts/konsolepart"))).plugin
;
153 m_konsolePart
= factory
? (factory
->create
<KParts::ReadOnlyPart
>(this)) : nullptr;
155 connect(m_konsolePart
, &KParts::ReadOnlyPart::destroyed
, this, &TerminalPanel::terminalExited
);
156 m_terminalWidget
= m_konsolePart
->widget();
157 setFocusProxy(m_terminalWidget
);
158 m_layout
->addWidget(m_terminalWidget
);
159 if (m_konsolePartMissingMessage
) {
160 m_layout
->removeWidget(m_konsolePartMissingMessage
);
162 m_terminal
= qobject_cast
<TerminalInterface
*>(m_konsolePart
);
164 // needed to collect the correct KonsolePart actionCollection
165 // namely the one of the single inner terminal and not the outer KonsolePart
166 if (!m_konsolePart
->factory() && m_terminalWidget
) {
167 if (!m_konsolePart
->clientBuilder()) {
168 m_konsolePart
->setClientBuilder(new KXMLGUIBuilder(m_terminalWidget
));
171 auto factory
= new KXMLGUIFactory(m_konsolePart
->clientBuilder(), this);
172 factory
->addClient(m_konsolePart
);
174 // Prevents the KXMLGui warning about removing the client
175 connect(m_terminalWidget
, &QObject::destroyed
, this, [factory
, this] {
176 factory
->removeClient(m_konsolePart
);
181 if (!m_konsolePartMissingMessage
) {
182 const auto konsoleInstallUrl
= QUrl("appstream://org.kde.konsole.desktop");
183 const auto konsoleNotInstalledText
= i18n(
184 "Terminal cannot be shown because Konsole is not installed. "
185 "Please install it and then reopen the panel.");
186 m_konsolePartMissingMessage
= new KMessageWidget(konsoleNotInstalledText
, this);
187 m_konsolePartMissingMessage
->setPosition(KMessageWidget::Footer
);
188 m_konsolePartMissingMessage
->setCloseButtonVisible(false);
189 m_konsolePartMissingMessage
->hide();
190 if (KIO::DesktopExecParser::hasSchemeHandler(konsoleInstallUrl
)) {
191 auto installKonsoleAction
= new QAction(i18n("Install Konsole"), this);
192 connect(installKonsoleAction
, &QAction::triggered
, [konsoleInstallUrl
]() {
193 QDesktopServices::openUrl(konsoleInstallUrl
);
195 m_konsolePartMissingMessage
->addAction(installKonsoleAction
);
197 m_layout
->addWidget(m_konsolePartMissingMessage
);
198 m_layout
->setSizeConstraint(QLayout::SetMaximumSize
);
201 m_konsolePartMissingMessage
->animatedShow();
205 m_terminal
->showShellInDir(url().toLocalFile());
206 if (!hasProgramRunning()) {
209 m_terminalWidget
->setFocus();
210 connect(m_konsolePart
, SIGNAL(currentDirectoryChanged(QString
)), this, SLOT(slotKonsolePartCurrentDirectoryChanged(QString
)));
213 Panel::showEvent(event
);
216 void TerminalPanel::changeDir(const QUrl
&url
)
218 delete m_mostLocalUrlJob
;
219 m_mostLocalUrlJob
= nullptr;
221 if (url
.isLocalFile()) {
222 sendCdToTerminal(url
.toLocalFile());
226 // Try stat'ing the url; note that mostLocalUrl only works with ":local" protocols
227 if (KProtocolInfo::protocolClass(url
.scheme()) == QLatin1String(":local")) {
228 m_mostLocalUrlJob
= KIO::mostLocalUrl(url
, KIO::HideProgressInfo
);
229 if (m_mostLocalUrlJob
->uiDelegate()) {
230 KJobWidgets::setWindow(m_mostLocalUrlJob
, this);
232 connect(m_mostLocalUrlJob
, &KIO::StatJob::result
, this, &TerminalPanel::slotMostLocalUrlResult
);
236 // Last chance, try KIOFuse
237 sendCdToTerminalKIOFuse(url
);
240 void TerminalPanel::sendCdToTerminal(const QString
&dir
, HistoryPolicy addToHistory
)
242 if (dir
== m_konsolePartCurrentDirectory
// We are already there
243 && m_sendCdToTerminalHistory
.isEmpty() // …and that is not because the terminal couldn't keep up
245 m_clearTerminal
= false;
249 // Send prior Ctrl-E, Ctrl-U to ensure the line is empty. This is
250 // mandatory, otherwise sending a 'cd x\n' to a prompt with 'rm -rf *'
251 // would result in data loss.
252 m_terminal
->sendInput(QStringLiteral("\x05\x15"));
254 // We want to ignore the currentDirectoryChanged(QString) signal, which we will receive after
255 // the directory change, because this directory change is not caused by a "cd" command that the
256 // user entered in the panel. Therefore, we have to remember 'dir'. Note that it could also be
257 // a symbolic link -> remember the 'canonical' path.
258 if (addToHistory
== HistoryPolicy::AddToHistory
)
259 m_sendCdToTerminalHistory
.enqueue(QDir(dir
).canonicalPath());
261 m_terminal
->sendInput(" cd " + KShell::quoteArg(dir
) + '\r');
263 if (m_clearTerminal
) {
264 m_terminal
->sendInput(QStringLiteral(" clear\r"));
265 m_clearTerminal
= false;
269 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();
346 #include "moc_terminalpanel.cpp"