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