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