]> git.sesse.net Git - kdenlive/blob - src/projectlist.cpp
Grouping "audio" and "video" file formats for better src readability.
[kdenlive] / src / projectlist.cpp
1 /***************************************************************************
2  *   Copyright (C) 2007 by Jean-Baptiste Mardelle (jb@kdenlive.org)        *
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 "projectlist.h"
21 #include "projectitem.h"
22 #include "addfoldercommand.h"
23 #include "kdenlivesettings.h"
24 #include "slideshowclip.h"
25 #include "ui_colorclip_ui.h"
26 #include "titlewidget.h"
27 #include "definitions.h"
28 #include "clipmanager.h"
29 #include "docclipbase.h"
30 #include "kdenlivedoc.h"
31 #include "renderer.h"
32 #include "kthumb.h"
33 #include "projectlistview.h"
34 #include "editclipcommand.h"
35 #include "editfoldercommand.h"
36 #include "ui_templateclip_ui.h"
37
38 #include <KDebug>
39 #include <KAction>
40 #include <KLocale>
41 #include <KFileDialog>
42 #include <KInputDialog>
43 #include <KMessageBox>
44
45 #include <nepomuk/global.h>
46 #include <nepomuk/resourcemanager.h>
47 //#include <nepomuk/tag.h>
48
49 #include <QMouseEvent>
50 #include <QStylePainter>
51 #include <QPixmap>
52 #include <QIcon>
53 #include <QMenu>
54 #include <QProcess>
55 #include <QHeaderView>
56
57 ProjectList::ProjectList(QWidget *parent) :
58         QWidget(parent),
59         m_render(NULL),
60         m_fps(-1),
61         m_commandStack(NULL),
62         m_editAction(NULL),
63         m_deleteAction(NULL),
64         m_openAction(NULL),
65         m_reloadAction(NULL),
66         m_selectedItem(NULL),
67         m_refreshed(false),
68         m_infoQueue(),
69         m_thumbnailQueue()
70 {
71
72     m_listView = new ProjectListView(this);;
73     QVBoxLayout *layout = new QVBoxLayout;
74     layout->setContentsMargins(0, 0, 0, 0);
75
76     // setup toolbar
77     KTreeWidgetSearchLine *searchView = new KTreeWidgetSearchLine(this);
78     m_toolbar = new QToolBar("projectToolBar", this);
79     m_toolbar->addWidget(searchView);
80     searchView->setTreeWidget(m_listView);
81
82     m_addButton = new QToolButton(m_toolbar);
83     m_addButton->setPopupMode(QToolButton::MenuButtonPopup);
84     m_toolbar->addWidget(m_addButton);
85
86     layout->addWidget(m_toolbar);
87     layout->addWidget(m_listView);
88     setLayout(layout);
89
90     m_queueTimer.setInterval(100);
91     connect(&m_queueTimer, SIGNAL(timeout()), this, SLOT(slotProcessNextClipInQueue()));
92     m_queueTimer.setSingleShot(true);
93
94
95
96     connect(m_listView, SIGNAL(itemSelectionChanged()), this, SLOT(slotClipSelected()));
97     connect(m_listView, SIGNAL(focusMonitor()), this, SLOT(slotClipSelected()));
98     connect(m_listView, SIGNAL(pauseMonitor()), this, SLOT(slotPauseMonitor()));
99     connect(m_listView, SIGNAL(requestMenu(const QPoint &, QTreeWidgetItem *)), this, SLOT(slotContextMenu(const QPoint &, QTreeWidgetItem *)));
100     connect(m_listView, SIGNAL(addClip()), this, SLOT(slotAddClip()));
101     connect(m_listView, SIGNAL(addClip(const QList <QUrl>, const QString &, const QString &)), this, SLOT(slotAddClip(const QList <QUrl>, const QString &, const QString &)));
102     connect(m_listView, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this, SLOT(slotItemEdited(QTreeWidgetItem *, int)));
103     connect(m_listView, SIGNAL(showProperties(DocClipBase *)), this, SIGNAL(showClipProperties(DocClipBase *)));
104
105     ItemDelegate *listViewDelegate = new ItemDelegate(m_listView);
106     m_listView->setItemDelegate(listViewDelegate);
107
108     if (KdenliveSettings::activate_nepomuk()) {
109         Nepomuk::ResourceManager::instance()->init();
110         if (!Nepomuk::ResourceManager::instance()->initialized()) {
111             kDebug() << "Cannot communicate with Nepomuk, DISABLING it";
112             KdenliveSettings::setActivate_nepomuk(false);
113         }
114     }
115 }
116
117 ProjectList::~ProjectList()
118 {
119     delete m_menu;
120     delete m_toolbar;
121 }
122
123 void ProjectList::setupMenu(QMenu *addMenu, QAction *defaultAction)
124 {
125     QList <QAction *> actions = addMenu->actions();
126     for (int i = 0; i < actions.count(); i++) {
127         if (actions.at(i)->data().toString() == "clip_properties") {
128             m_editAction = actions.at(i);
129             m_toolbar->addAction(m_editAction);
130             actions.removeAt(i);
131             i--;
132         } else if (actions.at(i)->data().toString() == "delete_clip") {
133             m_deleteAction = actions.at(i);
134             m_toolbar->addAction(m_deleteAction);
135             actions.removeAt(i);
136             i--;
137         } else if (actions.at(i)->data().toString() == "edit_clip") {
138             m_openAction = actions.at(i);
139             actions.removeAt(i);
140             i--;
141         } else if (actions.at(i)->data().toString() == "reload_clip") {
142             m_reloadAction = actions.at(i);
143             actions.removeAt(i);
144             i--;
145         }
146     }
147
148     QMenu *m = new QMenu();
149     m->addActions(actions);
150     m_addButton->setMenu(m);
151     m_addButton->setDefaultAction(defaultAction);
152     m_menu = new QMenu();
153     m_menu->addActions(addMenu->actions());
154 }
155
156 void ProjectList::setupGeneratorMenu(QMenu *addMenu, QMenu *transcodeMenu)
157 {
158     if (!addMenu) return;
159     QMenu *menu = m_addButton->menu();
160     menu->addMenu(addMenu);
161     m_addButton->setMenu(menu);
162
163     m_menu->addMenu(addMenu);
164     if (addMenu->isEmpty()) addMenu->setEnabled(false);
165     m_menu->addMenu(transcodeMenu);
166     if (transcodeMenu->isEmpty()) transcodeMenu->setEnabled(false);
167     m_menu->addAction(m_reloadAction);
168     m_menu->addAction(m_editAction);
169     m_menu->addAction(m_openAction);
170     m_menu->addAction(m_deleteAction);
171     m_menu->insertSeparator(m_deleteAction);
172 }
173
174
175 QByteArray ProjectList::headerInfo() const
176 {
177     return m_listView->header()->saveState();
178 }
179
180 void ProjectList::setHeaderInfo(const QByteArray &state)
181 {
182     m_listView->header()->restoreState(state);
183 }
184
185 void ProjectList::slotEditClip()
186 {
187     ProjectItem *item = static_cast <ProjectItem*>(m_listView->currentItem());
188     if (!(item->flags() & Qt::ItemIsDragEnabled)) return;
189     if (item && !item->isGroup()) {
190         emit clipSelected(item->referencedClip());
191         emit showClipProperties(item->referencedClip());
192     }
193 }
194
195 void ProjectList::slotOpenClip()
196 {
197     ProjectItem *item = static_cast <ProjectItem*>(m_listView->currentItem());
198     if (item && !item->isGroup()) {
199         if (item->clipType() == IMAGE) {
200             if (KdenliveSettings::defaultimageapp().isEmpty()) KMessageBox::sorry(this, i18n("Please set a default application to open images in the Settings dialog"));
201             else QProcess::startDetached(KdenliveSettings::defaultimageapp(), QStringList() << item->clipUrl().path());
202         }
203         if (item->clipType() == AUDIO) {
204             if (KdenliveSettings::defaultaudioapp().isEmpty()) KMessageBox::sorry(this, i18n("Please set a default application to open audio files in the Settings dialog"));
205             else QProcess::startDetached(KdenliveSettings::defaultaudioapp(), QStringList() << item->clipUrl().path());
206         }
207     }
208 }
209
210 void ProjectList::slotReloadClip()
211 {
212     QList<QTreeWidgetItem *> selected = m_listView->selectedItems();
213     ProjectItem *item;
214     for (int i = 0; i < selected.count(); i++) {
215         item = static_cast <ProjectItem *>(selected.at(i));
216         if (item && !item->isGroup()) {
217             if (item->clipType() == IMAGE) {
218                 item->referencedClip()->producer()->set("force_reload", 1);
219             } else if (item->clipType() == TEXT) {
220                 if (!item->referencedClip()->getProperty("xmltemplate").isEmpty()) regenerateTemplate(item);
221             }
222             //requestClipInfo(item->toXml(), item->clipId(), true);
223             // Clear the file_hash value, which will cause a complete reload of the clip
224             emit getFileProperties(item->toXml(), item->clipId(), true);
225         }
226     }
227 }
228
229 void ProjectList::setRenderer(Render *projectRender)
230 {
231     m_render = projectRender;
232     m_listView->setIconSize(QSize(40 * m_render->dar(), 40));
233 }
234
235 void ProjectList::slotClipSelected()
236 {
237     if (m_listView->currentItem()) {
238         ProjectItem *clip = static_cast <ProjectItem*>(m_listView->currentItem());
239         if (!clip->isGroup()) {
240             m_selectedItem = clip;
241             emit clipSelected(clip->referencedClip());
242         }
243         m_editAction->setEnabled(true);
244         m_deleteAction->setEnabled(true);
245         m_reloadAction->setEnabled(true);
246         if (clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) {
247             m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
248             m_openAction->setEnabled(true);
249         } else if (clip->clipType() == AUDIO && !KdenliveSettings::defaultaudioapp().isEmpty()) {
250             m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
251             m_openAction->setEnabled(true);
252         } else m_openAction->setEnabled(false);
253     } else {
254         emit clipSelected(NULL);
255         m_editAction->setEnabled(false);
256         m_deleteAction->setEnabled(false);
257         m_openAction->setEnabled(false);
258         m_reloadAction->setEnabled(false);
259     }
260 }
261
262 void ProjectList::slotPauseMonitor()
263 {
264     if (m_render) m_render->pause();
265 }
266
267 void ProjectList::slotUpdateClipProperties(const QString &id, QMap <QString, QString> properties)
268 {
269     ProjectItem *item = getItemById(id);
270     if (item) {
271         slotUpdateClipProperties(item, properties);
272         if (properties.contains("colour") || properties.contains("resource") || properties.contains("xmldata") || properties.contains("force_aspect_ratio")) {
273             slotRefreshClipThumbnail(item);
274             emit refreshClip();
275         }
276         if (properties.contains("out")) item->changeDuration(properties.value("out").toInt());
277     }
278 }
279
280 void ProjectList::slotUpdateClipProperties(ProjectItem *clip, QMap <QString, QString> properties)
281 {
282     if (!clip) return;
283     if (!clip->isGroup()) clip->setProperties(properties);
284     if (properties.contains("xmldata")) regenerateTemplateImage(clip);
285     if (properties.contains("name")) {
286         m_listView->blockSignals(true);
287         clip->setText(1, properties.value("name"));
288         m_listView->blockSignals(false);
289         emit clipNameChanged(clip->clipId(), properties.value("name"));
290     }
291     if (properties.contains("description")) {
292         CLIPTYPE type = clip->clipType();
293         m_listView->blockSignals(true);
294         clip->setText(2, properties.value("description"));
295         m_listView->blockSignals(false);
296         if (KdenliveSettings::activate_nepomuk() && (type == AUDIO || type == VIDEO || type == AV || type == IMAGE || type == PLAYLIST)) {
297             // Use Nepomuk system to store clip description
298             Nepomuk::Resource f(clip->clipUrl().path());
299             f.setDescription(properties.value("description"));
300         }
301         emit projectModified();
302     }
303 }
304
305 void ProjectList::slotItemEdited(QTreeWidgetItem *item, int column)
306 {
307     ProjectItem *clip = static_cast <ProjectItem*>(item);
308     if (column == 2) {
309         if (clip->referencedClip()) {
310             QMap <QString, QString> oldprops;
311             QMap <QString, QString> newprops;
312             oldprops["description"] = clip->referencedClip()->getProperty("description");
313             newprops["description"] = item->text(2);
314
315             if (clip->clipType() == TEXT && !clip->referencedClip()->getProperty("xmltemplate").isEmpty()) {
316                 // This is a text template clip, update the image
317                 oldprops.insert("xmldata", clip->referencedClip()->getProperty("xmldata"));
318                 newprops.insert("xmldata", generateTemplateXml(clip->referencedClip()->getProperty("xmltemplate"), item->text(2)).toString());
319             }
320
321             slotUpdateClipProperties(clip->clipId(), newprops);
322             EditClipCommand *command = new EditClipCommand(this, clip->clipId(), oldprops, newprops, false);
323             m_commandStack->push(command);
324         }
325     } else if (column == 1) {
326         if (clip->isGroup()) {
327             editFolder(item->text(1), clip->groupName(), clip->clipId());
328             clip->setGroupName(item->text(1));
329             m_doc->clipManager()->addFolder(clip->clipId(), item->text(1));
330             const int children = item->childCount();
331             for (int i = 0; i < children; i++) {
332                 ProjectItem *child = static_cast <ProjectItem *>(item->child(i));
333                 child->setProperty("groupname", item->text(1));
334             }
335         } else {
336             if (clip->referencedClip()) {
337                 QMap <QString, QString> oldprops;
338                 QMap <QString, QString> newprops;
339                 oldprops["name"] = clip->referencedClip()->getProperty("name");
340                 newprops["name"] = item->text(1);
341                 slotUpdateClipProperties(clip, newprops);
342                 emit projectModified();
343                 EditClipCommand *command = new EditClipCommand(this, clip->clipId(), oldprops, newprops, false);
344                 m_commandStack->push(command);
345             }
346         }
347     }
348 }
349
350 void ProjectList::slotContextMenu(const QPoint &pos, QTreeWidgetItem *item)
351 {
352     bool enable = false;
353     if (item) {
354         enable = true;
355     }
356     m_editAction->setEnabled(enable);
357     m_deleteAction->setEnabled(enable);
358     m_reloadAction->setEnabled(enable);
359     if (enable) {
360         ProjectItem *clip = static_cast <ProjectItem*>(item);
361         if (clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) {
362             m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
363             m_openAction->setEnabled(true);
364         } else if (clip->clipType() == AUDIO && !KdenliveSettings::defaultaudioapp().isEmpty()) {
365             m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
366             m_openAction->setEnabled(true);
367         } else m_openAction->setEnabled(false);
368     } else m_openAction->setEnabled(false);
369     m_menu->popup(pos);
370 }
371
372 void ProjectList::slotRemoveClip()
373 {
374     if (!m_listView->currentItem()) return;
375     QList <QString> ids;
376     QMap <QString, QString> folderids;
377     QList<QTreeWidgetItem *> selected = m_listView->selectedItems();
378     ProjectItem *item;
379     for (int i = 0; i < selected.count(); i++) {
380         item = static_cast <ProjectItem *>(selected.at(i));
381         if (item->isGroup()) folderids[item->groupName()] = item->clipId();
382         else ids << item->clipId();
383         if (item->numReferences() > 0) {
384             if (KMessageBox::questionYesNo(this, i18np("Delete clip <b>%2</b>?<br>This will also remove the clip in timeline", "Delete clip <b>%2</b>?<br>This will also remove its %1 clips in timeline", item->numReferences(), item->names().at(1)), i18n("Delete Clip")) != KMessageBox::Yes) return;
385         } else if (item->isGroup() && item->childCount() > 0) {
386             int children = item->childCount();
387             if (KMessageBox::questionYesNo(this, i18n("Delete folder <b>%2</b>?<br>This will also remove the %1 clips in that folder", children, item->names().at(1)), i18n("Delete Folder")) != KMessageBox::Yes) return;
388             for (int i = 0; i < children; ++i) {
389                 ProjectItem *child = static_cast <ProjectItem *>(item->child(i));
390                 ids << child->clipId();
391             }
392         }
393     }
394     if (!ids.isEmpty()) m_doc->deleteProjectClip(ids);
395     if (!folderids.isEmpty()) deleteProjectFolder(folderids);
396     if (m_listView->topLevelItemCount() == 0) {
397         m_editAction->setEnabled(false);
398         m_deleteAction->setEnabled(false);
399         m_openAction->setEnabled(false);
400         m_reloadAction->setEnabled(false);
401     }
402 }
403
404 void ProjectList::selectItemById(const QString &clipId)
405 {
406     ProjectItem *item = getItemById(clipId);
407     if (item) m_listView->setCurrentItem(item);
408 }
409
410
411 void ProjectList::slotDeleteClip(const QString &clipId)
412 {
413     ProjectItem *item = getItemById(clipId);
414     if (!item) {
415         kDebug() << "/// Cannot find clip to delete";
416         return;
417     }
418     delete item;
419 }
420
421
422 void ProjectList::editFolder(const QString folderName, const QString oldfolderName, const QString &clipId)
423 {
424     EditFolderCommand *command = new EditFolderCommand(this, folderName, oldfolderName, clipId, false);
425     m_commandStack->push(command);
426     m_doc->setModified(true);
427 }
428
429 void ProjectList::slotAddFolder()
430 {
431     AddFolderCommand *command = new AddFolderCommand(this, i18n("Folder"), QString::number(m_doc->clipManager()->getFreeFolderId()), true);
432     m_commandStack->push(command);
433 }
434
435 void ProjectList::slotAddFolder(const QString foldername, const QString &clipId, bool remove, bool edit)
436 {
437     if (remove) {
438         ProjectItem *item = getFolderItemById(clipId);
439         if (item) {
440             m_doc->clipManager()->deleteFolder(clipId);
441             delete item;
442         }
443     } else {
444         if (edit) {
445             ProjectItem *item = getFolderItemById(clipId);
446             QTreeWidgetItemIterator it(m_listView);
447             if (item) {
448                 m_listView->blockSignals(true);
449                 item->setGroupName(foldername);
450                 m_listView->blockSignals(false);
451                 m_doc->clipManager()->addFolder(clipId, foldername);
452                 const int children = item->childCount();
453                 for (int i = 0; i < children; i++) {
454                     ProjectItem *child = static_cast <ProjectItem *>(item->child(i));
455                     child->setProperty("groupname", foldername);
456                 }
457             }
458         } else {
459             QStringList text;
460             text << QString() << foldername;
461             m_listView->blockSignals(true);
462             m_listView->setCurrentItem(new ProjectItem(m_listView, text, clipId));
463             m_doc->clipManager()->addFolder(clipId, foldername);
464             m_listView->blockSignals(false);
465         }
466     }
467 }
468
469
470
471 void ProjectList::deleteProjectFolder(QMap <QString, QString> map)
472 {
473     QMapIterator<QString, QString> i(map);
474     QUndoCommand *delCommand = new QUndoCommand();
475     delCommand->setText(i18n("Delete Folder"));
476     while (i.hasNext()) {
477         i.next();
478         new AddFolderCommand(this, i.key(), i.value(), false, delCommand);
479     }
480     m_commandStack->push(delCommand);
481     m_doc->setModified(true);
482 }
483
484 void ProjectList::slotAddClip(DocClipBase *clip, bool getProperties)
485 {
486     if (getProperties) m_listView->setEnabled(false);
487     m_listView->blockSignals(true);
488     const QString parent = clip->getProperty("groupid");
489     kDebug() << "Adding clip with groupid: " << parent;
490     ProjectItem *item = NULL;
491     if (!parent.isEmpty()) {
492         ProjectItem *parentitem = getFolderItemById(parent);
493         if (!parentitem) {
494             QStringList text;
495             QString groupName = clip->getProperty("groupname");
496             //kDebug() << "Adding clip to new group: " << groupName;
497             if (groupName.isEmpty()) groupName = i18n("Folder");
498             text << QString() << groupName;
499             parentitem = new ProjectItem(m_listView, text, parent);
500         } else {
501             //kDebug() << "Adding clip to existing group: " << parentitem->groupName();
502         }
503         if (parentitem) item = new ProjectItem(parentitem, clip);
504     }
505     if (item == NULL) item = new ProjectItem(m_listView, clip);
506     KUrl url = clip->fileURL();
507
508     if (getProperties == false && !clip->getClipHash().isEmpty()) {
509         QString cachedPixmap = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "thumbs/" + clip->getClipHash() + ".png";
510         if (QFile::exists(cachedPixmap)) {
511             item->setIcon(0, QPixmap(cachedPixmap));
512         }
513     }
514
515     if (!url.isEmpty() && KdenliveSettings::activate_nepomuk()) {
516         // if file has Nepomuk comment, use it
517         Nepomuk::Resource f(url.path());
518         QString annotation = f.description();
519         if (!annotation.isEmpty()) item->setText(2, annotation);
520         item->setText(3, QString::number(f.rating()));
521     }
522     m_listView->blockSignals(false);
523 }
524
525 void ProjectList::slotResetProjectList()
526 {
527     m_listView->clear();
528     emit clipSelected(NULL);
529     m_thumbnailQueue.clear();
530     m_infoQueue.clear();
531     m_refreshed = false;
532 }
533
534 void ProjectList::requestClipInfo(const QDomElement xml, const QString id)
535 {
536     m_infoQueue.insert(id, xml);
537     m_listView->setEnabled(false);
538     if (!m_queueTimer.isActive()) m_queueTimer.start();
539     //if (m_infoQueue.count() == 1 || ) QTimer::singleShot(300, this, SLOT(slotProcessNextClipInQueue()));
540 }
541
542 void ProjectList::slotProcessNextClipInQueue()
543 {
544     if (m_infoQueue.isEmpty()) {
545         slotProcessNextThumbnail();
546         return;
547     }
548
549     QMap<QString, QDomElement>::const_iterator j = m_infoQueue.constBegin();
550     if (j != m_infoQueue.constEnd()) {
551         const QDomElement dom = j.value();
552         const QString id = j.key();
553         m_infoQueue.remove(j.key());
554         emit getFileProperties(dom, id, false);
555     }
556     if (!m_infoQueue.isEmpty()) m_queueTimer.start();
557 }
558
559 void ProjectList::slotUpdateClip(const QString &id)
560 {
561     ProjectItem *item = getItemById(id);
562     m_listView->blockSignals(true);
563     if (item) item->setData(1, UsageRole, QString::number(item->numReferences()));
564     m_listView->blockSignals(false);
565 }
566
567 void ProjectList::updateAllClips()
568 {
569     QTreeWidgetItemIterator it(m_listView);
570     while (*it) {
571         ProjectItem *item = static_cast <ProjectItem *>(*it);
572         if (!item->isGroup()) {
573             DocClipBase *clip = item->referencedClip();
574             if (clip->clipType() == TEXT && !QFile::exists(clip->fileURL().path())) {
575                 // regenerate text clip image if required
576                 TitleWidget *dia_ui = new TitleWidget(KUrl(), QString(), m_render, this);
577                 QDomDocument doc;
578                 doc.setContent(clip->getProperty("xmldata"));
579                 dia_ui->setXml(doc);
580                 QImage pix = dia_ui->renderedPixmap();
581                 pix.save(clip->fileURL().path());
582                 delete dia_ui;
583             }
584
585             if (item->referencedClip()->producer() == NULL) {
586                 if (clip->isPlaceHolder() == false) requestClipInfo(clip->toXML(), clip->getId());
587                 else item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
588             } else {
589                 if (item->icon(0).isNull()) {
590                     requestClipThumbnail(clip->getId());
591                 }
592                 if (item->data(1, DurationRole).toString().isEmpty()) {
593                     m_listView->blockSignals(true);
594                     item->changeDuration(item->referencedClip()->producer()->get_playtime());
595                     m_listView->blockSignals(false);
596                 }
597             }
598             m_listView->blockSignals(true);
599             item->setData(1, UsageRole, QString::number(item->numReferences()));
600             m_listView->blockSignals(false);
601             qApp->processEvents();
602         }
603         ++it;
604     }
605     if (m_infoQueue.isEmpty()) slotProcessNextThumbnail();
606 }
607
608 void ProjectList::slotAddClip(const QList <QUrl> givenList, const QString &groupName, const QString &groupId)
609 {
610     if (!m_commandStack) kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
611     KUrl::List list;
612     if (givenList.isEmpty()) {
613         // Build list of mime types
614         QStringList mimeTypes = QStringList() << "application/x-kdenlive" << "video/x-flv" << "application/vnd.rn-realmedia" << "video/x-dv" << "video/dv" << "video/x-msvideo" << "video/x-matroska" << "video/mlt-playlist" << "video/mpeg" << "video/ogg" << "video/x-ms-wmv" << "audio/x-flac" << "audio/x-matroska" << "audio/mp4" << "audio/mpeg" << "audio/x-mp3" << "audio/ogg" << "audio/x-wav" << "application/ogg" << "video/mp4" << "video/quicktime" << "image/gif" << "image/jpeg" << "image/png" << "image/x-tga" << "image/x-bmp" << "image/svg+xml" << "image/tiff" << "image/x-xcf-gimp" << "image/x-vnd.adobe.photoshop" << "image/x-pcx" << "image/x-exr";
615
616         QString allExtensions;
617         foreach(const QString& mimeType, mimeTypes) {
618             KMimeType::Ptr mime(KMimeType::mimeType(mimeType));
619             if (mime) {
620                 allExtensions.append(mime->patterns().join(" "));
621                 allExtensions.append(' ');
622             }
623         }
624         QString dialogFilter = allExtensions + ' ' + QLatin1Char('|') + i18n("All Supported Files");
625         dialogFilter.append("\n*" + QLatin1Char('|') + i18n("All Files"));
626         list = KFileDialog::getOpenUrls(KUrl("kfiledialog:///clipfolder"), dialogFilter, this);
627
628     } else {
629         for (int i = 0; i < givenList.count(); i++)
630             list << givenList.at(i);
631     }
632     if (list.isEmpty()) return;
633
634     if (givenList.isEmpty()) {
635         QStringList groupInfo = getGroup();
636         m_doc->slotAddClipList(list, groupInfo.at(0), groupInfo.at(1));
637     } else m_doc->slotAddClipList(list, groupName, groupId);
638 }
639
640 void ProjectList::slotRemoveInvalidClip(const QString &id, bool replace)
641 {
642     ProjectItem *item = getItemById(id);
643     QTimer::singleShot(300, this, SLOT(slotProcessNextClipInQueue()));
644     if (item) {
645         const QString path = item->referencedClip()->fileURL().path();
646         if (!path.isEmpty()) {
647             if (replace) KMessageBox::sorry(this, i18n("Clip <b>%1</b><br>is invalid, will be removed from project.", path));
648             else {
649                 if (KMessageBox::questionYesNo(this, i18n("Clip <b>%1</b><br>is missing or invalid. Remove it from project?", path), i18n("Invalid clip")) == KMessageBox::Yes) replace = true;
650             }
651         }
652         QList <QString> ids;
653         ids << id;
654         if (replace) m_doc->deleteProjectClip(ids);
655     }
656 }
657
658 void ProjectList::slotAddColorClip()
659 {
660     if (!m_commandStack) kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
661     QDialog *dia = new QDialog(this);
662     Ui::ColorClip_UI dia_ui;
663     dia_ui.setupUi(dia);
664     dia_ui.clip_name->setText(i18n("Color Clip"));
665     dia_ui.clip_duration->setText(KdenliveSettings::color_duration());
666     if (dia->exec() == QDialog::Accepted) {
667         QString color = dia_ui.clip_color->color().name();
668         color = color.replace(0, 1, "0x") + "ff";
669         QStringList groupInfo = getGroup();
670         m_doc->slotCreateColorClip(dia_ui.clip_name->text(), color, dia_ui.clip_duration->text(), groupInfo.at(0), groupInfo.at(1));
671     }
672     delete dia;
673 }
674
675
676 void ProjectList::slotAddSlideshowClip()
677 {
678     if (!m_commandStack) kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
679     SlideshowClip *dia = new SlideshowClip(m_timecode, this);
680
681     if (dia->exec() == QDialog::Accepted) {
682         QStringList groupInfo = getGroup();
683         m_doc->slotCreateSlideshowClipFile(dia->clipName(), dia->selectedPath(), dia->imageCount(), dia->clipDuration(), dia->loop(), dia->fade(), dia->lumaDuration(), dia->lumaFile(), dia->softness(), groupInfo.at(0), groupInfo.at(1));
684     }
685     delete dia;
686 }
687
688 void ProjectList::slotAddTitleClip()
689 {
690     QStringList groupInfo = getGroup();
691     m_doc->slotCreateTextClip(groupInfo.at(0), groupInfo.at(1));
692 }
693
694 void ProjectList::slotAddTitleTemplateClip()
695 {
696     QStringList groupInfo = getGroup();
697     if (!m_commandStack) kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
698
699     // Get the list of existing templates
700     QStringList filter;
701     filter << "*.kdenlivetitle";
702     const QString path = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
703     QStringList templateFiles = QDir(path).entryList(filter, QDir::Files);
704
705     QDialog *dia = new QDialog(this);
706     Ui::TemplateClip_UI dia_ui;
707     dia_ui.setupUi(dia);
708     for (int i = 0; i < templateFiles.size(); ++i) {
709         dia_ui.template_list->comboBox()->addItem(templateFiles.at(i), path + templateFiles.at(i));
710     }
711     dia_ui.template_list->fileDialog()->setFilter("*.kdenlivetitle");
712     //warning: setting base directory doesn't work??
713     KUrl startDir(path);
714     dia_ui.template_list->fileDialog()->setUrl(startDir);
715     dia_ui.description->setHidden(true);
716     if (dia->exec() == QDialog::Accepted) {
717         QString textTemplate = dia_ui.template_list->comboBox()->itemData(dia_ui.template_list->comboBox()->currentIndex()).toString();
718         if (textTemplate.isEmpty()) textTemplate = dia_ui.template_list->comboBox()->currentText();
719         if (dia_ui.normal_clip->isChecked()) {
720             // Create a normal title clip
721             m_doc->slotCreateTextClip(groupInfo.at(0), groupInfo.at(1), textTemplate);
722         } else {
723             // Create a cloned template clip
724             m_doc->slotCreateTextTemplateClip(groupInfo.at(0), groupInfo.at(1), KUrl(textTemplate));
725         }
726     }
727     delete dia;
728 }
729
730 QStringList ProjectList::getGroup() const
731 {
732     QStringList result;
733     ProjectItem *item = static_cast <ProjectItem*>(m_listView->currentItem());
734     if (item && !item->isGroup()) {
735         while (item->parent()) {
736             item = static_cast <ProjectItem*>(item->parent());
737             if (item->isGroup()) break;
738         }
739     }
740     if (item && item->isGroup()) {
741         result << item->groupName();
742         result << item->clipId();
743     } else result << QString() << QString();
744     return result;
745 }
746
747 void ProjectList::setDocument(KdenliveDoc *doc)
748 {
749     m_listView->blockSignals(true);
750     m_listView->clear();
751     emit clipSelected(NULL);
752     m_thumbnailQueue.clear();
753     m_infoQueue.clear();
754     m_refreshed = false;
755     m_fps = doc->fps();
756     m_timecode = doc->timecode();
757     m_commandStack = doc->commandStack();
758     m_doc = doc;
759
760     QMap <QString, QString> flist = doc->clipManager()->documentFolderList();
761     QMapIterator<QString, QString> f(flist);
762     while (f.hasNext()) {
763         f.next();
764         (void) new ProjectItem(m_listView, QStringList() << QString() << f.value(), f.key());
765     }
766
767     QList <DocClipBase*> list = doc->clipManager()->documentClipList();
768     for (int i = 0; i < list.count(); i++) {
769         slotAddClip(list.at(i), false);
770     }
771
772     m_listView->blockSignals(false);
773     m_toolbar->setEnabled(true);
774 }
775
776 QDomElement ProjectList::producersList()
777 {
778     QDomDocument doc;
779     QDomElement prods = doc.createElement("producerlist");
780     doc.appendChild(prods);
781     kDebug() << "////////////  PRO LISTĀ BUILD PRDSLIST ";
782     QTreeWidgetItemIterator it(m_listView);
783     while (*it) {
784         if (!((ProjectItem *)(*it))->isGroup())
785             prods.appendChild(doc.importNode(((ProjectItem *)(*it))->toXml(), true));
786         ++it;
787     }
788     return prods;
789 }
790
791 void ProjectList::slotCheckForEmptyQueue()
792 {
793     if (!m_refreshed && m_thumbnailQueue.isEmpty() && m_infoQueue.isEmpty()) {
794         m_refreshed = true;
795         emit loadingIsOver();
796     } else QTimer::singleShot(300, this, SLOT(slotCheckForEmptyQueue()));
797 }
798
799 void ProjectList::reloadClipThumbnails()
800 {
801     m_thumbnailQueue.clear();
802     QTreeWidgetItemIterator it(m_listView);
803     while (*it) {
804         if (!((ProjectItem *)(*it))->isGroup())
805             m_thumbnailQueue << ((ProjectItem *)(*it))->clipId();
806         ++it;
807     }
808     QTimer::singleShot(300, this, SLOT(slotProcessNextThumbnail()));
809 }
810
811 void ProjectList::requestClipThumbnail(const QString id)
812 {
813     m_thumbnailQueue.append(id);
814 }
815
816 void ProjectList::slotProcessNextThumbnail()
817 {
818     if (m_thumbnailQueue.isEmpty() && m_infoQueue.isEmpty()) {
819         m_listView->setEnabled(true);
820         slotCheckForEmptyQueue();
821         return;
822     }
823     if (!m_infoQueue.isEmpty()) {
824         //QTimer::singleShot(300, this, SLOT(slotProcessNextThumbnail()));
825         return;
826     }
827     slotRefreshClipThumbnail(m_thumbnailQueue.takeFirst(), false);
828 }
829
830 void ProjectList::slotRefreshClipThumbnail(const QString &clipId, bool update)
831 {
832     ProjectItem *item = getItemById(clipId);
833     if (item) slotRefreshClipThumbnail(item, update);
834     else slotProcessNextThumbnail();
835 }
836
837 void ProjectList::slotRefreshClipThumbnail(ProjectItem *item, bool update)
838 {
839     if (item) {
840         int height = 50;
841         int width = (int)(height  * m_render->dar());
842         DocClipBase *clip = item->referencedClip();
843         if (!clip) slotProcessNextThumbnail();
844         QPixmap pix;
845         if (clip->clipType() == AUDIO) pix = KIcon("audio-x-generic").pixmap(QSize(width, height));
846         else if (clip->clipType() == TEXT || clip->clipType() == IMAGE) pix = KThumb::getFrame(item->referencedClip()->producer(), 0, width, height);
847         else pix = item->referencedClip()->thumbProducer()->extractImage(item->referencedClip()->getClipThumbFrame(), width, height);
848         if (!pix.isNull()) {
849             m_listView->blockSignals(true);
850             item->setIcon(0, pix);
851             m_listView->blockSignals(false);
852             m_doc->cachePixmap(item->getClipHash(), pix);
853         }
854         if (update) emit projectModified();
855         QTimer::singleShot(100, this, SLOT(slotProcessNextThumbnail()));
856     }
857 }
858
859 void ProjectList::slotReplyGetFileProperties(const QString &clipId, Mlt::Producer *producer, const QMap < QString, QString > &properties, const QMap < QString, QString > &metadata, bool replace)
860 {
861     ProjectItem *item = getItemById(clipId);
862     if (item && producer) {
863         m_listView->blockSignals(true);
864         item->setProperties(properties, metadata);
865         Q_ASSERT_X(item->referencedClip(), "void ProjectList::slotReplyGetFileProperties", QString("Item with groupName %1 does not have a clip associated").arg(item->groupName()).toLatin1());
866         item->referencedClip()->setProducer(producer, replace);
867         emit receivedClipDuration(clipId);
868         if (replace) {
869             // update clip in clip monitor
870             emit clipSelected(NULL);
871             emit clipSelected(item->referencedClip());
872         }
873         /*else {
874             // Check if duration changed.
875             emit receivedClipDuration(clipId);
876             delete producer;
877         }*/
878         m_listView->blockSignals(false);
879         if (item->icon(0).isNull()) {
880             requestClipThumbnail(clipId);
881         }
882     } else kDebug() << "////////  COULD NOT FIND CLIP TO UPDATE PRPS...";
883
884     slotProcessNextClipInQueue();
885 }
886
887 void ProjectList::slotReplyGetImage(const QString &clipId, const QPixmap &pix)
888 {
889     ProjectItem *item = getItemById(clipId);
890     if (item && !pix.isNull()) {
891         m_listView->blockSignals(true);
892         item->setIcon(0, pix);
893         m_doc->cachePixmap(item->getClipHash(), pix);
894         m_listView->blockSignals(false);
895     }
896 }
897
898 ProjectItem *ProjectList::getItemById(const QString &id)
899 {
900     ProjectItem *item;
901     QTreeWidgetItemIterator it(m_listView);
902     while (*it) {
903         item = static_cast<ProjectItem *>(*it);
904         if (item->clipId() == id && item->clipType() != FOLDER)
905             return item;
906         ++it;
907     }
908     return NULL;
909 }
910
911 ProjectItem *ProjectList::getFolderItemById(const QString &id)
912 {
913     ProjectItem *item;
914     QTreeWidgetItemIterator it(m_listView);
915     while (*it) {
916         item = static_cast<ProjectItem *>(*it);
917         if (item->clipId() == id && item->clipType() == FOLDER)
918             return item;
919         ++it;
920     }
921     return NULL;
922 }
923
924 void ProjectList::slotSelectClip(const QString &ix)
925 {
926     ProjectItem *clip = getItemById(ix);
927     if (clip) {
928         m_listView->setCurrentItem(clip);
929         m_listView->scrollToItem(clip);
930         m_editAction->setEnabled(true);
931         m_deleteAction->setEnabled(true);
932         m_reloadAction->setEnabled(true);
933         if (clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) {
934             m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
935             m_openAction->setEnabled(true);
936         } else if (clip->clipType() == AUDIO && !KdenliveSettings::defaultaudioapp().isEmpty()) {
937             m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
938             m_openAction->setEnabled(true);
939         } else m_openAction->setEnabled(false);
940     }
941 }
942
943 QString ProjectList::currentClipUrl() const
944 {
945     ProjectItem *item = static_cast <ProjectItem*>(m_listView->currentItem());
946     if (item == NULL) return QString();
947     return item->clipUrl().path();
948 }
949
950 void ProjectList::regenerateTemplate(const QString &id)
951 {
952     ProjectItem *clip = getItemById(id);
953     if (clip) regenerateTemplate(clip);
954 }
955
956 void ProjectList::regenerateTemplate(ProjectItem *clip)
957 {
958     // Generate image for template clip
959     const QString comment = clip->referencedClip()->getProperty("description");
960     const QString path = clip->referencedClip()->getProperty("xmltemplate");
961     QDomDocument doc = generateTemplateXml(path, comment);
962     TitleWidget *dia_ui = new TitleWidget(KUrl(), QString(), m_render, this);
963     dia_ui->setXml(doc);
964     QImage pix = dia_ui->renderedPixmap();
965     pix.save(clip->clipUrl().path());
966     delete dia_ui;
967     clip->referencedClip()->producer()->set("force_reload", 1);
968 }
969
970 void ProjectList::regenerateTemplateImage(ProjectItem *clip)
971 {
972     // Generate image for template clip
973     TitleWidget *dia_ui = new TitleWidget(KUrl(), QString(), m_render, this);
974     QDomDocument doc;
975     doc.setContent(clip->referencedClip()->getProperty("xmldata"));
976     dia_ui->setXml(doc);
977     QImage pix = dia_ui->renderedPixmap();
978     pix.save(clip->clipUrl().path());
979     delete dia_ui;
980 }
981
982 QDomDocument ProjectList::generateTemplateXml(QString path, const QString &replaceString)
983 {
984     QDomDocument doc;
985     QFile file(path);
986     if (!file.open(QIODevice::ReadOnly)) {
987         kWarning() << "ERROR, CANNOT READ: " << path;
988         return doc;
989     }
990     if (!doc.setContent(&file)) {
991         kWarning() << "ERROR, CANNOT READ: " << path;
992         file.close();
993         return doc;
994     }
995     file.close();
996     QDomNodeList texts = doc.elementsByTagName("content");
997     for (int i = 0; i < texts.count(); i++) {
998         QString data = texts.item(i).firstChild().nodeValue();
999         data.replace("%s", replaceString);
1000         texts.item(i).firstChild().setNodeValue(data);
1001     }
1002     return doc;
1003 }
1004
1005 #include "projectlist.moc"