+void TerminalPanel::changeDir(const QUrl& url)
+{
+ delete m_mostLocalUrlJob;
+ m_mostLocalUrlJob = 0;
+
+ if (url.isLocalFile()) {
+ sendCdToTerminal(url.toLocalFile());
+ } else {
+ m_mostLocalUrlJob = KIO::mostLocalUrl(url, KIO::HideProgressInfo);
+ if (m_mostLocalUrlJob->ui()) {
+ KJobWidgets::setWindow(m_mostLocalUrlJob, this);
+ }
+ connect(m_mostLocalUrlJob, &KIO::StatJob::result, this, &TerminalPanel::slotMostLocalUrlResult);
+ }
+}
+
+void TerminalPanel::sendCdToTerminal(const QString& dir)
+{
+ if (dir == m_konsolePartCurrentDirectory) {
+ m_clearTerminal = false;
+ return;
+ }
+
+ if (!m_clearTerminal) {
+ // The TerminalV2 interface does not provide a way to delete the
+ // current line before sending a new input. This is mandatory,
+ // otherwise sending a 'cd x' to a existing 'rm -rf *' might
+ // result in data loss. As workaround SIGINT is send.
+ const int processId = m_terminal->terminalProcessId();
+ if (processId > 0) {
+ kill(processId, SIGINT);
+ }
+ }
+
+ m_terminal->sendInput(" cd " + KShell::quoteArg(dir) + '\n');
+
+ // We want to ignore the currentDirectoryChanged(QString) signal, which we will receive after
+ // the directory change, because this directory change is not caused by a "cd" command that the
+ // user entered in the panel. Therefore, we have to remember 'dir'. Note that it could also be
+ // a symbolic link -> remember the 'canonical' path.
+ m_sendCdToTerminalHistory.enqueue(QDir(dir).canonicalPath());
+
+ if (m_clearTerminal) {
+ m_terminal->sendInput(QStringLiteral(" clear\n"));
+ m_clearTerminal = false;
+ }
+}
+
+void TerminalPanel::slotMostLocalUrlResult(KJob* job)
+{
+ KIO::StatJob* statJob = static_cast<KIO::StatJob *>(job);
+ const QUrl url = statJob->mostLocalUrl();
+ if (url.isLocalFile()) {
+ sendCdToTerminal(url.toLocalFile());
+ }
+
+ m_mostLocalUrlJob = 0;
+}
+
+void TerminalPanel::slotKonsolePartCurrentDirectoryChanged(const QString& dir)
+{
+ m_konsolePartCurrentDirectory = QDir(dir).canonicalPath();
+
+ // Only emit a changeUrl signal if the directory change was caused by the user inside the
+ // terminal, and not by sendCdToTerminal(QString).
+ while (!m_sendCdToTerminalHistory.empty()) {
+ if (m_konsolePartCurrentDirectory == m_sendCdToTerminalHistory.dequeue()) {
+ return;
+ }
+ }
+
+ const QUrl url(QUrl::fromLocalFile(dir));
+ emit changeUrl(url);
+}