]> cloud.milkyroute.net Git - dolphin.git/blob - src/panels/terminal/terminalpanel.cpp
Fix terminal panel not keeping up with dir changes
[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 <KIO/JobUiDelegate>
13 #include <KJobWidgets>
14 #include <KLocalizedString>
15 #include <KMessageWidget>
16 #include <KMountPoint>
17 #include <KParts/ReadOnlyPart>
18 #include <KPluginFactory>
19 #include <KProtocolInfo>
20 #include <KShell>
21 #include <KXMLGUIBuilder>
22 #include <KXMLGUIFactory>
23 #include <kde_terminal_interface.h>
24
25 #include <QAction>
26 #include <QDesktopServices>
27 #include <QDir>
28 #include <QLabel>
29 #include <QShowEvent>
30 #include <QTimer>
31 #include <QVBoxLayout>
32
33 TerminalPanel::TerminalPanel(QWidget* parent) :
34 Panel(parent),
35 m_clearTerminal(true),
36 m_mostLocalUrlJob(nullptr),
37 m_layout(nullptr),
38 m_terminal(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())
47 {
48 m_layout = new QVBoxLayout(this);
49 m_layout->setContentsMargins(0, 0, 0, 0);
50 }
51
52 TerminalPanel::~TerminalPanel()
53 {
54 }
55
56 void TerminalPanel::goHome()
57 {
58 sendCdToTerminal(QDir::homePath(), HistoryPolicy::SkipHistory);
59 }
60
61 QString TerminalPanel::currentWorkingDirectory()
62 {
63 if (m_terminal) {
64 return m_terminal->currentWorkingDirectory();
65 }
66 return QString();
67 }
68
69 void TerminalPanel::terminalExited()
70 {
71 m_terminal = nullptr;
72 Q_EMIT hideTerminalPanel();
73 }
74
75 bool TerminalPanel::isHiddenInVisibleWindow() const
76 {
77 return parentWidget()
78 && 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() && 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)));
89
90 // Make sure this terminal does not prevent unmounting any removable drives
91 changeDir(QUrl::fromLocalFile(QStringLiteral("/")));
92
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 = '/';
98 }
99 }
100
101 QString TerminalPanel::runningProgramName() const
102 {
103 return m_terminal ? m_terminal->foregroundProcessName() : QString();
104 }
105
106 KActionCollection *TerminalPanel::actionCollection()
107 {
108 // m_terminal is the only reference reset to nullptr in case the terminal is
109 // closed again
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();
115 }
116 }
117 }
118 return nullptr;
119 }
120
121 bool TerminalPanel::hasProgramRunning() const
122 {
123 return m_terminal && (m_terminal->foregroundProcessId() != -1);
124 }
125
126 bool TerminalPanel::urlChanged()
127 {
128 if (!url().isValid()) {
129 return false;
130 }
131
132 const bool sendInput = m_terminal && !hasProgramRunning() && isVisible();
133 if (sendInput) {
134 changeDir(url());
135 }
136
137 return true;
138 }
139
140 void TerminalPanel::showEvent(QShowEvent* event)
141 {
142 if (event->spontaneous()) {
143 Panel::showEvent(event);
144 return;
145 }
146
147 if (!m_terminal) {
148 m_clearTerminal = true;
149 KPluginFactory *factory = KPluginFactory::loadFactory(KPluginMetaData(QStringLiteral("konsolepart"))).plugin;
150 m_konsolePart = factory ? (factory->create<KParts::ReadOnlyPart>(this)) : nullptr;
151 if (m_konsolePart) {
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);
158 }
159 m_terminal = qobject_cast<TerminalInterface*>(m_konsolePart);
160
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));
166 }
167
168 auto factory = new KXMLGUIFactory(m_konsolePart->clientBuilder(), this);
169 factory->addClient(m_konsolePart);
170
171 // Prevents the KXMLGui warning about removing the client
172 connect(m_terminalWidget, &QObject::destroyed, this, [factory, this] {
173 factory->removeClient(m_konsolePart);
174 });
175 }
176
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);
188 });
189 m_konsolePartMissingMessage->addAction(installKonsoleAction);
190 }
191 m_layout->addWidget(m_konsolePartMissingMessage);
192 m_layout->addStretch();
193 QTimer::singleShot(0, m_konsolePartMissingMessage, &KMessageWidget::animatedShow);
194 } else {
195 m_konsolePartMissingMessage->animatedShow();
196 }
197 }
198 if (m_terminal) {
199 m_terminal->showShellInDir(url().toLocalFile());
200 if(!hasProgramRunning()) {
201 changeDir(url());
202 }
203 m_terminalWidget->setFocus();
204 connect(m_konsolePart, SIGNAL(currentDirectoryChanged(QString)),
205 this, SLOT(slotKonsolePartCurrentDirectoryChanged(QString)));
206 }
207
208 Panel::showEvent(event);
209 }
210
211 void TerminalPanel::changeDir(const QUrl& url)
212 {
213 delete m_mostLocalUrlJob;
214 m_mostLocalUrlJob = nullptr;
215
216 if (url.isLocalFile()) {
217 sendCdToTerminal(url.toLocalFile());
218 return;
219 }
220
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);
226 }
227 connect(m_mostLocalUrlJob, &KIO::StatJob::result, this, &TerminalPanel::slotMostLocalUrlResult);
228 return;
229 }
230
231 // Last chance, try KIOFuse
232 sendCdToTerminalKIOFuse(url);
233 }
234
235 void TerminalPanel::sendCdToTerminal(const QString& dir, HistoryPolicy addToHistory)
236 {
237 if (dir == m_konsolePartCurrentDirectory // We are already there
238 && m_sendCdToTerminalHistory.isEmpty() // …and that is not because the terminal couldn't keep up
239 ) {
240 m_clearTerminal = false;
241 return;
242 }
243
244 #ifndef Q_OS_WIN
245 if (!m_clearTerminal) {
246 // The TerminalV2 interface does not provide a way to delete the
247 // current line before sending a new input. This is mandatory,
248 // otherwise sending a 'cd x' to a existing 'rm -rf *' might
249 // result in data loss. As workaround SIGINT is sent.
250 const int processId = m_terminal->terminalProcessId();
251 if (processId > 0) {
252 kill(processId, SIGINT);
253 }
254 }
255 #endif
256
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());
263
264 m_terminal->sendInput(" cd " + KShell::quoteArg(dir) + '\n');
265
266 if (m_clearTerminal) {
267 m_terminal->sendInput(QStringLiteral(" clear\n"));
268 m_clearTerminal = false;
269 }
270 }
271
272 void TerminalPanel::sendCdToTerminalKIOFuse(const QUrl &url) {
273 // URL isn't local, only hope for the terminal to be in sync with the
274 // DolphinView is to mount the remote URL in KIOFuse and point to it.
275 // If we can't do that for any reason, silently fail.
276 auto reply = m_kiofuseInterface.mountUrl(url.toString());
277 QDBusPendingCallWatcher * watcher = new QDBusPendingCallWatcher(reply, this);
278 QObject::connect(watcher, &QDBusPendingCallWatcher::finished, this, [=] (QDBusPendingCallWatcher* watcher) {
279 watcher->deleteLater();
280 if (!reply.isError()) {
281 // Successfully mounted, point to the KIOFuse equivalent path.
282 sendCdToTerminal(reply.value());
283 }
284 });
285 }
286
287 void TerminalPanel::slotMostLocalUrlResult(KJob* job)
288 {
289 KIO::StatJob* statJob = static_cast<KIO::StatJob *>(job);
290 const QUrl url = statJob->mostLocalUrl();
291 if (url.isLocalFile()) {
292 sendCdToTerminal(url.toLocalFile());
293 } else {
294 sendCdToTerminalKIOFuse(url);
295 }
296
297 m_mostLocalUrlJob = nullptr;
298 }
299
300 void TerminalPanel::slotKonsolePartCurrentDirectoryChanged(const QString& dir)
301 {
302 m_konsolePartCurrentDirectory = QDir(dir).canonicalPath();
303
304 // Only emit a changeUrl signal if the directory change was caused by the user inside the
305 // terminal, and not by sendCdToTerminal(QString).
306 while (!m_sendCdToTerminalHistory.empty()) {
307 if (m_konsolePartCurrentDirectory == m_sendCdToTerminalHistory.dequeue()) {
308 return;
309 }
310 }
311
312 // User may potentially be browsing inside a KIOFuse mount.
313 // If so lets try and change the DolphinView to point to the remote URL equivalent.
314 // instead of into the KIOFuse mount itself (which can cause performance issues!)
315 const QUrl url(QUrl::fromLocalFile(dir));
316
317 KMountPoint::Ptr mountPoint = KMountPoint::currentMountPoints().findByPath(m_konsolePartCurrentDirectory);
318 if (mountPoint && mountPoint->mountType() != QStringLiteral("fuse.kio-fuse")) {
319 // Not in KIOFUse mount, so just switch to the corresponding URL.
320 Q_EMIT changeUrl(url);
321 return;
322 }
323
324 auto reply = m_kiofuseInterface.remoteUrl(m_konsolePartCurrentDirectory);
325 QDBusPendingCallWatcher * watcher = new QDBusPendingCallWatcher(reply, this);
326 QObject::connect(watcher, &QDBusPendingCallWatcher::finished, this, [=] (QDBusPendingCallWatcher* watcher) {
327 watcher->deleteLater();
328 if (reply.isError()) {
329 // KIOFuse errored out... just show the normal URL
330 Q_EMIT changeUrl(url);
331 } else {
332 // Our location happens to be in a KIOFuse mount and is mounted.
333 // Let's change the DolphinView to point to the remote URL equivalent.
334 Q_EMIT changeUrl(QUrl::fromUserInput(reply.value()));
335 }
336 });
337 }
338
339 bool TerminalPanel::terminalHasFocus() const
340 {
341 if (m_terminalWidget) {
342 return m_terminalWidget->hasFocus();
343 }
344
345 return hasFocus();
346 }