]> cloud.milkyroute.net Git - dolphin.git/blob - src/panels/terminal/terminalpanel.cpp
Do not rely on KIO source-code compat code
[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 Q_EMIT hideTerminalPanel();
74 }
75
76 bool TerminalPanel::isHiddenInVisibleWindow() const
77 {
78 return parentWidget() && parentWidget()->isHidden();
79 }
80
81 void TerminalPanel::dockVisibilityChanged()
82 {
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)));
91
92 // Make sure this terminal does not prevent unmounting any removable drives
93 changeDir(QUrl::fromLocalFile(QStringLiteral("/")));
94
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 = '/';
100 }
101 }
102 }
103
104 QString TerminalPanel::runningProgramName() const
105 {
106 return m_terminal ? m_terminal->foregroundProcessName() : QString();
107 }
108
109 KActionCollection *TerminalPanel::actionCollection()
110 {
111 // m_terminal is the only reference reset to nullptr in case the terminal is
112 // closed again
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();
118 }
119 }
120 }
121 return nullptr;
122 }
123
124 bool TerminalPanel::hasProgramRunning() const
125 {
126 return m_terminal && (m_terminal->foregroundProcessId() != -1);
127 }
128
129 bool TerminalPanel::urlChanged()
130 {
131 if (!url().isValid()) {
132 return false;
133 }
134
135 const bool sendInput = m_terminal && !hasProgramRunning() && isVisible();
136 if (sendInput) {
137 changeDir(url());
138 }
139
140 return true;
141 }
142
143 void TerminalPanel::showEvent(QShowEvent *event)
144 {
145 if (event->spontaneous()) {
146 Panel::showEvent(event);
147 return;
148 }
149
150 if (!m_terminal) {
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;
154 if (m_konsolePart) {
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);
161 }
162 m_terminal = qobject_cast<TerminalInterface *>(m_konsolePart);
163
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));
169 }
170
171 auto factory = new KXMLGUIFactory(m_konsolePart->clientBuilder(), this);
172 factory->addClient(m_konsolePart);
173
174 // Prevents the KXMLGui warning about removing the client
175 connect(m_terminalWidget, &QObject::destroyed, this, [factory, this] {
176 factory->removeClient(m_konsolePart);
177 });
178 }
179
180 } else {
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);
194 });
195 m_konsolePartMissingMessage->addAction(installKonsoleAction);
196 }
197 m_layout->addWidget(m_konsolePartMissingMessage);
198 m_layout->setSizeConstraint(QLayout::SetMaximumSize);
199 }
200
201 m_konsolePartMissingMessage->animatedShow();
202 }
203 }
204 if (m_terminal) {
205 m_terminal->showShellInDir(url().toLocalFile());
206 if (!hasProgramRunning()) {
207 changeDir(url());
208 }
209 m_terminalWidget->setFocus();
210 connect(m_konsolePart, SIGNAL(currentDirectoryChanged(QString)), this, SLOT(slotKonsolePartCurrentDirectoryChanged(QString)));
211 }
212
213 Panel::showEvent(event);
214 }
215
216 void TerminalPanel::changeDir(const QUrl &url)
217 {
218 delete m_mostLocalUrlJob;
219 m_mostLocalUrlJob = nullptr;
220
221 if (url.isLocalFile()) {
222 sendCdToTerminal(url.toLocalFile());
223 return;
224 }
225
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);
231 }
232 connect(m_mostLocalUrlJob, &KIO::StatJob::result, this, &TerminalPanel::slotMostLocalUrlResult);
233 return;
234 }
235
236 // Last chance, try KIOFuse
237 sendCdToTerminalKIOFuse(url);
238 }
239
240 void TerminalPanel::sendCdToTerminal(const QString &dir, HistoryPolicy addToHistory)
241 {
242 if (dir == m_konsolePartCurrentDirectory // We are already there
243 && m_sendCdToTerminalHistory.isEmpty() // …and that is not because the terminal couldn't keep up
244 ) {
245 m_clearTerminal = false;
246 return;
247 }
248
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"));
253
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());
260
261 m_terminal->sendInput(" cd " + KShell::quoteArg(dir) + '\r');
262
263 if (m_clearTerminal) {
264 m_terminal->sendInput(QStringLiteral(" clear\r"));
265 m_clearTerminal = false;
266 }
267 }
268
269 void TerminalPanel::sendCdToTerminalKIOFuse(const QUrl &url)
270 {
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());
281 }
282 });
283 }
284
285 void TerminalPanel::slotMostLocalUrlResult(KJob *job)
286 {
287 KIO::StatJob *statJob = static_cast<KIO::StatJob *>(job);
288 const QUrl url = statJob->mostLocalUrl();
289 if (url.isLocalFile()) {
290 sendCdToTerminal(url.toLocalFile());
291 } else {
292 sendCdToTerminalKIOFuse(url);
293 }
294
295 m_mostLocalUrlJob = nullptr;
296 }
297
298 void TerminalPanel::slotKonsolePartCurrentDirectoryChanged(const QString &dir)
299 {
300 m_konsolePartCurrentDirectory = QDir(dir).canonicalPath();
301
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()) {
306 return;
307 }
308 }
309
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));
314
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);
319 return;
320 }
321
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);
329 } else {
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()));
333 }
334 });
335 }
336
337 bool TerminalPanel::terminalHasFocus() const
338 {
339 if (m_terminalWidget) {
340 return m_terminalWidget->hasFocus();
341 }
342
343 return hasFocus();
344 }
345
346 #include "moc_terminalpanel.cpp"