]> cloud.milkyroute.net Git - dolphin.git/blob - src/panels/terminal/terminalpanel.cpp
Merge branch 'release/21.12'
[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) {
238 m_clearTerminal = false;
239 return;
240 }
241
242 #ifndef Q_OS_WIN
243 if (!m_clearTerminal) {
244 // The TerminalV2 interface does not provide a way to delete the
245 // current line before sending a new input. This is mandatory,
246 // otherwise sending a 'cd x' to a existing 'rm -rf *' might
247 // result in data loss. As workaround SIGINT is sent.
248 const int processId = m_terminal->terminalProcessId();
249 if (processId > 0) {
250 kill(processId, SIGINT);
251 }
252 }
253 #endif
254
255 m_terminal->sendInput(" cd " + KShell::quoteArg(dir) + '\n');
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 if (m_clearTerminal) {
265 m_terminal->sendInput(QStringLiteral(" clear\n"));
266 m_clearTerminal = false;
267 }
268 }
269
270 void TerminalPanel::sendCdToTerminalKIOFuse(const QUrl &url) {
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 }