]> git.sesse.net Git - kdenlive/blob - src/projectlist.cpp
Fix loading of project thumbnails + possible crash on document loading
[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         return;
546     }
547
548     QMap<QString, QDomElement>::const_iterator j = m_infoQueue.constBegin();
549     if (j != m_infoQueue.constEnd()) {
550         const QDomElement dom = j.value();
551         const QString id = j.key();
552         m_infoQueue.remove(j.key());
553         emit getFileProperties(dom, id, false);
554     }
555     if (!m_infoQueue.isEmpty()) m_queueTimer.start();
556 }
557
558 void ProjectList::slotUpdateClip(const QString &id)
559 {
560     ProjectItem *item = getItemById(id);
561     m_listView->blockSignals(true);
562     if (item) item->setData(1, UsageRole, QString::number(item->numReferences()));
563     m_listView->blockSignals(false);
564 }
565
566 void ProjectList::updateAllClips()
567 {
568     QTreeWidgetItemIterator it(m_listView);
569     while (*it) {
570         ProjectItem *item = static_cast <ProjectItem *>(*it);
571         if (!item->isGroup()) {
572             DocClipBase *clip = item->referencedClip();
573             if (clip->clipType() == TEXT && !QFile::exists(clip->fileURL().path())) {
574                 // regenerate text clip image if required
575                 TitleWidget *dia_ui = new TitleWidget(KUrl(), QString(), m_render, this);
576                 QDomDocument doc;
577                 doc.setContent(clip->getProperty("xmldata"));
578                 dia_ui->setXml(doc);
579                 QImage pix = dia_ui->renderedPixmap();
580                 pix.save(clip->fileURL().path());
581                 delete dia_ui;
582             }
583
584             if (item->referencedClip()->producer() == NULL) {
585                 if (clip->isPlaceHolder() == false) requestClipInfo(clip->toXML(), clip->getId());
586                 else item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
587             } else {
588                 if (item->icon(0).isNull()) {
589                     requestClipThumbnail(clip->getId());
590                 }
591                 if (item->data(1, DurationRole).toString().isEmpty()) {
592                     m_listView->blockSignals(true);
593                     item->changeDuration(item->referencedClip()->producer()->get_playtime());
594                     m_listView->blockSignals(false);
595                 }
596             }
597             m_listView->blockSignals(true);
598             item->setData(1, UsageRole, QString::number(item->numReferences()));
599             m_listView->blockSignals(false);
600             qApp->processEvents();
601         }
602         ++it;
603     }
604     if (m_infoQueue.isEmpty()) slotProcessNextThumbnail();
605 }
606
607 void ProjectList::slotAddClip(const QList <QUrl> givenList, const QString &groupName, const QString &groupId)
608 {
609     if (!m_commandStack) kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
610     KUrl::List list;
611     if (givenList.isEmpty()) {
612         // Build list of mime types
613         QStringList mimeTypes = QStringList() << "application/x-kdenlive" << "video/x-flv" << "application/vnd.rn-realmedia" << "video/x-dv" << "video/dv" << "video/x-msvideo" << "video/mpeg" << "video/x-ms-wmv" << "audio/mpeg" << "audio/x-mp3" << "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" << "video/mlt-playlist" << "audio/x-flac" << "audio/mp4" << "video/x-matroska" << "audio/x-matroska" << "video/ogg" << "audio/ogg";
614
615         QString allExtensions;
616         foreach(const QString& mimeType, mimeTypes) {
617             KMimeType::Ptr mime(KMimeType::mimeType(mimeType));
618             if (mime) {
619                 allExtensions.append(mime->patterns().join(" "));
620                 allExtensions.append(' ');
621             }
622         }
623         QString dialogFilter = allExtensions + ' ' + QLatin1Char('|') + i18n("All Supported Files");
624         dialogFilter.append("\n*" + QLatin1Char('|') + i18n("All Files"));
625         list = KFileDialog::getOpenUrls(KUrl("kfiledialog:///clipfolder"), dialogFilter, this);
626
627     } else {
628         for (int i = 0; i < givenList.count(); i++)
629             list << givenList.at(i);
630     }
631     if (list.isEmpty()) return;
632
633     if (givenList.isEmpty()) {
634         QStringList groupInfo = getGroup();
635         m_doc->slotAddClipList(list, groupInfo.at(0), groupInfo.at(1));
636     } else m_doc->slotAddClipList(list, groupName, groupId);
637 }
638
639 void ProjectList::slotRemoveInvalidClip(const QString &id, bool replace)
640 {
641     ProjectItem *item = getItemById(id);
642     if (item) {
643         const QString path = item->referencedClip()->fileURL().path();
644         if (!path.isEmpty()) {
645             if (replace) KMessageBox::sorry(this, i18n("Clip <b>%1</b><br>is invalid, will be removed from project.", path));
646             else {
647                 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;
648             }
649         }
650         QList <QString> ids;
651         ids << id;
652         if (replace) m_doc->deleteProjectClip(ids);
653     }
654     QTimer::singleShot(300, this, SLOT(slotProcessNextClipInQueue()));
655 }
656
657 void ProjectList::slotAddColorClip()
658 {
659     if (!m_commandStack) kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
660     QDialog *dia = new QDialog(this);
661     Ui::ColorClip_UI dia_ui;
662     dia_ui.setupUi(dia);
663     dia_ui.clip_name->setText(i18n("Color Clip"));
664     dia_ui.clip_duration->setText(KdenliveSettings::color_duration());
665     if (dia->exec() == QDialog::Accepted) {
666         QString color = dia_ui.clip_color->color().name();
667         color = color.replace(0, 1, "0x") + "ff";
668         QStringList groupInfo = getGroup();
669         m_doc->slotCreateColorClip(dia_ui.clip_name->text(), color, dia_ui.clip_duration->text(), groupInfo.at(0), groupInfo.at(1));
670     }
671     delete dia;
672 }
673
674
675 void ProjectList::slotAddSlideshowClip()
676 {
677     if (!m_commandStack) kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
678     SlideshowClip *dia = new SlideshowClip(m_timecode, this);
679
680     if (dia->exec() == QDialog::Accepted) {
681         QStringList groupInfo = getGroup();
682         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));
683     }
684     delete dia;
685 }
686
687 void ProjectList::slotAddTitleClip()
688 {
689     QStringList groupInfo = getGroup();
690     m_doc->slotCreateTextClip(groupInfo.at(0), groupInfo.at(1));
691 }
692
693 void ProjectList::slotAddTitleTemplateClip()
694 {
695     QStringList groupInfo = getGroup();
696     if (!m_commandStack) kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
697
698     // Get the list of existing templates
699     QStringList filter;
700     filter << "*.kdenlivetitle";
701     const QString path = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
702     QStringList templateFiles = QDir(path).entryList(filter, QDir::Files);
703
704     QDialog *dia = new QDialog(this);
705     Ui::TemplateClip_UI dia_ui;
706     dia_ui.setupUi(dia);
707     for (int i = 0; i < templateFiles.size(); ++i) {
708         dia_ui.template_list->comboBox()->addItem(templateFiles.at(i), path + templateFiles.at(i));
709     }
710     dia_ui.template_list->fileDialog()->setFilter("*.kdenlivetitle");
711     //warning: setting base directory doesn't work??
712     KUrl startDir(path);
713     dia_ui.template_list->fileDialog()->setUrl(startDir);
714     dia_ui.description->setHidden(true);
715     if (dia->exec() == QDialog::Accepted) {
716         QString textTemplate = dia_ui.template_list->comboBox()->itemData(dia_ui.template_list->comboBox()->currentIndex()).toString();
717         if (textTemplate.isEmpty()) textTemplate = dia_ui.template_list->comboBox()->currentText();
718         if (dia_ui.normal_clip->isChecked()) {
719             // Create a normal title clip
720             m_doc->slotCreateTextClip(groupInfo.at(0), groupInfo.at(1), textTemplate);
721         } else {
722             // Create a cloned template clip
723             m_doc->slotCreateTextTemplateClip(groupInfo.at(0), groupInfo.at(1), KUrl(textTemplate));
724         }
725     }
726     delete dia;
727 }
728
729 QStringList ProjectList::getGroup() const
730 {
731     QStringList result;
732     ProjectItem *item = static_cast <ProjectItem*>(m_listView->currentItem());
733     if (item && !item->isGroup()) {
734         while (item->parent()) {
735             item = static_cast <ProjectItem*>(item->parent());
736             if (item->isGroup()) break;
737         }
738     }
739     if (item && item->isGroup()) {
740         result << item->groupName();
741         result << item->clipId();
742     } else result << QString() << QString();
743     return result;
744 }
745
746 void ProjectList::setDocument(KdenliveDoc *doc)
747 {
748     m_listView->blockSignals(true);
749     m_listView->clear();
750     emit clipSelected(NULL);
751     m_thumbnailQueue.clear();
752     m_infoQueue.clear();
753     m_refreshed = false;
754     m_fps = doc->fps();
755     m_timecode = doc->timecode();
756     m_commandStack = doc->commandStack();
757     m_doc = doc;
758
759     QMap <QString, QString> flist = doc->clipManager()->documentFolderList();
760     QMapIterator<QString, QString> f(flist);
761     while (f.hasNext()) {
762         f.next();
763         (void) new ProjectItem(m_listView, QStringList() << QString() << f.value(), f.key());
764     }
765
766     QList <DocClipBase*> list = doc->clipManager()->documentClipList();
767     for (int i = 0; i < list.count(); i++) {
768         slotAddClip(list.at(i), false);
769     }
770
771
772     QTreeWidgetItem *first = m_listView->topLevelItem(0);
773     if (first) m_listView->setCurrentItem(first);
774     m_listView->blockSignals(false);
775     m_toolbar->setEnabled(true);
776 }
777
778 QDomElement ProjectList::producersList()
779 {
780     QDomDocument doc;
781     QDomElement prods = doc.createElement("producerlist");
782     doc.appendChild(prods);
783     kDebug() << "////////////  PRO LISTĀ BUILD PRDSLIST ";
784     QTreeWidgetItemIterator it(m_listView);
785     while (*it) {
786         if (!((ProjectItem *)(*it))->isGroup())
787             prods.appendChild(doc.importNode(((ProjectItem *)(*it))->toXml(), true));
788         ++it;
789     }
790     return prods;
791 }
792
793 void ProjectList::slotCheckForEmptyQueue()
794 {
795     if (!m_refreshed && m_thumbnailQueue.isEmpty() && m_infoQueue.isEmpty()) {
796         m_listView->setEnabled(true);
797         m_refreshed = true;
798         emit loadingIsOver();
799     } else QTimer::singleShot(300, this, SLOT(slotCheckForEmptyQueue()));
800 }
801
802 void ProjectList::reloadClipThumbnails()
803 {
804     m_thumbnailQueue.clear();
805     QTreeWidgetItemIterator it(m_listView);
806     while (*it) {
807         if (!((ProjectItem *)(*it))->isGroup())
808             m_thumbnailQueue << ((ProjectItem *)(*it))->clipId();
809         ++it;
810     }
811     QTimer::singleShot(300, this, SLOT(slotProcessNextThumbnail()));
812 }
813
814 void ProjectList::requestClipThumbnail(const QString id)
815 {
816     m_thumbnailQueue.append(id);
817 }
818
819 void ProjectList::slotProcessNextThumbnail()
820 {
821     if (m_thumbnailQueue.isEmpty() && m_infoQueue.isEmpty()) {
822         slotCheckForEmptyQueue();
823         return;
824     }
825     if (!m_infoQueue.isEmpty()) {
826         QTimer::singleShot(300, this, SLOT(slotProcessNextThumbnail()));
827         return;
828     }
829     slotRefreshClipThumbnail(m_thumbnailQueue.takeFirst(), false);
830 }
831
832 void ProjectList::slotRefreshClipThumbnail(const QString &clipId, bool update)
833 {
834     ProjectItem *item = getItemById(clipId);
835     if (item) slotRefreshClipThumbnail(item, update);
836     else slotProcessNextThumbnail();
837 }
838
839 void ProjectList::slotRefreshClipThumbnail(ProjectItem *item, bool update)
840 {
841     if (item) {
842         int height = 50;
843         int width = (int)(height  * m_render->dar());
844         DocClipBase *clip = item->referencedClip();
845         if (!clip) slotProcessNextThumbnail();
846         QPixmap pix;
847         if (clip->clipType() == AUDIO) pix = KIcon("audio-x-generic").pixmap(QSize(width, height));
848         else if (clip->clipType() == TEXT || clip->clipType() == IMAGE) pix = KThumb::getFrame(item->referencedClip()->producer(), 0, width, height);
849         else pix = item->referencedClip()->thumbProducer()->extractImage(item->referencedClip()->getClipThumbFrame(), width, height);
850         if (!pix.isNull()) {
851             m_listView->blockSignals(true);
852             item->setIcon(0, pix);
853             m_listView->blockSignals(false);
854             m_doc->cachePixmap(item->getClipHash(), pix);
855         }
856         if (update) emit projectModified();
857         QTimer::singleShot(100, this, SLOT(slotProcessNextThumbnail()));
858     }
859 }
860
861 void ProjectList::slotReplyGetFileProperties(const QString &clipId, Mlt::Producer *producer, const QMap < QString, QString > &properties, const QMap < QString, QString > &metadata, bool replace)
862 {
863     ProjectItem *item = getItemById(clipId);
864     if (item && producer) {
865         m_listView->blockSignals(true);
866         item->setProperties(properties, metadata);
867         Q_ASSERT_X(item->referencedClip(), "void ProjectList::slotReplyGetFileProperties", QString("Item with groupName %1 does not have a clip associated").arg(item->groupName()).toLatin1());
868         item->referencedClip()->setProducer(producer, replace);
869         emit receivedClipDuration(clipId);
870         if (replace) {
871             // update clip in clip monitor
872             emit clipSelected(NULL);
873             emit clipSelected(item->referencedClip());
874         }
875         /*else {
876             // Check if duration changed.
877             emit receivedClipDuration(clipId);
878             delete producer;
879         }*/
880         m_listView->blockSignals(false);
881         if (item->icon(0).isNull()) {
882             requestClipThumbnail(clipId);
883         }
884     } else kDebug() << "////////  COULD NOT FIND CLIP TO UPDATE PRPS...";
885
886     if (m_infoQueue.isEmpty()) {
887         slotProcessNextThumbnail();
888     }
889 }
890
891 void ProjectList::slotReplyGetImage(const QString &clipId, const QPixmap &pix)
892 {
893     ProjectItem *item = getItemById(clipId);
894     if (item && !pix.isNull()) {
895         m_listView->blockSignals(true);
896         item->setIcon(0, pix);
897         m_doc->cachePixmap(item->getClipHash(), pix);
898         m_listView->blockSignals(false);
899     }
900 }
901
902 ProjectItem *ProjectList::getItemById(const QString &id)
903 {
904     ProjectItem *item;
905     QTreeWidgetItemIterator it(m_listView);
906     while (*it) {
907         item = static_cast<ProjectItem *>(*it);
908         if (item->clipId() == id && item->clipType() != FOLDER)
909             return item;
910         ++it;
911     }
912     return NULL;
913 }
914
915 ProjectItem *ProjectList::getFolderItemById(const QString &id)
916 {
917     ProjectItem *item;
918     QTreeWidgetItemIterator it(m_listView);
919     while (*it) {
920         item = static_cast<ProjectItem *>(*it);
921         if (item->clipId() == id && item->clipType() == FOLDER)
922             return item;
923         ++it;
924     }
925     return NULL;
926 }
927
928 void ProjectList::slotSelectClip(const QString &ix)
929 {
930     ProjectItem *clip = getItemById(ix);
931     if (clip) {
932         m_listView->setCurrentItem(clip);
933         m_listView->scrollToItem(clip);
934         m_editAction->setEnabled(true);
935         m_deleteAction->setEnabled(true);
936         m_reloadAction->setEnabled(true);
937         if (clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) {
938             m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
939             m_openAction->setEnabled(true);
940         } else if (clip->clipType() == AUDIO && !KdenliveSettings::defaultaudioapp().isEmpty()) {
941             m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
942             m_openAction->setEnabled(true);
943         } else m_openAction->setEnabled(false);
944     }
945 }
946
947 QString ProjectList::currentClipUrl() const
948 {
949     ProjectItem *item = static_cast <ProjectItem*>(m_listView->currentItem());
950     if (item == NULL) return QString();
951     return item->clipUrl().path();
952 }
953
954 void ProjectList::regenerateTemplate(const QString &id)
955 {
956     ProjectItem *clip = getItemById(id);
957     if (clip) regenerateTemplate(clip);
958 }
959
960 void ProjectList::regenerateTemplate(ProjectItem *clip)
961 {
962     // Generate image for template clip
963     const QString comment = clip->referencedClip()->getProperty("description");
964     const QString path = clip->referencedClip()->getProperty("xmltemplate");
965     QDomDocument doc = generateTemplateXml(path, comment);
966     TitleWidget *dia_ui = new TitleWidget(KUrl(), QString(), m_render, this);
967     dia_ui->setXml(doc);
968     QImage pix = dia_ui->renderedPixmap();
969     pix.save(clip->clipUrl().path());
970     delete dia_ui;
971     clip->referencedClip()->producer()->set("force_reload", 1);
972 }
973
974 void ProjectList::regenerateTemplateImage(ProjectItem *clip)
975 {
976     // Generate image for template clip
977     TitleWidget *dia_ui = new TitleWidget(KUrl(), QString(), m_render, this);
978     QDomDocument doc;
979     doc.setContent(clip->referencedClip()->getProperty("xmldata"));
980     dia_ui->setXml(doc);
981     QImage pix = dia_ui->renderedPixmap();
982     pix.save(clip->clipUrl().path());
983     delete dia_ui;
984 }
985
986 QDomDocument ProjectList::generateTemplateXml(QString path, const QString &replaceString)
987 {
988     QDomDocument doc;
989     QFile file(path);
990     if (!file.open(QIODevice::ReadOnly)) {
991         kWarning() << "ERROR, CANNOT READ: " << path;
992         return doc;
993     }
994     if (!doc.setContent(&file)) {
995         kWarning() << "ERROR, CANNOT READ: " << path;
996         file.close();
997         return doc;
998     }
999     file.close();
1000     QDomNodeList texts = doc.elementsByTagName("content");
1001     for (int i = 0; i < texts.count(); i++) {
1002         QString data = texts.item(i).firstChild().nodeValue();
1003         data.replace("%s", replaceString);
1004         texts.item(i).firstChild().setNodeValue(data);
1005     }
1006     return doc;
1007 }
1008
1009 #include "projectlist.moc"