]> cloud.milkyroute.net Git - dolphin.git/blob - src/panels/terminal/terminalpanel.cpp
Switch to C++20
[dolphin.git] / src / panels / terminal / terminalpanel.cpp
1 /*
2 * SPDX-FileCopyrightText: 2007-2010 Peter Penz <peter.penz19@gmail.com>
3 *
4 * SPDX-License-Identifier: GPL-2.0-or-later
5 */
6
7 #include "terminalpanel.h"
8
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>
19 #include <KShell>
20 #include <KXMLGUIBuilder>
21 #include <KXMLGUIFactory>
22 #include <kde_terminal_interface.h>
23
24 #include <QAction>
25 #include <QDesktopServices>
26 #include <QDir>
27 #include <QShowEvent>
28 #include <QTimer>
29 #include <QVBoxLayout>
30
31 TerminalPanel::TerminalPanel(QWidget *parent)
32 : Panel(parent)
33 , m_clearTerminal(true)
34 , m_mostLocalUrlJob(nullptr)
35 , m_layout(nullptr)
36 , m_terminal(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())
43 {
44 m_layout = new QVBoxLayout(this);
45 m_layout->setContentsMargins(0, 0, 0, 0);
46 }
47
48 TerminalPanel::~TerminalPanel()
49 {
50 if (m_konsolePart) {
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);
54 }
55 }
56
57 void TerminalPanel::goHome()
58 {
59 sendCdToTerminal(QDir::homePath(), HistoryPolicy::SkipHistory);
60 }
61
62 bool TerminalPanel::currentWorkingDirectoryIsChildOf(const QString &path) const
63 {
64 if (m_terminal) {
65 return m_terminal->currentWorkingDirectory().startsWith(path);
66 }
67 return false;
68 }
69
70 void TerminalPanel::terminalExited()
71 {
72 m_terminal = nullptr;
73 m_konsolePart = nullptr;
74 Q_EMIT hideTerminalPanel();
75 }
76
77 bool TerminalPanel::isHiddenInVisibleWindow() const
78 {
79 return parentWidget() && parentWidget()->isHidden();
80 }
81
82 void TerminalPanel::dockVisibilityChanged()
83 {
84 // Only react when the DockWidget itself (not some parent) is hidden. This way we don't
85 // respond when e.g. Dolphin is minimized.
86 if (isHiddenInVisibleWindow()) {
87 if (m_konsolePartMissingMessage) {
88 m_konsolePartMissingMessage->hide();
89 } else if (m_terminal && !hasProgramRunning()) {
90 // Make sure that the following "cd /" command will not affect the view.
91 disconnect(m_konsolePart, SIGNAL(currentDirectoryChanged(QString)), this, SLOT(slotKonsolePartCurrentDirectoryChanged(QString)));
92
93 // Make sure this terminal does not prevent unmounting any removable drives
94 changeDir(QUrl::fromLocalFile(QStringLiteral("/")));
95
96 // Because we have disconnected from the part's currentDirectoryChanged()
97 // signal, we have to update m_konsolePartCurrentDirectory manually. If this
98 // was not done, showing the panel again might not set the part's working
99 // directory correctly.
100 m_konsolePartCurrentDirectory = '/';
101 }
102 }
103 }
104
105 QString TerminalPanel::runningProgramName() const
106 {
107 return m_terminal ? m_terminal->foregroundProcessName() : QString();
108 }
109
110 KActionCollection *TerminalPanel::actionCollection()
111 {
112 // m_terminal is the only reference reset to nullptr in case the terminal is
113 // closed again
114 if (m_terminal && m_konsolePart && m_terminalWidget) {
115 const auto guiClients = m_konsolePart->childClients();
116 for (auto *client : guiClients) {
117 if (client->actionCollection()->associatedWidgets().contains(m_terminalWidget)) {
118 return client->actionCollection();
119 }
120 }
121 }
122 return nullptr;
123 }
124
125 bool TerminalPanel::hasProgramRunning() const
126 {
127 return m_terminal && (m_terminal->foregroundProcessId() != -1);
128 }
129
130 bool TerminalPanel::urlChanged()
131 {
132 if (!url().isValid()) {
133 return false;
134 }
135
136 const bool sendInput = m_terminal && !hasProgramRunning() && isVisible();
137 if (sendInput) {
138 changeDir(url());
139 }
140
141 return true;
142 }
143
144 void TerminalPanel::showEvent(QShowEvent *event)
145 {
146 if (event->spontaneous()) {
147 Panel::showEvent(event);
148 return;
149 }
150
151 if (!m_terminal) {
152 m_clearTerminal = true;
153 KPluginFactory *factory = KPluginFactory::loadFactory(KPluginMetaData(QStringLiteral("kf6/parts/konsolepart"))).plugin;
154 m_konsolePart = factory ? (factory->create<KParts::ReadOnlyPart>(this)) : nullptr;
155 if (m_konsolePart) {
156 connect(m_konsolePart, &KParts::ReadOnlyPart::destroyed, this, &TerminalPanel::terminalExited);
157 m_terminalWidget = m_konsolePart->widget();
158 setFocusProxy(m_terminalWidget);
159 m_layout->addWidget(m_terminalWidget);
160 if (m_konsolePartMissingMessage) {
161 m_layout->removeWidget(m_konsolePartMissingMessage);
162 }
163 m_terminal = qobject_cast<TerminalInterface *>(m_konsolePart);
164
165 // needed to collect the correct KonsolePart actionCollection
166 // namely the one of the single inner terminal and not the outer KonsolePart
167 if (!m_konsolePart->factory() && m_terminalWidget) {
168 if (!m_konsolePart->clientBuilder()) {
169 m_konsolePart->setClientBuilder(new KXMLGUIBuilder(m_terminalWidget));
170 }
171
172 auto factory = new KXMLGUIFactory(m_konsolePart->clientBuilder(), this);
173 factory->addClient(m_konsolePart);
174
175 // Prevents the KXMLGui warning about removing the client
176 connect(m_terminalWidget, &QObject::destroyed, this, [factory, this] {
177 factory->removeClient(m_konsolePart);
178 });
179 }
180
181 } else {
182 if (!m_konsolePartMissingMessage) {
183 const auto konsoleInstallUrl = QUrl("appstream://org.kde.konsole.desktop");
184 const auto konsoleNotInstalledText = i18n(
185 "Terminal cannot be shown because Konsole is not installed. "
186 "Please install it and then reopen the panel.");
187 m_konsolePartMissingMessage = new KMessageWidget(konsoleNotInstalledText, this);
188 m_konsolePartMissingMessage->setPosition(KMessageWidget::Footer);
189 m_konsolePartMissingMessage->setCloseButtonVisible(false);
190 m_konsolePartMissingMessage->hide();
191 if (KIO::DesktopExecParser::hasSchemeHandler(konsoleInstallUrl)) {
192 auto installKonsoleAction = new QAction(i18n("Install Konsole"), this);
193 connect(installKonsoleAction, &QAction::triggered, [konsoleInstallUrl]() {
194 QDesktopServices::openUrl(konsoleInstallUrl);
195 });
196 m_konsolePartMissingMessage->addAction(installKonsoleAction);
197 }
198 m_layout->addWidget(m_konsolePartMissingMessage);
199 m_layout->setSizeConstraint(QLayout::SetMaximumSize);
200 }
201
202 m_konsolePartMissingMessage->animatedShow();
203 }
204 }
205 if (m_terminal) {
206 m_terminal->showShellInDir(url().toLocalFile());
207 if (!hasProgramRunning()) {
208 changeDir(url());
209 }
210 m_terminalWidget->setFocus();
211 connect(m_konsolePart, SIGNAL(currentDirectoryChanged(QString)), this, SLOT(slotKonsolePartCurrentDirectoryChanged(QString)));
212 }
213
214 Panel::showEvent(event);
215 }
216
217 void TerminalPanel::changeDir(const QUrl &url)
218 {
219 delete m_mostLocalUrlJob;
220 m_mostLocalUrlJob = nullptr;
221
222 if (url.isEmpty()) {
223 return;
224 }
225
226 if (url.isLocalFile()) {
227 sendCdToTerminal(url.toLocalFile());
228 return;
229 }
230
231 // Try stat'ing the url; note that mostLocalUrl only works with ":local" protocols
232 if (KProtocolInfo::protocolClass(url.scheme()) == QLatin1String(":local")) {
233 m_mostLocalUrlJob = KIO::mostLocalUrl(url, KIO::HideProgressInfo);
234 if (m_mostLocalUrlJob->uiDelegate()) {
235 KJobWidgets::setWindow(m_mostLocalUrlJob, this);
236 }
237 connect(m_mostLocalUrlJob, &KIO::StatJob::result, this, &TerminalPanel::slotMostLocalUrlResult);
238 return;
239 }
240
241 // Last chance, try KIOFuse
242 sendCdToTerminalKIOFuse(url);
243 }
244
245 void TerminalPanel::sendCdToTerminal(const QString &dir, HistoryPolicy addToHistory)
246 {
247 if (dir == m_konsolePartCurrentDirectory // We are already there
248 && m_sendCdToTerminalHistory.isEmpty() // …and that is not because the terminal couldn't keep up
249 ) {
250 m_clearTerminal = false;
251 return;
252 }
253
254 // Send prior Ctrl-E, Ctrl-U to ensure the line is empty. This is
255 // mandatory, otherwise sending a 'cd x\n' to a prompt with 'rm -rf *'
256 // would result in data loss.
257 m_terminal->sendInput(QStringLiteral("\x05\x15"));
258
259 // We want to ignore the currentDirectoryChanged(QString) signal, which we will receive after
260 // the directory change, because this directory change is not caused by a "cd" command that the
261 // user entered in the panel. Therefore, we have to remember 'dir'. Note that it could also be
262 // a symbolic link -> remember the 'canonical' path.
263 if (addToHistory == HistoryPolicy::AddToHistory)
264 m_sendCdToTerminalHistory.enqueue(QDir(dir).canonicalPath());
265
266 m_terminal->sendInput(" cd " + KShell::quoteArg(dir) + '\r');
267
268 if (m_clearTerminal) {
269 m_terminal->sendInput(QStringLiteral(" clear\r"));
270 m_clearTerminal = false;
271 }
272 }
273
274 void TerminalPanel::sendCdToTerminalKIOFuse(const QUrl &url)
275 {
276 // URL isn't local, only hope for the terminal to be in sync with the
277 // DolphinView is to mount the remote URL in KIOFuse and point to it.
278 // If we can't do that for any reason, silently fail.
279 auto reply = m_kiofuseInterface.mountUrl(url.toString());
280 QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(reply, this);
281 QObject::connect(watcher, &QDBusPendingCallWatcher::finished, this, [=, this](QDBusPendingCallWatcher *watcher) {
282 watcher->deleteLater();
283 if (!reply.isError()) {
284 // Successfully mounted, point to the KIOFuse equivalent path.
285 sendCdToTerminal(reply.value());
286 }
287 });
288 }
289
290 void TerminalPanel::slotMostLocalUrlResult(KJob *job)
291 {
292 KIO::StatJob *statJob = static_cast<KIO::StatJob *>(job);
293 const QUrl url = statJob->mostLocalUrl();
294 if (url.isLocalFile()) {
295 sendCdToTerminal(url.toLocalFile());
296 } else {
297 sendCdToTerminalKIOFuse(url);
298 }
299
300 m_mostLocalUrlJob = nullptr;
301 }
302
303 void TerminalPanel::slotKonsolePartCurrentDirectoryChanged(const QString &dir)
304 {
305 m_konsolePartCurrentDirectory = QDir(dir).canonicalPath();
306
307 // Only emit a changeUrl signal if the directory change was caused by the user inside the
308 // terminal, and not by sendCdToTerminal(QString).
309 while (!m_sendCdToTerminalHistory.empty()) {
310 if (m_konsolePartCurrentDirectory == m_sendCdToTerminalHistory.dequeue()) {
311 return;
312 }
313 }
314
315 // User may potentially be browsing inside a KIOFuse mount.
316 // If so lets try and change the DolphinView to point to the remote URL equivalent.
317 // instead of into the KIOFuse mount itself (which can cause performance issues!)
318 const QUrl url(QUrl::fromLocalFile(dir));
319
320 KMountPoint::Ptr mountPoint = KMountPoint::currentMountPoints().findByPath(m_konsolePartCurrentDirectory);
321 if (mountPoint && mountPoint->mountType() != QStringLiteral("fuse.kio-fuse")) {
322 // Not in KIOFUse mount, so just switch to the corresponding URL.
323 Q_EMIT changeUrl(url);
324 return;
325 }
326
327 auto reply = m_kiofuseInterface.remoteUrl(m_konsolePartCurrentDirectory);
328 QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(reply, this);
329 QObject::connect(watcher, &QDBusPendingCallWatcher::finished, this, [=, this](QDBusPendingCallWatcher *watcher) {
330 watcher->deleteLater();
331 if (reply.isError()) {
332 // KIOFuse errored out... just show the normal URL
333 Q_EMIT changeUrl(url);
334 } else {
335 // Our location happens to be in a KIOFuse mount and is mounted.
336 // Let's change the DolphinView to point to the remote URL equivalent.
337 Q_EMIT changeUrl(QUrl::fromUserInput(reply.value()));
338 }
339 });
340 }
341
342 bool TerminalPanel::terminalHasFocus() const
343 {
344 if (m_terminalWidget) {
345 return m_terminalWidget->hasFocus();
346 }
347
348 return hasFocus();
349 }
350
351 #include "moc_terminalpanel.cpp"