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