]> cloud.milkyroute.net Git - dolphin.git/blob - src/panels/terminal/terminalpanel.cpp
Output of licensedigger + manual cleanup afterwards.
[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 <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 } else {
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 }
196 }
197
198 void TerminalPanel::sendCdToTerminal(const QString& dir, HistoryPolicy addToHistory)
199 {
200 if (dir == m_konsolePartCurrentDirectory) {
201 m_clearTerminal = false;
202 return;
203 }
204
205 #ifndef Q_OS_WIN
206 if (!m_clearTerminal) {
207 // The TerminalV2 interface does not provide a way to delete the
208 // current line before sending a new input. This is mandatory,
209 // otherwise sending a 'cd x' to a existing 'rm -rf *' might
210 // result in data loss. As workaround SIGINT is sent.
211 const int processId = m_terminal->terminalProcessId();
212 if (processId > 0) {
213 kill(processId, SIGINT);
214 }
215 }
216 #endif
217
218 m_terminal->sendInput(" cd " + KShell::quoteArg(dir) + '\n');
219
220 // We want to ignore the currentDirectoryChanged(QString) signal, which we will receive after
221 // the directory change, because this directory change is not caused by a "cd" command that the
222 // user entered in the panel. Therefore, we have to remember 'dir'. Note that it could also be
223 // a symbolic link -> remember the 'canonical' path.
224 if (addToHistory == HistoryPolicy::AddToHistory)
225 m_sendCdToTerminalHistory.enqueue(QDir(dir).canonicalPath());
226
227 if (m_clearTerminal) {
228 m_terminal->sendInput(QStringLiteral(" clear\n"));
229 m_clearTerminal = false;
230 }
231 }
232
233 void TerminalPanel::slotMostLocalUrlResult(KJob* job)
234 {
235 KIO::StatJob* statJob = static_cast<KIO::StatJob *>(job);
236 const QUrl url = statJob->mostLocalUrl();
237 if (url.isLocalFile()) {
238 sendCdToTerminal(url.toLocalFile());
239 } else {
240 // URL isn't local, only hope for the terminal to be in sync with the
241 // DolphinView is to mount the remote URL in KIOFuse and point to it.
242 // If we can't do that for any reason, silently fail.
243 auto reply = m_kiofuseInterface.mountUrl(url.toString());
244 QDBusPendingCallWatcher * watcher = new QDBusPendingCallWatcher(reply, this);
245 QObject::connect(watcher, &QDBusPendingCallWatcher::finished, this, [=] (QDBusPendingCallWatcher* watcher) {
246 watcher->deleteLater();
247 if (!reply.isError()) {
248 // Successfully mounted, point to the KIOFuse equivalent path.
249 sendCdToTerminal(reply.value());
250 }
251 });
252 }
253
254 m_mostLocalUrlJob = nullptr;
255 }
256
257 void TerminalPanel::slotKonsolePartCurrentDirectoryChanged(const QString& dir)
258 {
259 m_konsolePartCurrentDirectory = QDir(dir).canonicalPath();
260
261 // Only emit a changeUrl signal if the directory change was caused by the user inside the
262 // terminal, and not by sendCdToTerminal(QString).
263 while (!m_sendCdToTerminalHistory.empty()) {
264 if (m_konsolePartCurrentDirectory == m_sendCdToTerminalHistory.dequeue()) {
265 return;
266 }
267 }
268
269 // User may potentially be browsing inside a KIOFuse mount.
270 // If so lets try and change the DolphinView to point to the remote URL equivalent.
271 // instead of into the KIOFuse mount itself (which can cause performance issues!)
272 const QUrl url(QUrl::fromLocalFile(dir));
273
274 KMountPoint::Ptr mountPoint = KMountPoint::currentMountPoints().findByPath(m_konsolePartCurrentDirectory);
275 if (mountPoint && mountPoint->mountType() != QStringLiteral("fuse.kio-fuse")) {
276 // Not in KIOFUse mount, so just switch to the corresponding URL.
277 emit changeUrl(url);
278 return;
279 }
280
281 auto reply = m_kiofuseInterface.remoteUrl(m_konsolePartCurrentDirectory);
282 QDBusPendingCallWatcher * watcher = new QDBusPendingCallWatcher(reply, this);
283 QObject::connect(watcher, &QDBusPendingCallWatcher::finished, this, [=] (QDBusPendingCallWatcher* watcher) {
284 watcher->deleteLater();
285 if (reply.isError()) {
286 // KIOFuse errored out... just show the normal URL
287 emit changeUrl(url);
288 } else {
289 // Our location happens to be in a KIOFuse mount and is mounted.
290 // Let's change the DolphinView to point to the remote URL equivalent.
291 emit changeUrl(QUrl::fromUserInput(reply.value()));
292 }
293 });
294 }
295
296 bool TerminalPanel::terminalHasFocus() const
297 {
298 if (m_terminalWidget) {
299 return m_terminalWidget->hasFocus();
300 }
301
302 return hasFocus();
303 }