]> cloud.milkyroute.net Git - dolphin.git/blob - src/panels/terminal/terminalpanel.cpp
Merge branch 'master' into kf6
[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::currentWorkingDirectoryIsChildOf(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()) {
81 if (m_konsolePartMissingMessage) {
82 m_konsolePartMissingMessage->hide();
83 } else if (m_terminal && !hasProgramRunning()) {
84 // Make sure that the following "cd /" command will not affect the view.
85 disconnect(m_konsolePart, SIGNAL(currentDirectoryChanged(QString)), this, SLOT(slotKonsolePartCurrentDirectoryChanged(QString)));
86
87 // Make sure this terminal does not prevent unmounting any removable drives
88 changeDir(QUrl::fromLocalFile(QStringLiteral("/")));
89
90 // Because we have disconnected from the part's currentDirectoryChanged()
91 // signal, we have to update m_konsolePartCurrentDirectory manually. If this
92 // was not done, showing the panel again might not set the part's working
93 // directory correctly.
94 m_konsolePartCurrentDirectory = '/';
95 }
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("kf6/parts/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 {
176 if (!m_konsolePartMissingMessage) {
177 const auto konsoleInstallUrl = QUrl("appstream://org.kde.konsole.desktop");
178 const auto konsoleNotInstalledText = i18n(
179 "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->setSizeConstraint(QLayout::SetMaximumSize);
193 }
194
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)), this, SLOT(slotKonsolePartCurrentDirectoryChanged(QString)));
205 }
206
207 Panel::showEvent(event);
208 }
209
210 void TerminalPanel::changeDir(const QUrl &url)
211 {
212 delete m_mostLocalUrlJob;
213 m_mostLocalUrlJob = nullptr;
214
215 if (url.isLocalFile()) {
216 sendCdToTerminal(url.toLocalFile());
217 return;
218 }
219
220 // Try stat'ing the url; note that mostLocalUrl only works with ":local" protocols
221 if (KProtocolInfo::protocolClass(url.scheme()) == QLatin1String(":local")) {
222 m_mostLocalUrlJob = KIO::mostLocalUrl(url, KIO::HideProgressInfo);
223 if (m_mostLocalUrlJob->uiDelegate()) {
224 KJobWidgets::setWindow(m_mostLocalUrlJob, this);
225 }
226 connect(m_mostLocalUrlJob, &KIO::StatJob::result, this, &TerminalPanel::slotMostLocalUrlResult);
227 return;
228 }
229
230 // Last chance, try KIOFuse
231 sendCdToTerminalKIOFuse(url);
232 }
233
234 void TerminalPanel::sendCdToTerminal(const QString &dir, HistoryPolicy addToHistory)
235 {
236 if (dir == m_konsolePartCurrentDirectory // We are already there
237 && m_sendCdToTerminalHistory.isEmpty() // …and that is not because the terminal couldn't keep up
238 ) {
239 m_clearTerminal = false;
240 return;
241 }
242
243 // Send prior Ctrl-E, Ctrl-U to ensure the line is empty. This is
244 // mandatory, otherwise sending a 'cd x\n' to a prompt with 'rm -rf *'
245 // would result in data loss.
246 m_terminal->sendInput(QStringLiteral("\x05\x15"));
247
248 // We want to ignore the currentDirectoryChanged(QString) signal, which we will receive after
249 // the directory change, because this directory change is not caused by a "cd" command that the
250 // user entered in the panel. Therefore, we have to remember 'dir'. Note that it could also be
251 // a symbolic link -> remember the 'canonical' path.
252 if (addToHistory == HistoryPolicy::AddToHistory)
253 m_sendCdToTerminalHistory.enqueue(QDir(dir).canonicalPath());
254
255 m_terminal->sendInput(" cd " + KShell::quoteArg(dir) + '\r');
256
257 if (m_clearTerminal) {
258 m_terminal->sendInput(QStringLiteral(" clear\r"));
259 m_clearTerminal = false;
260 }
261 }
262
263 void TerminalPanel::sendCdToTerminalKIOFuse(const QUrl &url)
264 {
265 // URL isn't local, only hope for the terminal to be in sync with the
266 // DolphinView is to mount the remote URL in KIOFuse and point to it.
267 // If we can't do that for any reason, silently fail.
268 auto reply = m_kiofuseInterface.mountUrl(url.toString());
269 QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(reply, this);
270 QObject::connect(watcher, &QDBusPendingCallWatcher::finished, this, [=](QDBusPendingCallWatcher *watcher) {
271 watcher->deleteLater();
272 if (!reply.isError()) {
273 // Successfully mounted, point to the KIOFuse equivalent path.
274 sendCdToTerminal(reply.value());
275 }
276 });
277 }
278
279 void TerminalPanel::slotMostLocalUrlResult(KJob *job)
280 {
281 KIO::StatJob *statJob = static_cast<KIO::StatJob *>(job);
282 const QUrl url = statJob->mostLocalUrl();
283 if (url.isLocalFile()) {
284 sendCdToTerminal(url.toLocalFile());
285 } else {
286 sendCdToTerminalKIOFuse(url);
287 }
288
289 m_mostLocalUrlJob = nullptr;
290 }
291
292 void TerminalPanel::slotKonsolePartCurrentDirectoryChanged(const QString &dir)
293 {
294 m_konsolePartCurrentDirectory = QDir(dir).canonicalPath();
295
296 // Only emit a changeUrl signal if the directory change was caused by the user inside the
297 // terminal, and not by sendCdToTerminal(QString).
298 while (!m_sendCdToTerminalHistory.empty()) {
299 if (m_konsolePartCurrentDirectory == m_sendCdToTerminalHistory.dequeue()) {
300 return;
301 }
302 }
303
304 // User may potentially be browsing inside a KIOFuse mount.
305 // If so lets try and change the DolphinView to point to the remote URL equivalent.
306 // instead of into the KIOFuse mount itself (which can cause performance issues!)
307 const QUrl url(QUrl::fromLocalFile(dir));
308
309 KMountPoint::Ptr mountPoint = KMountPoint::currentMountPoints().findByPath(m_konsolePartCurrentDirectory);
310 if (mountPoint && mountPoint->mountType() != QStringLiteral("fuse.kio-fuse")) {
311 // Not in KIOFUse mount, so just switch to the corresponding URL.
312 Q_EMIT changeUrl(url);
313 return;
314 }
315
316 auto reply = m_kiofuseInterface.remoteUrl(m_konsolePartCurrentDirectory);
317 QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(reply, this);
318 QObject::connect(watcher, &QDBusPendingCallWatcher::finished, this, [=](QDBusPendingCallWatcher *watcher) {
319 watcher->deleteLater();
320 if (reply.isError()) {
321 // KIOFuse errored out... just show the normal URL
322 Q_EMIT changeUrl(url);
323 } else {
324 // Our location happens to be in a KIOFuse mount and is mounted.
325 // Let's change the DolphinView to point to the remote URL equivalent.
326 Q_EMIT changeUrl(QUrl::fromUserInput(reply.value()));
327 }
328 });
329 }
330
331 bool TerminalPanel::terminalHasFocus() const
332 {
333 if (m_terminalWidget) {
334 return m_terminalWidget->hasFocus();
335 }
336
337 return hasFocus();
338 }
339
340 #include "moc_terminalpanel.cpp"