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