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