]> git.sesse.net Git - kdenlive/blob - src/utils/freesound.cpp
Now one can also search and import image clips from openclipart.org
[kdenlive] / src / utils / freesound.cpp
1 /***************************************************************************
2  *   Copyright (C) 2008 by Jean-Baptiste Mardelle (jb@kdenlive.org)        *
3  *   Copyright (C) 2011 by Marco Gittler (marco@gitma.de)                  *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) any later version.                                   *
9  *                                                                         *
10  *   This program is distributed in the hope that it will be useful,       *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with this program; if not, write to the                         *
17  *   Free Software Foundation, Inc.,                                       *
18  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA          *
19  ***************************************************************************/
20
21
22 #include "freesound.h"
23
24 #include <QPushButton>
25 #include <QSpinBox>
26 #include <QListWidget>
27 #include <QDomDocument>
28
29 #include <KDebug>
30 #include "kdenlivesettings.h"
31 #include <KGlobalSettings>
32 #include <KMessageBox>
33 #include <KFileDialog>
34 #include <kio/job.h>
35 #include <KIO/NetAccess>
36 #include <KRun>
37
38 #include <qjson/parser.h>
39
40 const int imageRole = Qt::UserRole;
41 const int urlRole = Qt::UserRole + 1;
42 const int downloadRole = Qt::UserRole + 2;
43 const int durationRole = Qt::UserRole + 3;
44 const int previewRole = Qt::UserRole + 4;
45 const int authorRole = Qt::UserRole + 5;
46 const int authorUrl = Qt::UserRole + 6;
47 const int infoUrl = Qt::UserRole + 7;
48
49
50 FreeSound::FreeSound(const QString & folder, QWidget * parent) :
51         QDialog(parent),
52         m_folder(folder),
53         m_service(FREESOUND)
54 {
55     setFont(KGlobalSettings::toolBarFont());
56     setupUi(this);
57     setAttribute(Qt::WA_DeleteOnClose);
58     service_list->addItem(i18n("Freesound Audio Library"), FREESOUND);
59     service_list->addItem(i18n("Open Clip Art Graphic Library"), OPENCLIPART);
60     setWindowTitle(i18n("Search Online Resources"));
61     connect(button_search, SIGNAL(clicked()), this, SLOT(slotStartSearch()));
62     connect(search_results, SIGNAL(currentRowChanged(int)), this, SLOT(slotUpdateCurrentSound()));
63     connect(button_preview, SIGNAL(clicked()), this, SLOT(slotPlaySound()));
64     connect(button_import, SIGNAL(clicked()), this, SLOT(slotSaveSound()));
65     connect(sound_author, SIGNAL(leftClickedUrl(const QString &)), this, SLOT(slotOpenUrl(const QString &)));
66     connect(sound_name, SIGNAL(leftClickedUrl(const QString &)), this, SLOT(slotOpenUrl(const QString &)));
67     m_previewProcess = new QProcess;
68     connect(m_previewProcess, SIGNAL(stateChanged(QProcess::ProcessState)), this, SLOT(slotPreviewStatusChanged(QProcess::ProcessState)));
69     connect(service_list, SIGNAL(currentIndexChanged(int)), this, SLOT(slotChangeService()));
70     sound_image->setFixedWidth(180);
71 }
72
73 FreeSound::~FreeSound()
74 {
75     if (m_previewProcess) delete m_previewProcess;
76 }
77
78 void FreeSound::slotStartSearch()
79 {
80     m_result.clear();
81     m_currentPreview.clear();
82     m_currentUrl.clear();
83     page_number->blockSignals(true);
84     page_number->setValue(0);
85     page_number->blockSignals(false);
86     QString uri;
87     if (m_service == FREESOUND) {
88         uri = "http://www.freesound.org/api/sounds/search/?q=";
89         uri.append(search_text->text());
90         uri.append("&api_key=a1772c8236e945a4bee30a64058dabf8");
91     }
92     else if (m_service == OPENCLIPART) {
93         uri = "http://openclipart.org/api/search/?query=";
94         uri.append(search_text->text());
95         //water&page=4
96     }
97     KIO::TransferJob *job = KIO::get(KUrl(uri));
98     connect (job, SIGNAL(  data(KIO::Job *, const QByteArray & )), this, SLOT(slotDataIsHere(KIO::Job *,const QByteArray &)));
99     connect(job, SIGNAL(result(KJob*)), this, SLOT(slotShowResults()));
100 }
101
102 void FreeSound::slotDataIsHere(KIO::Job *,const QByteArray & data )
103 {
104   m_result.append(data);
105 }
106
107 void FreeSound::slotShowResults()
108 {
109     search_results->blockSignals(true);
110     search_results->clear();
111     if (m_service == FREESOUND) {
112         QJson::Parser parser;
113         bool ok;
114         kDebug()<<"// GOT RESULT: "<<m_result;
115         m_data = parser.parse(m_result, &ok);
116         QVariant sounds;
117         if (m_data.canConvert(QVariant::Map)) {
118             QMap <QString, QVariant> map = m_data.toMap();
119             QMap<QString, QVariant>::const_iterator i = map.constBegin();
120             while (i != map.constEnd()) {
121                 if (i.key() == "num_results") search_info->setText(i18np("Found %1 result", "Found %1 results", i.value().toInt()));
122                 else if (i.key() == "num_pages") {
123                     page_number->setMaximum(i.value().toInt());
124                 }
125                 else if (i.key() == "sounds") {
126                     sounds = i.value();
127                     if (sounds.canConvert(QVariant::List)) {
128                         QList <QVariant> soundsList = sounds.toList();
129                         for (int j = 0; j < soundsList.count(); j++) {
130                             if (soundsList.at(j).canConvert(QVariant::Map)) {
131                                 QMap <QString, QVariant> soundmap = soundsList.at(j).toMap();
132                                 if (soundmap.contains("original_filename")) {
133                                     QListWidgetItem *item = new   QListWidgetItem(soundmap.value("original_filename").toString(), search_results);
134                                     item->setData(imageRole, soundmap.value("waveform_m").toString());
135                                     item->setData(infoUrl, soundmap.value("url").toString());
136                                     item->setData(durationRole, soundmap.value("duration").toDouble());
137                                     item->setData(previewRole, soundmap.value("preview-hq-mp3").toString());
138                                     item->setData(downloadRole, soundmap.value("serve").toString() + "?api_key=a1772c8236e945a4bee30a64058dabf8");
139                                     QVariant authorInfo = soundmap.value("user");
140                                     if (authorInfo.canConvert(QVariant::Map)) {
141                                         QMap <QString, QVariant> authorMap = authorInfo.toMap();
142                                         if (authorMap.contains("username")) {
143                                             item->setData(authorRole, authorMap.value("username").toString());
144                                             item->setData(authorUrl, authorMap.value("url").toString());
145                                         }
146                                     }
147                                 }
148                             }
149                         }
150                     }
151                 }
152                 ++i;
153             }
154         }
155     }
156     else if (m_service == OPENCLIPART) {
157         QDomDocument doc;
158         doc.setContent(m_result);
159         QDomNodeList items = doc.documentElement().elementsByTagName("item");
160         for (int i = 0; i < items.count(); i++) {
161             QDomElement currentClip = items.at(i).toElement();
162             QDomElement title = currentClip.firstChildElement("title");
163             QListWidgetItem *item = new QListWidgetItem(title.firstChild().nodeValue(), search_results);
164             QDomElement thumb = currentClip.firstChildElement("media:thumbnail");
165             item->setData(imageRole, thumb.attribute("url"));
166             QDomElement enclosure = currentClip.firstChildElement("enclosure");
167             item->setData(downloadRole, enclosure.attribute("url"));
168             QDomElement link = currentClip.firstChildElement("link");
169             item->setData(infoUrl, link.firstChild().nodeValue());
170             QDomElement author = currentClip.firstChildElement("dc:creator");
171             item->setData(authorRole, author.firstChild().nodeValue());
172             item->setData(authorUrl, QString("http://openclipart.org/user-detail/") + author.firstChild().nodeValue());
173         }
174     }
175     search_results->blockSignals(false);
176     search_results->setCurrentRow(0);
177 }
178
179 void FreeSound::slotUpdateCurrentSound()
180 {
181     m_currentPreview.clear();
182     m_currentUrl.clear();
183     QListWidgetItem *item = search_results->currentItem();
184     if (!item) {
185         sound_box->setEnabled(false);
186         return;
187     }
188     m_currentPreview = item->data(previewRole).toString();
189     m_currentUrl = item->data(downloadRole).toString();
190     button_preview->setEnabled(!m_currentPreview.isEmpty());
191     sound_box->setEnabled(true);
192     sound_name->setText(item->text());
193     sound_name->setUrl(item->data(infoUrl).toString());
194     sound_author->setText(item->data(authorRole).toString());
195     sound_author->setUrl(item->data(authorUrl).toString());
196     if (!item->data(durationRole).isNull()) sound_duration->setText(QString::number(item->data(durationRole).toDouble()));
197     KUrl img(item->data(imageRole).toString());
198     if (img.isEmpty()) return;
199     if (KIO::NetAccess::exists(img, KIO::NetAccess::SourceSide, this)) {
200         QString tmpFile;
201         if (KIO::NetAccess::download(img, tmpFile, this)) {
202             QPixmap pix(tmpFile);
203             int newHeight = pix.height() * sound_image->width() / pix.width();
204             if (newHeight > 2 * sound_image->width()) {
205                 sound_image->setScaledContents(false);
206                 //sound_image->setFixedHeight(sound_image->width());
207             }
208             else {
209                 sound_image->setScaledContents(true);
210                 sound_image->setFixedHeight(newHeight);
211             }
212             sound_image->setPixmap(pix);
213             KIO::NetAccess::removeTempFile(tmpFile);
214         }
215     }
216 }
217
218
219 void FreeSound::slotPlaySound()
220 {
221     if (m_currentPreview.isEmpty()) return;
222     if (m_previewProcess && m_previewProcess->state() != QProcess::NotRunning) {
223         m_previewProcess->close();
224         return;
225     }
226     m_previewProcess->start("ffplay", QStringList() << m_currentPreview << "-nodisp");
227 }
228
229 void FreeSound::slotPreviewStatusChanged(QProcess::ProcessState state)
230 {
231     if (state == QProcess::NotRunning)
232         button_preview->setText(i18n("Preview"));
233     else 
234         button_preview->setText(i18n("Stop"));
235 }
236
237 void FreeSound::slotSaveSound()
238 {
239     if (m_currentUrl.isEmpty()) return;
240     QString path = m_folder;
241     if (!path.endsWith('/')) path.append('/');
242     path.append(sound_name->text());
243     QString ext;
244     if (m_service == FREESOUND) {
245         ext = "*." + sound_name->text().section('.', -1);
246     }
247     else if (m_service == OPENCLIPART) {
248         path.append("." + m_currentUrl.section('.', -1));
249         ext = "*." + m_currentUrl.section('.', -1);
250     }
251     QString saveUrl = KFileDialog::getSaveFileName(KUrl(path), ext);
252     if (saveUrl.isEmpty()) return;
253     if (KIO::NetAccess::download(KUrl(m_currentUrl), saveUrl, this)) {
254         emit addClip(KUrl(saveUrl), sound_name->url());
255     }
256 }
257
258 void FreeSound::slotOpenUrl(const QString &url)
259 {
260     new KRun(KUrl(url), this);
261 }
262
263 void FreeSound::slotChangeService()
264 {
265     m_service = (SERVICETYPE) service_list->itemData(service_list->currentIndex()).toInt();
266     if (m_service == FREESOUND) {
267         button_preview->setVisible(true);
268         duration_label->setVisible(true);
269         search_info->setVisible(true);
270     }
271     else if (m_service == OPENCLIPART) {
272         button_preview->setVisible(false);
273         duration_label->setVisible(false);
274         search_info->setVisible(false);
275         sound_duration->setText(QString());
276     }
277     if (!search_text->text().isEmpty()) slotStartSearch();
278 }
279