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