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