]> git.sesse.net Git - kdenlive/blob - src/projectlist.cpp
Automatically update clips when they change on disk. It means you can now edit an...
[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(const QString &id)
211 {
212     QList<QTreeWidgetItem *> selected;
213     if (id.isEmpty()) selected = m_listView->selectedItems();
214     else selected.append(getItemById(id));
215     ProjectItem *item;
216     for (int i = 0; i < selected.count(); i++) {
217         item = static_cast <ProjectItem *>(selected.at(i));
218         if (item && !item->isGroup()) {
219             if (item->clipType() == IMAGE) {
220                 item->referencedClip()->producer()->set("force_reload", 1);
221             } else if (item->clipType() == TEXT) {
222                 if (!item->referencedClip()->getProperty("xmltemplate").isEmpty()) regenerateTemplate(item);
223             }
224             //requestClipInfo(item->toXml(), item->clipId(), true);
225             // Clear the file_hash value, which will cause a complete reload of the clip
226             emit getFileProperties(item->toXml(), item->clipId(), true);
227         }
228     }
229 }
230
231 void ProjectList::setRenderer(Render *projectRender)
232 {
233     m_render = projectRender;
234     m_listView->setIconSize(QSize(40 * m_render->dar(), 40));
235 }
236
237 void ProjectList::slotClipSelected()
238 {
239     if (m_listView->currentItem()) {
240         ProjectItem *clip = static_cast <ProjectItem*>(m_listView->currentItem());
241         if (!clip->isGroup()) {
242             m_selectedItem = clip;
243             emit clipSelected(clip->referencedClip());
244         }
245         m_editAction->setEnabled(true);
246         m_deleteAction->setEnabled(true);
247         m_reloadAction->setEnabled(true);
248         if (clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) {
249             m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
250             m_openAction->setEnabled(true);
251         } else if (clip->clipType() == AUDIO && !KdenliveSettings::defaultaudioapp().isEmpty()) {
252             m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
253             m_openAction->setEnabled(true);
254         } else m_openAction->setEnabled(false);
255     } else {
256         emit clipSelected(NULL);
257         m_editAction->setEnabled(false);
258         m_deleteAction->setEnabled(false);
259         m_openAction->setEnabled(false);
260         m_reloadAction->setEnabled(false);
261     }
262 }
263
264 void ProjectList::slotPauseMonitor()
265 {
266     if (m_render) m_render->pause();
267 }
268
269 void ProjectList::slotUpdateClipProperties(const QString &id, QMap <QString, QString> properties)
270 {
271     ProjectItem *item = getItemById(id);
272     if (item) {
273         slotUpdateClipProperties(item, properties);
274         if (properties.contains("colour") || properties.contains("resource") || properties.contains("xmldata") || properties.contains("force_aspect_ratio")) {
275             slotRefreshClipThumbnail(item);
276             emit refreshClip();
277         }
278         if (properties.contains("out")) item->changeDuration(properties.value("out").toInt());
279     }
280 }
281
282 void ProjectList::slotUpdateClipProperties(ProjectItem *clip, QMap <QString, QString> properties)
283 {
284     if (!clip) return;
285     if (!clip->isGroup()) clip->setProperties(properties);
286     if (properties.contains("xmldata")) regenerateTemplateImage(clip);
287     if (properties.contains("name")) {
288         m_listView->blockSignals(true);
289         clip->setText(1, properties.value("name"));
290         m_listView->blockSignals(false);
291         emit clipNameChanged(clip->clipId(), properties.value("name"));
292     }
293     if (properties.contains("description")) {
294         CLIPTYPE type = clip->clipType();
295         m_listView->blockSignals(true);
296         clip->setText(2, properties.value("description"));
297         m_listView->blockSignals(false);
298         if (KdenliveSettings::activate_nepomuk() && (type == AUDIO || type == VIDEO || type == AV || type == IMAGE || type == PLAYLIST)) {
299             // Use Nepomuk system to store clip description
300             Nepomuk::Resource f(clip->clipUrl().path());
301             f.setDescription(properties.value("description"));
302         }
303         emit projectModified();
304     }
305 }
306
307 void ProjectList::slotItemEdited(QTreeWidgetItem *item, int column)
308 {
309     ProjectItem *clip = static_cast <ProjectItem*>(item);
310     if (column == 2) {
311         if (clip->referencedClip()) {
312             QMap <QString, QString> oldprops;
313             QMap <QString, QString> newprops;
314             oldprops["description"] = clip->referencedClip()->getProperty("description");
315             newprops["description"] = item->text(2);
316
317             if (clip->clipType() == TEXT && !clip->referencedClip()->getProperty("xmltemplate").isEmpty()) {
318                 // This is a text template clip, update the image
319                 oldprops.insert("xmldata", clip->referencedClip()->getProperty("xmldata"));
320                 newprops.insert("xmldata", generateTemplateXml(clip->referencedClip()->getProperty("xmltemplate"), item->text(2)).toString());
321             }
322
323             slotUpdateClipProperties(clip->clipId(), newprops);
324             EditClipCommand *command = new EditClipCommand(this, clip->clipId(), oldprops, newprops, false);
325             m_commandStack->push(command);
326         }
327     } else if (column == 1) {
328         if (clip->isGroup()) {
329             editFolder(item->text(1), clip->groupName(), clip->clipId());
330             clip->setGroupName(item->text(1));
331             m_doc->clipManager()->addFolder(clip->clipId(), item->text(1));
332             const int children = item->childCount();
333             for (int i = 0; i < children; i++) {
334                 ProjectItem *child = static_cast <ProjectItem *>(item->child(i));
335                 child->setProperty("groupname", item->text(1));
336             }
337         } else {
338             if (clip->referencedClip()) {
339                 QMap <QString, QString> oldprops;
340                 QMap <QString, QString> newprops;
341                 oldprops["name"] = clip->referencedClip()->getProperty("name");
342                 newprops["name"] = item->text(1);
343                 slotUpdateClipProperties(clip, newprops);
344                 emit projectModified();
345                 EditClipCommand *command = new EditClipCommand(this, clip->clipId(), oldprops, newprops, false);
346                 m_commandStack->push(command);
347             }
348         }
349     }
350 }
351
352 void ProjectList::slotContextMenu(const QPoint &pos, QTreeWidgetItem *item)
353 {
354     bool enable = false;
355     if (item) {
356         enable = true;
357     }
358     m_editAction->setEnabled(enable);
359     m_deleteAction->setEnabled(enable);
360     m_reloadAction->setEnabled(enable);
361     if (enable) {
362         ProjectItem *clip = static_cast <ProjectItem*>(item);
363         if (clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) {
364             m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
365             m_openAction->setEnabled(true);
366         } else if (clip->clipType() == AUDIO && !KdenliveSettings::defaultaudioapp().isEmpty()) {
367             m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
368             m_openAction->setEnabled(true);
369         } else m_openAction->setEnabled(false);
370     } else m_openAction->setEnabled(false);
371     m_menu->popup(pos);
372 }
373
374 void ProjectList::slotRemoveClip()
375 {
376     if (!m_listView->currentItem()) return;
377     QList <QString> ids;
378     QMap <QString, QString> folderids;
379     QList<QTreeWidgetItem *> selected = m_listView->selectedItems();
380     ProjectItem *item;
381     for (int i = 0; i < selected.count(); i++) {
382         item = static_cast <ProjectItem *>(selected.at(i));
383         if (item->isGroup()) folderids[item->groupName()] = item->clipId();
384         else ids << item->clipId();
385         if (item->numReferences() > 0) {
386             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;
387         } else if (item->isGroup() && item->childCount() > 0) {
388             int children = item->childCount();
389             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;
390             for (int i = 0; i < children; ++i) {
391                 ProjectItem *child = static_cast <ProjectItem *>(item->child(i));
392                 ids << child->clipId();
393             }
394         }
395     }
396     if (!ids.isEmpty()) m_doc->deleteProjectClip(ids);
397     if (!folderids.isEmpty()) deleteProjectFolder(folderids);
398     if (m_listView->topLevelItemCount() == 0) {
399         m_editAction->setEnabled(false);
400         m_deleteAction->setEnabled(false);
401         m_openAction->setEnabled(false);
402         m_reloadAction->setEnabled(false);
403     }
404 }
405
406 void ProjectList::selectItemById(const QString &clipId)
407 {
408     ProjectItem *item = getItemById(clipId);
409     if (item) m_listView->setCurrentItem(item);
410 }
411
412
413 void ProjectList::slotDeleteClip(const QString &clipId)
414 {
415     ProjectItem *item = getItemById(clipId);
416     if (!item) {
417         kDebug() << "/// Cannot find clip to delete";
418         return;
419     }
420     m_listView->blockSignals(true);
421     delete item;
422     m_doc->clipManager()->deleteClip(clipId);
423     m_listView->blockSignals(false);
424     slotClipSelected();
425 }
426
427
428 void ProjectList::editFolder(const QString folderName, const QString oldfolderName, const QString &clipId)
429 {
430     EditFolderCommand *command = new EditFolderCommand(this, folderName, oldfolderName, clipId, false);
431     m_commandStack->push(command);
432     m_doc->setModified(true);
433 }
434
435 void ProjectList::slotAddFolder()
436 {
437     AddFolderCommand *command = new AddFolderCommand(this, i18n("Folder"), QString::number(m_doc->clipManager()->getFreeFolderId()), true);
438     m_commandStack->push(command);
439 }
440
441 void ProjectList::slotAddFolder(const QString foldername, const QString &clipId, bool remove, bool edit)
442 {
443     if (remove) {
444         ProjectItem *item = getFolderItemById(clipId);
445         if (item) {
446             m_doc->clipManager()->deleteFolder(clipId);
447             delete item;
448         }
449     } else {
450         if (edit) {
451             ProjectItem *item = getFolderItemById(clipId);
452             QTreeWidgetItemIterator it(m_listView);
453             if (item) {
454                 m_listView->blockSignals(true);
455                 item->setGroupName(foldername);
456                 m_listView->blockSignals(false);
457                 m_doc->clipManager()->addFolder(clipId, foldername);
458                 const int children = item->childCount();
459                 for (int i = 0; i < children; i++) {
460                     ProjectItem *child = static_cast <ProjectItem *>(item->child(i));
461                     child->setProperty("groupname", foldername);
462                 }
463             }
464         } else {
465             QStringList text;
466             text << QString() << foldername;
467             m_listView->blockSignals(true);
468             m_listView->setCurrentItem(new ProjectItem(m_listView, text, clipId));
469             m_doc->clipManager()->addFolder(clipId, foldername);
470             m_listView->blockSignals(false);
471         }
472     }
473 }
474
475
476
477 void ProjectList::deleteProjectFolder(QMap <QString, QString> map)
478 {
479     QMapIterator<QString, QString> i(map);
480     QUndoCommand *delCommand = new QUndoCommand();
481     delCommand->setText(i18n("Delete Folder"));
482     while (i.hasNext()) {
483         i.next();
484         new AddFolderCommand(this, i.key(), i.value(), false, delCommand);
485     }
486     m_commandStack->push(delCommand);
487     m_doc->setModified(true);
488 }
489
490 void ProjectList::slotAddClip(DocClipBase *clip, bool getProperties)
491 {
492     if (getProperties) m_listView->setEnabled(false);
493     m_listView->blockSignals(true);
494     const QString parent = clip->getProperty("groupid");
495     kDebug() << "Adding clip with groupid: " << parent;
496     ProjectItem *item = NULL;
497     if (!parent.isEmpty()) {
498         ProjectItem *parentitem = getFolderItemById(parent);
499         if (!parentitem) {
500             QStringList text;
501             QString groupName = clip->getProperty("groupname");
502             //kDebug() << "Adding clip to new group: " << groupName;
503             if (groupName.isEmpty()) groupName = i18n("Folder");
504             text << QString() << groupName;
505             parentitem = new ProjectItem(m_listView, text, parent);
506         } else {
507             //kDebug() << "Adding clip to existing group: " << parentitem->groupName();
508         }
509         if (parentitem) item = new ProjectItem(parentitem, clip);
510     }
511     if (item == NULL) item = new ProjectItem(m_listView, clip);
512     KUrl url = clip->fileURL();
513
514     if (getProperties == false && !clip->getClipHash().isEmpty()) {
515         QString cachedPixmap = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "thumbs/" + clip->getClipHash() + ".png";
516         if (QFile::exists(cachedPixmap)) {
517             item->setIcon(0, QPixmap(cachedPixmap));
518         }
519     }
520
521     if (!url.isEmpty() && KdenliveSettings::activate_nepomuk()) {
522         // if file has Nepomuk comment, use it
523         Nepomuk::Resource f(url.path());
524         QString annotation = f.description();
525         if (!annotation.isEmpty()) item->setText(2, annotation);
526         item->setText(3, QString::number(f.rating()));
527     }
528     m_listView->blockSignals(false);
529 }
530
531 void ProjectList::slotResetProjectList()
532 {
533     m_listView->clear();
534     emit clipSelected(NULL);
535     m_thumbnailQueue.clear();
536     m_infoQueue.clear();
537     m_refreshed = false;
538 }
539
540 void ProjectList::requestClipInfo(const QDomElement xml, const QString id)
541 {
542     m_infoQueue.insert(id, xml);
543     m_listView->setEnabled(false);
544     if (!m_queueTimer.isActive()) m_queueTimer.start();
545     //if (m_infoQueue.count() == 1 || ) QTimer::singleShot(300, this, SLOT(slotProcessNextClipInQueue()));
546 }
547
548 void ProjectList::slotProcessNextClipInQueue()
549 {
550     if (m_infoQueue.isEmpty()) {
551         slotProcessNextThumbnail();
552         return;
553     }
554
555     QMap<QString, QDomElement>::const_iterator j = m_infoQueue.constBegin();
556     if (j != m_infoQueue.constEnd()) {
557         const QDomElement dom = j.value();
558         const QString id = j.key();
559         m_infoQueue.remove(j.key());
560         emit getFileProperties(dom, id, false);
561     }
562     if (!m_infoQueue.isEmpty()) m_queueTimer.start();
563 }
564
565 void ProjectList::slotUpdateClip(const QString &id)
566 {
567     ProjectItem *item = getItemById(id);
568     m_listView->blockSignals(true);
569     if (item) item->setData(1, UsageRole, QString::number(item->numReferences()));
570     m_listView->blockSignals(false);
571 }
572
573 void ProjectList::updateAllClips()
574 {
575     QTreeWidgetItemIterator it(m_listView);
576     while (*it) {
577         ProjectItem *item = static_cast <ProjectItem *>(*it);
578         if (!item->isGroup()) {
579             DocClipBase *clip = item->referencedClip();
580             if (clip->clipType() == TEXT && !QFile::exists(clip->fileURL().path())) {
581                 // regenerate text clip image if required
582                 TitleWidget *dia_ui = new TitleWidget(KUrl(), QString(), m_render, this);
583                 QDomDocument doc;
584                 doc.setContent(clip->getProperty("xmldata"));
585                 dia_ui->setXml(doc);
586                 QImage pix = dia_ui->renderedPixmap();
587                 pix.save(clip->fileURL().path());
588                 delete dia_ui;
589             }
590
591             if (item->referencedClip()->producer() == NULL) {
592                 if (clip->isPlaceHolder() == false) requestClipInfo(clip->toXML(), clip->getId());
593                 else item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
594             } else {
595                 if (item->icon(0).isNull()) {
596                     requestClipThumbnail(clip->getId());
597                 }
598                 if (item->data(1, DurationRole).toString().isEmpty()) {
599                     m_listView->blockSignals(true);
600                     item->changeDuration(item->referencedClip()->producer()->get_playtime());
601                     m_listView->blockSignals(false);
602                 }
603             }
604             m_listView->blockSignals(true);
605             item->setData(1, UsageRole, QString::number(item->numReferences()));
606             m_listView->blockSignals(false);
607             qApp->processEvents();
608         }
609         ++it;
610     }
611     if (m_infoQueue.isEmpty()) slotProcessNextThumbnail();
612 }
613
614 void ProjectList::slotAddClip(const QList <QUrl> givenList, const QString &groupName, const QString &groupId)
615 {
616     if (!m_commandStack) kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
617     KUrl::List list;
618     if (givenList.isEmpty()) {
619         // Build list of mime types
620         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";
621
622         QString allExtensions;
623         foreach(const QString& mimeType, mimeTypes) {
624             KMimeType::Ptr mime(KMimeType::mimeType(mimeType));
625             if (mime) {
626                 allExtensions.append(mime->patterns().join(" "));
627                 allExtensions.append(' ');
628             }
629         }
630         QString dialogFilter = allExtensions + ' ' + QLatin1Char('|') + i18n("All Supported Files");
631         dialogFilter.append("\n*" + QLatin1Char('|') + i18n("All Files"));
632         list = KFileDialog::getOpenUrls(KUrl("kfiledialog:///clipfolder"), dialogFilter, this);
633
634     } else {
635         for (int i = 0; i < givenList.count(); i++)
636             list << givenList.at(i);
637     }
638     if (list.isEmpty()) return;
639
640     if (givenList.isEmpty()) {
641         QStringList groupInfo = getGroup();
642         m_doc->slotAddClipList(list, groupInfo.at(0), groupInfo.at(1));
643     } else m_doc->slotAddClipList(list, groupName, groupId);
644 }
645
646 void ProjectList::slotRemoveInvalidClip(const QString &id, bool replace)
647 {
648     ProjectItem *item = getItemById(id);
649     QTimer::singleShot(300, this, SLOT(slotProcessNextClipInQueue()));
650     if (item) {
651         const QString path = item->referencedClip()->fileURL().path();
652         if (!path.isEmpty()) {
653             if (replace) KMessageBox::sorry(this, i18n("Clip <b>%1</b><br>is invalid, will be removed from project.", path));
654             else {
655                 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;
656             }
657         }
658         QList <QString> ids;
659         ids << id;
660         if (replace) m_doc->deleteProjectClip(ids);
661     }
662 }
663
664 void ProjectList::slotAddColorClip()
665 {
666     if (!m_commandStack) kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
667     QDialog *dia = new QDialog(this);
668     Ui::ColorClip_UI dia_ui;
669     dia_ui.setupUi(dia);
670     dia_ui.clip_name->setText(i18n("Color Clip"));
671     dia_ui.clip_duration->setText(KdenliveSettings::color_duration());
672     if (dia->exec() == QDialog::Accepted) {
673         QString color = dia_ui.clip_color->color().name();
674         color = color.replace(0, 1, "0x") + "ff";
675         QStringList groupInfo = getGroup();
676         m_doc->slotCreateColorClip(dia_ui.clip_name->text(), color, dia_ui.clip_duration->text(), groupInfo.at(0), groupInfo.at(1));
677     }
678     delete dia;
679 }
680
681
682 void ProjectList::slotAddSlideshowClip()
683 {
684     if (!m_commandStack) kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
685     SlideshowClip *dia = new SlideshowClip(m_timecode, this);
686
687     if (dia->exec() == QDialog::Accepted) {
688         QStringList groupInfo = getGroup();
689         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));
690     }
691     delete dia;
692 }
693
694 void ProjectList::slotAddTitleClip()
695 {
696     QStringList groupInfo = getGroup();
697     m_doc->slotCreateTextClip(groupInfo.at(0), groupInfo.at(1));
698 }
699
700 void ProjectList::slotAddTitleTemplateClip()
701 {
702     QStringList groupInfo = getGroup();
703     if (!m_commandStack) kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
704
705     // Get the list of existing templates
706     QStringList filter;
707     filter << "*.kdenlivetitle";
708     const QString path = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
709     QStringList templateFiles = QDir(path).entryList(filter, QDir::Files);
710
711     QDialog *dia = new QDialog(this);
712     Ui::TemplateClip_UI dia_ui;
713     dia_ui.setupUi(dia);
714     for (int i = 0; i < templateFiles.size(); ++i) {
715         dia_ui.template_list->comboBox()->addItem(templateFiles.at(i), path + templateFiles.at(i));
716     }
717     dia_ui.template_list->fileDialog()->setFilter("*.kdenlivetitle");
718     //warning: setting base directory doesn't work??
719     KUrl startDir(path);
720     dia_ui.template_list->fileDialog()->setUrl(startDir);
721     dia_ui.description->setHidden(true);
722     if (dia->exec() == QDialog::Accepted) {
723         QString textTemplate = dia_ui.template_list->comboBox()->itemData(dia_ui.template_list->comboBox()->currentIndex()).toString();
724         if (textTemplate.isEmpty()) textTemplate = dia_ui.template_list->comboBox()->currentText();
725         if (dia_ui.normal_clip->isChecked()) {
726             // Create a normal title clip
727             m_doc->slotCreateTextClip(groupInfo.at(0), groupInfo.at(1), textTemplate);
728         } else {
729             // Create a cloned template clip
730             m_doc->slotCreateTextTemplateClip(groupInfo.at(0), groupInfo.at(1), KUrl(textTemplate));
731         }
732     }
733     delete dia;
734 }
735
736 QStringList ProjectList::getGroup() const
737 {
738     QStringList result;
739     ProjectItem *item = static_cast <ProjectItem*>(m_listView->currentItem());
740     if (item && !item->isGroup()) {
741         while (item->parent()) {
742             item = static_cast <ProjectItem*>(item->parent());
743             if (item->isGroup()) break;
744         }
745     }
746     if (item && item->isGroup()) {
747         result << item->groupName();
748         result << item->clipId();
749     } else result << QString() << QString();
750     return result;
751 }
752
753 void ProjectList::setDocument(KdenliveDoc *doc)
754 {
755     m_listView->blockSignals(true);
756     m_listView->clear();
757     emit clipSelected(NULL);
758     m_thumbnailQueue.clear();
759     m_infoQueue.clear();
760     m_refreshed = false;
761     m_fps = doc->fps();
762     m_timecode = doc->timecode();
763     m_commandStack = doc->commandStack();
764     m_doc = doc;
765
766     connect(m_doc->clipManager(), SIGNAL(reloadClip(const QString &)), this, SLOT(slotReloadClip(const QString &)));
767
768     QMap <QString, QString> flist = doc->clipManager()->documentFolderList();
769     QMapIterator<QString, QString> f(flist);
770     while (f.hasNext()) {
771         f.next();
772         (void) new ProjectItem(m_listView, QStringList() << QString() << f.value(), f.key());
773     }
774
775     QList <DocClipBase*> list = doc->clipManager()->documentClipList();
776     for (int i = 0; i < list.count(); i++) {
777         slotAddClip(list.at(i), false);
778     }
779
780     m_listView->blockSignals(false);
781     m_toolbar->setEnabled(true);
782 }
783
784 QDomElement ProjectList::producersList()
785 {
786     QDomDocument doc;
787     QDomElement prods = doc.createElement("producerlist");
788     doc.appendChild(prods);
789     kDebug() << "////////////  PRO LISTĀ BUILD PRDSLIST ";
790     QTreeWidgetItemIterator it(m_listView);
791     while (*it) {
792         if (!((ProjectItem *)(*it))->isGroup())
793             prods.appendChild(doc.importNode(((ProjectItem *)(*it))->toXml(), true));
794         ++it;
795     }
796     return prods;
797 }
798
799 void ProjectList::slotCheckForEmptyQueue()
800 {
801     if (!m_refreshed && m_thumbnailQueue.isEmpty() && m_infoQueue.isEmpty()) {
802         m_refreshed = true;
803         emit loadingIsOver();
804     } else QTimer::singleShot(300, this, SLOT(slotCheckForEmptyQueue()));
805 }
806
807 void ProjectList::reloadClipThumbnails()
808 {
809     m_thumbnailQueue.clear();
810     QTreeWidgetItemIterator it(m_listView);
811     while (*it) {
812         if (!((ProjectItem *)(*it))->isGroup())
813             m_thumbnailQueue << ((ProjectItem *)(*it))->clipId();
814         ++it;
815     }
816     QTimer::singleShot(300, this, SLOT(slotProcessNextThumbnail()));
817 }
818
819 void ProjectList::requestClipThumbnail(const QString id)
820 {
821     m_thumbnailQueue.append(id);
822 }
823
824 void ProjectList::slotProcessNextThumbnail()
825 {
826     if (m_thumbnailQueue.isEmpty() && m_infoQueue.isEmpty()) {
827         m_listView->setEnabled(true);
828         slotCheckForEmptyQueue();
829         return;
830     }
831     if (!m_infoQueue.isEmpty()) {
832         //QTimer::singleShot(300, this, SLOT(slotProcessNextThumbnail()));
833         return;
834     }
835     slotRefreshClipThumbnail(m_thumbnailQueue.takeFirst(), false);
836 }
837
838 void ProjectList::slotRefreshClipThumbnail(const QString &clipId, bool update)
839 {
840     ProjectItem *item = getItemById(clipId);
841     if (item) slotRefreshClipThumbnail(item, update);
842     else slotProcessNextThumbnail();
843 }
844
845 void ProjectList::slotRefreshClipThumbnail(ProjectItem *item, bool update)
846 {
847     if (item) {
848         int height = 50;
849         int width = (int)(height  * m_render->dar());
850         DocClipBase *clip = item->referencedClip();
851         if (!clip) slotProcessNextThumbnail();
852         QPixmap pix;
853         if (clip->clipType() == AUDIO) pix = KIcon("audio-x-generic").pixmap(QSize(width, height));
854         else if (clip->clipType() == TEXT || clip->clipType() == IMAGE) pix = KThumb::getFrame(item->referencedClip()->producer(), 0, width, height);
855         else pix = item->referencedClip()->thumbProducer()->extractImage(item->referencedClip()->getClipThumbFrame(), width, height);
856         if (!pix.isNull()) {
857             m_listView->blockSignals(true);
858             item->setIcon(0, pix);
859             m_listView->blockSignals(false);
860             m_doc->cachePixmap(item->getClipHash(), pix);
861         }
862         if (update) emit projectModified();
863         QTimer::singleShot(100, this, SLOT(slotProcessNextThumbnail()));
864     }
865 }
866
867 void ProjectList::slotReplyGetFileProperties(const QString &clipId, Mlt::Producer *producer, const QMap < QString, QString > &properties, const QMap < QString, QString > &metadata, bool replace)
868 {
869     ProjectItem *item = getItemById(clipId);
870     if (item && producer) {
871         m_listView->blockSignals(true);
872         item->setProperties(properties, metadata);
873         Q_ASSERT_X(item->referencedClip(), "void ProjectList::slotReplyGetFileProperties", QString("Item with groupName %1 does not have a clip associated").arg(item->groupName()).toLatin1());
874         item->referencedClip()->setProducer(producer, replace);
875         emit receivedClipDuration(clipId);
876         if (replace) {
877             // update clip in clip monitor
878             emit clipSelected(NULL);
879             emit clipSelected(item->referencedClip());
880         }
881         /*else {
882             // Check if duration changed.
883             emit receivedClipDuration(clipId);
884             delete producer;
885         }*/
886         m_listView->blockSignals(false);
887         if (item->icon(0).isNull()) {
888             requestClipThumbnail(clipId);
889         }
890     } else kDebug() << "////////  COULD NOT FIND CLIP TO UPDATE PRPS...";
891
892     slotProcessNextClipInQueue();
893 }
894
895 void ProjectList::slotReplyGetImage(const QString &clipId, const QPixmap &pix)
896 {
897     ProjectItem *item = getItemById(clipId);
898     if (item && !pix.isNull()) {
899         m_listView->blockSignals(true);
900         item->setIcon(0, pix);
901         m_doc->cachePixmap(item->getClipHash(), pix);
902         m_listView->blockSignals(false);
903     }
904 }
905
906 ProjectItem *ProjectList::getItemById(const QString &id)
907 {
908     ProjectItem *item;
909     QTreeWidgetItemIterator it(m_listView);
910     while (*it) {
911         item = static_cast<ProjectItem *>(*it);
912         if (item->clipId() == id && item->clipType() != FOLDER)
913             return item;
914         ++it;
915     }
916     return NULL;
917 }
918
919 ProjectItem *ProjectList::getFolderItemById(const QString &id)
920 {
921     ProjectItem *item;
922     QTreeWidgetItemIterator it(m_listView);
923     while (*it) {
924         item = static_cast<ProjectItem *>(*it);
925         if (item->clipId() == id && item->clipType() == FOLDER)
926             return item;
927         ++it;
928     }
929     return NULL;
930 }
931
932 void ProjectList::slotSelectClip(const QString &ix)
933 {
934     ProjectItem *clip = getItemById(ix);
935     if (clip) {
936         m_listView->setCurrentItem(clip);
937         m_listView->scrollToItem(clip);
938         m_editAction->setEnabled(true);
939         m_deleteAction->setEnabled(true);
940         m_reloadAction->setEnabled(true);
941         if (clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) {
942             m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
943             m_openAction->setEnabled(true);
944         } else if (clip->clipType() == AUDIO && !KdenliveSettings::defaultaudioapp().isEmpty()) {
945             m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
946             m_openAction->setEnabled(true);
947         } else m_openAction->setEnabled(false);
948     }
949 }
950
951 QString ProjectList::currentClipUrl() const
952 {
953     ProjectItem *item = static_cast <ProjectItem*>(m_listView->currentItem());
954     if (item == NULL) return QString();
955     return item->clipUrl().path();
956 }
957
958 void ProjectList::regenerateTemplate(const QString &id)
959 {
960     ProjectItem *clip = getItemById(id);
961     if (clip) regenerateTemplate(clip);
962 }
963
964 void ProjectList::regenerateTemplate(ProjectItem *clip)
965 {
966     // Generate image for template clip
967     const QString comment = clip->referencedClip()->getProperty("description");
968     const QString path = clip->referencedClip()->getProperty("xmltemplate");
969     QDomDocument doc = generateTemplateXml(path, comment);
970     TitleWidget *dia_ui = new TitleWidget(KUrl(), QString(), m_render, this);
971     dia_ui->setXml(doc);
972     QImage pix = dia_ui->renderedPixmap();
973     pix.save(clip->clipUrl().path());
974     delete dia_ui;
975     clip->referencedClip()->producer()->set("force_reload", 1);
976 }
977
978 void ProjectList::regenerateTemplateImage(ProjectItem *clip)
979 {
980     // Generate image for template clip
981     TitleWidget *dia_ui = new TitleWidget(KUrl(), QString(), m_render, this);
982     QDomDocument doc;
983     doc.setContent(clip->referencedClip()->getProperty("xmldata"));
984     dia_ui->setXml(doc);
985     QImage pix = dia_ui->renderedPixmap();
986     pix.save(clip->clipUrl().path());
987     delete dia_ui;
988 }
989
990 QDomDocument ProjectList::generateTemplateXml(QString path, const QString &replaceString)
991 {
992     QDomDocument doc;
993     QFile file(path);
994     if (!file.open(QIODevice::ReadOnly)) {
995         kWarning() << "ERROR, CANNOT READ: " << path;
996         return doc;
997     }
998     if (!doc.setContent(&file)) {
999         kWarning() << "ERROR, CANNOT READ: " << path;
1000         file.close();
1001         return doc;
1002     }
1003     file.close();
1004     QDomNodeList texts = doc.elementsByTagName("content");
1005     for (int i = 0; i < texts.count(); i++) {
1006         QString data = texts.item(i).firstChild().nodeValue();
1007         data.replace("%s", replaceString);
1008         texts.item(i).firstChild().setNodeValue(data);
1009     }
1010     return doc;
1011 }
1012
1013 #include "projectlist.moc"