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