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