]> cloud.milkyroute.net Git - dolphin.git/blob - src/panels/terminal/terminalpanel.cpp
Merge branch 'release/20.08' into master
[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 #include "kiofuse_interface.h"
9
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 <KPluginLoader>
20 #include <KProtocolInfo>
21 #include <KService>
22 #include <KShell>
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 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 bool TerminalPanel::hasProgramRunning() const
107 {
108 return m_terminal && (m_terminal->foregroundProcessId() != -1);
109 }
110
111 bool TerminalPanel::urlChanged()
112 {
113 if (!url().isValid()) {
114 return false;
115 }
116
117 const bool sendInput = m_terminal && !hasProgramRunning() && isVisible();
118 if (sendInput) {
119 changeDir(url());
120 }
121
122 return true;
123 }
124
125 void TerminalPanel::showEvent(QShowEvent* event)
126 {
127 if (event->spontaneous()) {
128 Panel::showEvent(event);
129 return;
130 }
131
132 if (!m_terminal) {
133 m_clearTerminal = true;
134 KPluginFactory* factory = nullptr;
135 KService::Ptr service = KService::serviceByDesktopName(QStringLiteral("konsolepart"));
136 if (service) {
137 factory = KPluginLoader(service->library()).factory();
138 }
139 m_konsolePart = factory ? (factory->create<KParts::ReadOnlyPart>(this)) : nullptr;
140 if (m_konsolePart) {
141 connect(m_konsolePart, &KParts::ReadOnlyPart::destroyed, this, &TerminalPanel::terminalExited);
142 m_terminalWidget = m_konsolePart->widget();
143 setFocusProxy(m_terminalWidget);
144 m_layout->addWidget(m_terminalWidget);
145 if (m_konsolePartMissingMessage) {
146 m_layout->removeWidget(m_konsolePartMissingMessage);
147 }
148 m_terminal = qobject_cast<TerminalInterface*>(m_konsolePart);
149 } else if (!m_konsolePartMissingMessage) {
150 const auto konsoleInstallUrl = QUrl("appstream://org.kde.konsole.desktop");
151 const auto konsoleNotInstalledText = i18n("Terminal cannot be shown because Konsole is not installed. "
152 "Please install it and then reopen the panel.");
153 m_konsolePartMissingMessage = new KMessageWidget(konsoleNotInstalledText, this);
154 m_konsolePartMissingMessage->setCloseButtonVisible(false);
155 m_konsolePartMissingMessage->hide();
156 if (KIO::DesktopExecParser::hasSchemeHandler(konsoleInstallUrl)) {
157 auto installKonsoleAction = new QAction(i18n("Install Konsole"), this);
158 connect(installKonsoleAction, &QAction::triggered, [konsoleInstallUrl]() {
159 QDesktopServices::openUrl(konsoleInstallUrl);
160 });
161 m_konsolePartMissingMessage->addAction(installKonsoleAction);
162 }
163 m_layout->addWidget(m_konsolePartMissingMessage);
164 m_layout->addStretch();
165 QTimer::singleShot(0, m_konsolePartMissingMessage, &KMessageWidget::animatedShow);
166 } else {
167 m_konsolePartMissingMessage->animatedShow();
168 }
169 }
170 if (m_terminal) {
171 m_terminal->showShellInDir(url().toLocalFile());
172 if(!hasProgramRunning()) {
173 changeDir(url());
174 }
175 m_terminalWidget->setFocus();
176 connect(m_konsolePart, SIGNAL(currentDirectoryChanged(QString)),
177 this, SLOT(slotKonsolePartCurrentDirectoryChanged(QString)));
178 }
179
180 Panel::showEvent(event);
181 }
182
183 void TerminalPanel::changeDir(const QUrl& url)
184 {
185 delete m_mostLocalUrlJob;
186 m_mostLocalUrlJob = nullptr;
187
188 if (url.isLocalFile()) {
189 sendCdToTerminal(url.toLocalFile());
190 return;
191 }
192
193 // Try stat'ing the url; note that mostLocalUrl only works with ":local" protocols
194 if (KProtocolInfo::protocolClass(url.scheme()) == QLatin1String(":local")) {
195 m_mostLocalUrlJob = KIO::mostLocalUrl(url, KIO::HideProgressInfo);
196 if (m_mostLocalUrlJob->uiDelegate()) {
197 KJobWidgets::setWindow(m_mostLocalUrlJob, this);
198 }
199 connect(m_mostLocalUrlJob, &KIO::StatJob::result, this, &TerminalPanel::slotMostLocalUrlResult);
200 return;
201 }
202
203 // Last chance, try KIOFuse
204 sendCdToTerminalKIOFuse(url);
205 }
206
207 void TerminalPanel::sendCdToTerminal(const QString& dir, HistoryPolicy addToHistory)
208 {
209 if (dir == m_konsolePartCurrentDirectory) {
210 m_clearTerminal = false;
211 return;
212 }
213
214 #ifndef Q_OS_WIN
215 if (!m_clearTerminal) {
216 // The TerminalV2 interface does not provide a way to delete the
217 // current line before sending a new input. This is mandatory,
218 // otherwise sending a 'cd x' to a existing 'rm -rf *' might
219 // result in data loss. As workaround SIGINT is sent.
220 const int processId = m_terminal->terminalProcessId();
221 if (processId > 0) {
222 kill(processId, SIGINT);
223 }
224 }
225 #endif
226
227 m_terminal->sendInput(" cd " + KShell::quoteArg(dir) + '\n');
228
229 // We want to ignore the currentDirectoryChanged(QString) signal, which we will receive after
230 // the directory change, because this directory change is not caused by a "cd" command that the
231 // user entered in the panel. Therefore, we have to remember 'dir'. Note that it could also be
232 // a symbolic link -> remember the 'canonical' path.
233 if (addToHistory == HistoryPolicy::AddToHistory)
234 m_sendCdToTerminalHistory.enqueue(QDir(dir).canonicalPath());
235
236 if (m_clearTerminal) {
237 m_terminal->sendInput(QStringLiteral(" clear\n"));
238 m_clearTerminal = false;
239 }
240 }
241
242 void TerminalPanel::sendCdToTerminalKIOFuse(const QUrl &url) {
243 // URL isn't local, only hope for the terminal to be in sync with the
244 // DolphinView is to mount the remote URL in KIOFuse and point to it.
245 // If we can't do that for any reason, silently fail.
246 auto reply = m_kiofuseInterface.mountUrl(url.toString());
247 QDBusPendingCallWatcher * watcher = new QDBusPendingCallWatcher(reply, this);
248 QObject::connect(watcher, &QDBusPendingCallWatcher::finished, this, [=] (QDBusPendingCallWatcher* watcher) {
249 watcher->deleteLater();
250 if (!reply.isError()) {
251 // Successfully mounted, point to the KIOFuse equivalent path.
252 sendCdToTerminal(reply.value());
253 }
254 });
255 }
256
257 void TerminalPanel::slotMostLocalUrlResult(KJob* job)
258 {
259 KIO::StatJob* statJob = static_cast<KIO::StatJob *>(job);
260 const QUrl url = statJob->mostLocalUrl();
261 if (url.isLocalFile()) {
262 sendCdToTerminal(url.toLocalFile());
263 } else {
264 sendCdToTerminalKIOFuse(url);
265 }
266
267 m_mostLocalUrlJob = nullptr;
268 }
269
270 void TerminalPanel::slotKonsolePartCurrentDirectoryChanged(const QString& dir)
271 {
272 m_konsolePartCurrentDirectory = QDir(dir).canonicalPath();
273
274 // Only emit a changeUrl signal if the directory change was caused by the user inside the
275 // terminal, and not by sendCdToTerminal(QString).
276 while (!m_sendCdToTerminalHistory.empty()) {
277 if (m_konsolePartCurrentDirectory == m_sendCdToTerminalHistory.dequeue()) {
278 return;
279 }
280 }
281
282 // User may potentially be browsing inside a KIOFuse mount.
283 // If so lets try and change the DolphinView to point to the remote URL equivalent.
284 // instead of into the KIOFuse mount itself (which can cause performance issues!)
285 const QUrl url(QUrl::fromLocalFile(dir));
286
287 KMountPoint::Ptr mountPoint = KMountPoint::currentMountPoints().findByPath(m_konsolePartCurrentDirectory);
288 if (mountPoint && mountPoint->mountType() != QStringLiteral("fuse.kio-fuse")) {
289 // Not in KIOFUse mount, so just switch to the corresponding URL.
290 emit changeUrl(url);
291 return;
292 }
293
294 auto reply = m_kiofuseInterface.remoteUrl(m_konsolePartCurrentDirectory);
295 QDBusPendingCallWatcher * watcher = new QDBusPendingCallWatcher(reply, this);
296 QObject::connect(watcher, &QDBusPendingCallWatcher::finished, this, [=] (QDBusPendingCallWatcher* watcher) {
297 watcher->deleteLater();
298 if (reply.isError()) {
299 // KIOFuse errored out... just show the normal URL
300 emit changeUrl(url);
301 } else {
302 // Our location happens to be in a KIOFuse mount and is mounted.
303 // Let's change the DolphinView to point to the remote URL equivalent.
304 emit changeUrl(QUrl::fromUserInput(reply.value()));
305 }
306 });
307 }
308
309 bool TerminalPanel::terminalHasFocus() const
310 {
311 if (m_terminalWidget) {
312 return m_terminalWidget->hasFocus();
313 }
314
315 return hasFocus();
316 }