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