File indexing completed on 2024-04-28 16:54:22

0001 /*
0002     SPDX-FileCopyrightText: 2009 Esben Mose Hansen <kde@mosehansen.dk>
0003 
0004     SPDX-License-Identifier: GPL-2.0-or-later
0005 */
0006 
0007 #include "clipcommandprocess.h"
0008 
0009 #include <KMacroExpander>
0010 
0011 #include "history.h"
0012 #include "historystringitem.h"
0013 #include "urlgrabber.h"
0014 
0015 ClipCommandProcess::ClipCommandProcess(const ClipAction &action,
0016                                        const ClipCommand &command,
0017                                        const QString &clip,
0018                                        History *history,
0019                                        HistoryItemConstPtr original_item)
0020     : KProcess()
0021     , m_history(history)
0022     , m_historyItem(original_item)
0023     , m_newhistoryItem()
0024 {
0025     QHash<QChar, QString> map;
0026     map.insert(QLatin1Char('s'), clip);
0027 
0028     // support %u, %U (indicates url param(s)) and %f, %F (file param(s))
0029     map.insert(QLatin1Char('u'), clip);
0030     map.insert(QLatin1Char('U'), clip);
0031     map.insert(QLatin1Char('f'), clip);
0032     map.insert(QLatin1Char('F'), clip);
0033 
0034     const QStringList matches = action.actionCapturedTexts();
0035     // support only %0 and the first 9 matches...
0036     const int numMatches = qMin(10, matches.count());
0037     for (int i = 0; i < numMatches; ++i) {
0038         map.insert(QChar('0' + i), matches.at(i));
0039     }
0040 
0041     setOutputChannelMode(OnlyStdoutChannel);
0042     setShellCommand(KMacroExpander::expandMacrosShellQuote(command.command, map).trimmed());
0043 
0044     connect(this, SIGNAL(finished(int, QProcess::ExitStatus)), SLOT(slotFinished(int, QProcess::ExitStatus)));
0045     if (command.output != ClipCommand::IGNORE) {
0046         connect(this, &QIODevice::readyRead, this, &ClipCommandProcess::slotStdOutputAvailable);
0047     }
0048     if (command.output != ClipCommand::REPLACE) {
0049         m_historyItem.clear();
0050     }
0051 }
0052 
0053 void ClipCommandProcess::slotFinished(int /*exitCode*/, QProcess::ExitStatus /*newState*/)
0054 {
0055     if (m_history) {
0056         // If an history item was provided, remove it so that the new item can replace it
0057         if (m_historyItem) {
0058             m_history->remove(m_historyItem);
0059         }
0060         if (!m_newhistoryItem.isEmpty()) {
0061             m_history->insert(HistoryItemPtr(new HistoryStringItem(m_newhistoryItem)));
0062         }
0063     }
0064     deleteLater();
0065 }
0066 
0067 void ClipCommandProcess::slotStdOutputAvailable()
0068 {
0069     m_newhistoryItem.append(QString::fromLocal8Bit(this->readAllStandardOutput()));
0070 }