]> git.sesse.net Git - kdenlive/blob - src/projectlist.cpp
Fix gimp mimetype
[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 "editclipcutcommand.h"
36 #include "editfoldercommand.h"
37 #include "addclipcutcommand.h"
38
39 #include "ui_templateclip_ui.h"
40
41 #include <KDebug>
42 #include <KAction>
43 #include <KLocale>
44 #include <KFileDialog>
45 #include <KInputDialog>
46 #include <KMessageBox>
47 #include <KIO/NetAccess>
48 #include <KFileItem>
49 #ifdef NEPOMUK
50 #include <nepomuk/global.h>
51 #include <nepomuk/resourcemanager.h>
52 //#include <nepomuk/tag.h>
53 #endif
54
55 #include <QMouseEvent>
56 #include <QStylePainter>
57 #include <QPixmap>
58 #include <QIcon>
59 #include <QMenu>
60 #include <QProcess>
61 #include <QHeaderView>
62
63 ProjectList::ProjectList(QWidget *parent) :
64         QWidget(parent),
65         m_render(NULL),
66         m_fps(-1),
67         m_commandStack(NULL),
68         m_editAction(NULL),
69         m_deleteAction(NULL),
70         m_openAction(NULL),
71         m_reloadAction(NULL),
72         m_transcodeAction(NULL),
73         m_doc(NULL),
74         m_refreshed(false),
75         m_infoQueue(),
76         m_thumbnailQueue()
77 {
78
79     m_listView = new ProjectListView(this);;
80     QVBoxLayout *layout = new QVBoxLayout;
81     layout->setContentsMargins(0, 0, 0, 0);
82
83     // setup toolbar
84     KTreeWidgetSearchLine *searchView = new KTreeWidgetSearchLine(this);
85     m_toolbar = new QToolBar("projectToolBar", this);
86     m_toolbar->addWidget(searchView);
87     int s = style()->pixelMetric(QStyle::PM_SmallIconSize);
88     m_toolbar->setIconSize(QSize(s, s));
89     searchView->setTreeWidget(m_listView);
90
91     m_addButton = new QToolButton(m_toolbar);
92     m_addButton->setPopupMode(QToolButton::MenuButtonPopup);
93     m_toolbar->addWidget(m_addButton);
94
95     layout->addWidget(m_toolbar);
96     layout->addWidget(m_listView);
97     setLayout(layout);
98
99     m_queueTimer.setInterval(100);
100     connect(&m_queueTimer, SIGNAL(timeout()), this, SLOT(slotProcessNextClipInQueue()));
101     m_queueTimer.setSingleShot(true);
102
103
104     connect(m_listView, SIGNAL(projectModified()), this, SIGNAL(projectModified()));
105     connect(m_listView, SIGNAL(itemSelectionChanged()), this, SLOT(slotClipSelected()));
106     connect(m_listView, SIGNAL(focusMonitor()), this, SLOT(slotClipSelected()));
107     connect(m_listView, SIGNAL(pauseMonitor()), this, SLOT(slotPauseMonitor()));
108     connect(m_listView, SIGNAL(requestMenu(const QPoint &, QTreeWidgetItem *)), this, SLOT(slotContextMenu(const QPoint &, QTreeWidgetItem *)));
109     connect(m_listView, SIGNAL(addClip()), this, SLOT(slotAddClip()));
110     connect(m_listView, SIGNAL(addClip(const QList <QUrl>, const QString &, const QString &)), this, SLOT(slotAddClip(const QList <QUrl>, const QString &, const QString &)));
111     connect(m_listView, SIGNAL(addClipCut(const QString &, int, int)), this, SLOT(slotAddClipCut(const QString &, int, int)));
112     connect(m_listView, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this, SLOT(slotItemEdited(QTreeWidgetItem *, int)));
113     connect(m_listView, SIGNAL(showProperties(DocClipBase *)), this, SIGNAL(showClipProperties(DocClipBase *)));
114
115     m_listViewDelegate = new ItemDelegate(m_listView);
116     m_listView->setItemDelegate(m_listViewDelegate);
117 #ifdef NEPOMUK
118     if (KdenliveSettings::activate_nepomuk()) {
119         Nepomuk::ResourceManager::instance()->init();
120         if (!Nepomuk::ResourceManager::instance()->initialized()) {
121             kDebug() << "Cannot communicate with Nepomuk, DISABLING it";
122             KdenliveSettings::setActivate_nepomuk(false);
123         }
124     }
125 #endif
126 }
127
128 ProjectList::~ProjectList()
129 {
130     delete m_menu;
131     delete m_toolbar;
132     m_listView->blockSignals(true);
133     m_listView->clear();
134     delete m_listViewDelegate;
135 }
136
137 void ProjectList::focusTree() const
138 {
139     m_listView->setFocus();
140 }
141
142 void ProjectList::setupMenu(QMenu *addMenu, QAction *defaultAction)
143 {
144     QList <QAction *> actions = addMenu->actions();
145     for (int i = 0; i < actions.count(); i++) {
146         if (actions.at(i)->data().toString() == "clip_properties") {
147             m_editAction = actions.at(i);
148             m_toolbar->addAction(m_editAction);
149             actions.removeAt(i);
150             i--;
151         } else if (actions.at(i)->data().toString() == "delete_clip") {
152             m_deleteAction = actions.at(i);
153             m_toolbar->addAction(m_deleteAction);
154             actions.removeAt(i);
155             i--;
156         } else if (actions.at(i)->data().toString() == "edit_clip") {
157             m_openAction = actions.at(i);
158             actions.removeAt(i);
159             i--;
160         } else if (actions.at(i)->data().toString() == "reload_clip") {
161             m_reloadAction = actions.at(i);
162             actions.removeAt(i);
163             i--;
164         }
165     }
166
167     QMenu *m = new QMenu();
168     m->addActions(actions);
169     m_addButton->setMenu(m);
170     m_addButton->setDefaultAction(defaultAction);
171     m_menu = new QMenu();
172     m_menu->addActions(addMenu->actions());
173 }
174
175 void ProjectList::setupGeneratorMenu(QMenu *addMenu, QMenu *transcodeMenu)
176 {
177     if (!addMenu) return;
178     QMenu *menu = m_addButton->menu();
179     menu->addMenu(addMenu);
180     m_addButton->setMenu(menu);
181
182     m_menu->addMenu(addMenu);
183     if (addMenu->isEmpty()) addMenu->setEnabled(false);
184     m_menu->addMenu(transcodeMenu);
185     if (transcodeMenu->isEmpty()) transcodeMenu->setEnabled(false);
186     m_transcodeAction = transcodeMenu;
187     m_menu->addAction(m_reloadAction);
188     m_menu->addAction(m_editAction);
189     m_menu->addAction(m_openAction);
190     m_menu->addAction(m_deleteAction);
191     m_menu->insertSeparator(m_deleteAction);
192 }
193
194
195 QByteArray ProjectList::headerInfo() const
196 {
197     return m_listView->header()->saveState();
198 }
199
200 void ProjectList::setHeaderInfo(const QByteArray &state)
201 {
202     m_listView->header()->restoreState(state);
203 }
204
205 void ProjectList::updateProjectFormat(Timecode t)
206 {
207     m_timecode = t;
208 }
209
210 void ProjectList::slotEditClip()
211 {
212     QList<QTreeWidgetItem *> list = m_listView->selectedItems();
213     if (list.count() > 1) {
214         editClipSelection(list);
215         return;
216     }
217     ProjectItem *item;
218     if (!m_listView->currentItem() || m_listView->currentItem()->type() == PROJECTFOLDERTYPE) return;
219     if (m_listView->currentItem()->type() == PROJECTSUBCLIPTYPE) {
220         item = static_cast <ProjectItem*>(m_listView->currentItem()->parent());
221     } else item = static_cast <ProjectItem*>(m_listView->currentItem());
222     if (!(item->flags() & Qt::ItemIsDragEnabled)) return;
223     if (item) {
224         emit clipSelected(item->referencedClip());
225         emit showClipProperties(item->referencedClip());
226     }
227 }
228
229 void ProjectList::editClipSelection(QList<QTreeWidgetItem *> list)
230 {
231     // Gather all common properties
232     QMap <QString, QString> commonproperties;
233     QList <DocClipBase *> clipList;
234     commonproperties.insert("force_aspect_ratio", "-");
235     commonproperties.insert("force_fps", "-");
236     commonproperties.insert("force_progressive", "-");
237     commonproperties.insert("threads", "-");
238     commonproperties.insert("video_index", "-");
239     commonproperties.insert("audio_index", "-");
240
241     bool allowDurationChange = true;
242     int commonDuration = -1;
243     ProjectItem *item;
244     for (int i = 0; i < list.count(); i++) {
245         item = NULL;
246         if (list.at(i)->type() == PROJECTFOLDERTYPE) continue;
247         if (list.at(i)->type() == PROJECTSUBCLIPTYPE) {
248             item = static_cast <ProjectItem*>(list.at(i)->parent());
249         } else item = static_cast <ProjectItem*>(list.at(i));
250         if (!(item->flags() & Qt::ItemIsDragEnabled)) continue;
251         if (item) {
252             // check properties
253             DocClipBase *clip = item->referencedClip();
254             if (clipList.contains(clip)) continue;
255             if (clip->clipType() != COLOR && clip->clipType() != IMAGE && clip->clipType() != TEXT) {
256                 allowDurationChange = false;
257             }
258             if (allowDurationChange && commonDuration != 0) {
259                 if (commonDuration == -1) {
260                     commonDuration = clip->duration().frames(m_fps);
261                 } else if (commonDuration != clip->duration().frames(m_fps)) {
262                     commonDuration = 0;
263                 }
264             }
265             clipList.append(clip);
266             QMap <QString, QString> clipprops = clip->properties();
267             QMapIterator<QString, QString> p(commonproperties);
268             while (p.hasNext()) {
269                 p.next();
270                 if (p.value().isEmpty()) continue;
271                 if (clipprops.contains(p.key())) {
272                     if (p.value() == "-") commonproperties.insert(p.key(), clipprops.value(p.key()));
273                     else if (p.value() != clipprops.value(p.key())) commonproperties.insert(p.key(), QString());
274                 } else commonproperties.insert(p.key(), QString());
275             }
276         }
277     }
278     if (allowDurationChange) commonproperties.insert("out", QString::number(commonDuration));
279     QMapIterator<QString, QString> p(commonproperties);
280     while (p.hasNext()) {
281         p.next();
282         kDebug() << "Result: " << p.key() << " = " << p.value();
283     }
284     emit showClipProperties(clipList, commonproperties);
285 }
286
287 void ProjectList::slotOpenClip()
288 {
289     ProjectItem *item;
290     if (!m_listView->currentItem() || m_listView->currentItem()->type() == PROJECTFOLDERTYPE) return;
291     if (m_listView->currentItem()->type() == QTreeWidgetItem::UserType + 1) {
292         item = static_cast <ProjectItem*>(m_listView->currentItem()->parent());
293     } else item = static_cast <ProjectItem*>(m_listView->currentItem());
294     if (item) {
295         if (item->clipType() == IMAGE) {
296             if (KdenliveSettings::defaultimageapp().isEmpty()) KMessageBox::sorry(this, i18n("Please set a default application to open images in the Settings dialog"));
297             else QProcess::startDetached(KdenliveSettings::defaultimageapp(), QStringList() << item->clipUrl().path());
298         }
299         if (item->clipType() == AUDIO) {
300             if (KdenliveSettings::defaultaudioapp().isEmpty()) KMessageBox::sorry(this, i18n("Please set a default application to open audio files in the Settings dialog"));
301             else QProcess::startDetached(KdenliveSettings::defaultaudioapp(), QStringList() << item->clipUrl().path());
302         }
303     }
304 }
305
306 void ProjectList::cleanup()
307 {
308     m_listView->clearSelection();
309     QTreeWidgetItemIterator it(m_listView);
310     ProjectItem *item;
311     while (*it) {
312         if ((*it)->type() != PROJECTCLIPTYPE) {
313             it++;
314             continue;
315         }
316         item = static_cast <ProjectItem *>(*it);
317         if (item->numReferences() == 0) item->setSelected(true);
318         it++;
319     }
320     slotRemoveClip();
321 }
322
323 void ProjectList::trashUnusedClips()
324 {
325     QTreeWidgetItemIterator it(m_listView);
326     ProjectItem *item;
327     QStringList ids;
328     QStringList urls;
329     while (*it) {
330         if ((*it)->type() != PROJECTCLIPTYPE) {
331             it++;
332             continue;
333         }
334         item = static_cast <ProjectItem *>(*it);
335         if (item->numReferences() == 0) {
336             ids << item->clipId();
337             KUrl url = item->clipUrl();
338             if (!url.isEmpty() && !urls.contains(url.path())) urls << url.path();
339         }
340         it++;
341     }
342
343     // Check that we don't use the URL in another clip
344     QTreeWidgetItemIterator it2(m_listView);
345     while (*it2) {
346         if ((*it2)->type() != PROJECTCLIPTYPE) {
347             it2++;
348             continue;
349         }
350         item = static_cast <ProjectItem *>(*it2);
351         if (item->numReferences() > 0) {
352             KUrl url = item->clipUrl();
353             if (!url.isEmpty() && urls.contains(url.path())) urls.removeAll(url.path());
354         }
355         it2++;
356     }
357
358     emit deleteProjectClips(ids, QMap <QString, QString>());
359     for (int i = 0; i < urls.count(); i++) {
360         KIO::NetAccess::del(KUrl(urls.at(i)), this);
361     }
362 }
363
364 void ProjectList::slotReloadClip(const QString &id)
365 {
366     QList<QTreeWidgetItem *> selected;
367     if (id.isEmpty()) selected = m_listView->selectedItems();
368     else selected.append(getItemById(id));
369     ProjectItem *item;
370     for (int i = 0; i < selected.count(); i++) {
371         if (selected.at(i)->type() != PROJECTCLIPTYPE) continue;
372         item = static_cast <ProjectItem *>(selected.at(i));
373         if (item) {
374             if (item->clipType() == IMAGE) {
375                 item->referencedClip()->producer()->set("force_reload", 1);
376             } else if (item->clipType() == TEXT) {
377                 if (!item->referencedClip()->getProperty("xmltemplate").isEmpty()) regenerateTemplate(item);
378             }
379             //requestClipInfo(item->toXml(), item->clipId(), true);
380             // Clear the file_hash value, which will cause a complete reload of the clip
381             emit getFileProperties(item->toXml(), item->clipId(), m_listView->iconSize().height(), true);
382         }
383     }
384 }
385
386 void ProjectList::setRenderer(Render *projectRender)
387 {
388     m_render = projectRender;
389     m_listView->setIconSize(QSize((ProjectItem::itemDefaultHeight() - 2) * m_render->dar(), ProjectItem::itemDefaultHeight() - 2));
390 }
391
392 void ProjectList::slotClipSelected()
393 {
394     if (!m_listView->isEnabled()) return;
395     if (m_listView->currentItem()) {
396         if (m_listView->currentItem()->type() == PROJECTFOLDERTYPE) {
397             emit clipSelected(NULL);
398             m_editAction->setEnabled(false);
399             m_deleteAction->setEnabled(true);
400             m_openAction->setEnabled(false);
401             m_reloadAction->setEnabled(false);
402             m_transcodeAction->setEnabled(false);
403         } else {
404             ProjectItem *clip;
405             if (m_listView->currentItem()->type() == PROJECTSUBCLIPTYPE) {
406                 // this is a sub item, use base clip
407                 m_deleteAction->setEnabled(true);
408                 clip = static_cast <ProjectItem*>(m_listView->currentItem()->parent());
409                 if (clip == NULL) kDebug() << "-----------ERROR";
410                 SubProjectItem *sub = static_cast <SubProjectItem*>(m_listView->currentItem());
411                 emit clipSelected(clip->referencedClip(), sub->zone());
412                 m_transcodeAction->setEnabled(false);
413                 return;
414             }
415             clip = static_cast <ProjectItem*>(m_listView->currentItem());
416             if (clip) emit clipSelected(clip->referencedClip());
417             m_editAction->setEnabled(true);
418             m_deleteAction->setEnabled(true);
419             m_reloadAction->setEnabled(true);
420             m_transcodeAction->setEnabled(true);
421             if (clip && clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) {
422                 m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
423                 m_openAction->setEnabled(true);
424             } else if (clip && clip->clipType() == AUDIO && !KdenliveSettings::defaultaudioapp().isEmpty()) {
425                 m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
426                 m_openAction->setEnabled(true);
427             } else m_openAction->setEnabled(false);
428             // Display relevant transcoding actions only
429             adjustTranscodeActions(clip);
430         }
431     } else {
432         emit clipSelected(NULL);
433         m_editAction->setEnabled(false);
434         m_deleteAction->setEnabled(false);
435         m_openAction->setEnabled(false);
436         m_reloadAction->setEnabled(false);
437         m_transcodeAction->setEnabled(false);
438     }
439 }
440
441 void ProjectList::adjustTranscodeActions(ProjectItem *clip) const
442 {
443     if (clip == NULL || clip->type() != PROJECTCLIPTYPE || clip->clipType() == COLOR || clip->clipType() == TEXT || clip->clipType() == PLAYLIST) {
444         m_transcodeAction->setEnabled(false);
445         return;
446     }
447     m_transcodeAction->setEnabled(true);
448     QList<QAction *> transcodeActions = m_transcodeAction->actions();
449     QStringList data;
450     QString condition;
451     for (int i = 0; i < transcodeActions.count(); i++) {
452         data = transcodeActions.at(i)->data().toStringList();
453         if (data.count() > 2) {
454             condition = data.at(2);
455             if (condition.startsWith("vcodec")) transcodeActions.at(i)->setEnabled(clip->referencedClip()->hasVideoCodec(condition.section("=", 1, 1)));
456             else if (condition.startsWith("acodec")) transcodeActions.at(i)->setEnabled(clip->referencedClip()->hasVideoCodec(condition.section("=", 1, 1)));
457         }
458     }
459
460 }
461
462 void ProjectList::slotPauseMonitor()
463 {
464     if (m_render) m_render->pause();
465 }
466
467 void ProjectList::slotUpdateClipProperties(const QString &id, QMap <QString, QString> properties)
468 {
469     ProjectItem *item = getItemById(id);
470     if (item) {
471         slotUpdateClipProperties(item, properties);
472         if (properties.contains("out") || properties.contains("force_fps")) {
473             slotReloadClip(id);
474         } else if (properties.contains("colour") || properties.contains("resource") || properties.contains("xmldata") || properties.contains("force_aspect_ratio") || properties.contains("templatetext")) {
475             slotRefreshClipThumbnail(item);
476             emit refreshClip();
477         }
478     }
479 }
480
481 void ProjectList::slotUpdateClipProperties(ProjectItem *clip, QMap <QString, QString> properties)
482 {
483     if (!clip) return;
484     clip->setProperties(properties);
485     if (properties.contains("name")) {
486         m_listView->blockSignals(true);
487         clip->setText(0, properties.value("name"));
488         m_listView->blockSignals(false);
489         emit clipNameChanged(clip->clipId(), properties.value("name"));
490     }
491     if (properties.contains("description")) {
492         CLIPTYPE type = clip->clipType();
493         m_listView->blockSignals(true);
494         clip->setText(1, properties.value("description"));
495         m_listView->blockSignals(false);
496 #ifdef NEPOMUK
497         if (KdenliveSettings::activate_nepomuk() && (type == AUDIO || type == VIDEO || type == AV || type == IMAGE || type == PLAYLIST)) {
498             // Use Nepomuk system to store clip description
499             Nepomuk::Resource f(clip->clipUrl().path());
500             f.setDescription(properties.value("description"));
501         }
502 #endif
503         emit projectModified();
504     }
505 }
506
507 void ProjectList::slotItemEdited(QTreeWidgetItem *item, int column)
508 {
509     if (item->type() == PROJECTSUBCLIPTYPE) {
510         // this is a sub-item
511         if (column == 1) {
512             // user edited description
513             SubProjectItem *sub = static_cast <SubProjectItem*>(item);
514             ProjectItem *item = static_cast <ProjectItem *>(sub->parent());
515             EditClipCutCommand *command = new EditClipCutCommand(this, item->clipId(), sub->zone(), sub->zone(), sub->description(), sub->text(1), true);
516             m_commandStack->push(command);
517             //slotUpdateCutClipProperties(sub->clipId(), sub->zone(), sub->text(1), sub->text(1));
518         }
519         return;
520     }
521     if (item->type() == PROJECTFOLDERTYPE) {
522         if (column != 0) return;
523         FolderProjectItem *folder = static_cast <FolderProjectItem*>(item);
524         editFolder(item->text(0), folder->groupName(), folder->clipId());
525         folder->setGroupName(item->text(0));
526         m_doc->clipManager()->addFolder(folder->clipId(), item->text(0));
527         const int children = item->childCount();
528         for (int i = 0; i < children; i++) {
529             ProjectItem *child = static_cast <ProjectItem *>(item->child(i));
530             child->setProperty("groupname", item->text(0));
531         }
532         return;
533     }
534
535     ProjectItem *clip = static_cast <ProjectItem*>(item);
536     if (column == 1) {
537         if (clip->referencedClip()) {
538             QMap <QString, QString> oldprops;
539             QMap <QString, QString> newprops;
540             oldprops["description"] = clip->referencedClip()->getProperty("description");
541             newprops["description"] = item->text(1);
542
543             if (clip->clipType() == TEXT) {
544                 // This is a text template clip, update the image
545                 /*oldprops.insert("xmldata", clip->referencedClip()->getProperty("xmldata"));
546                 newprops.insert("xmldata", generateTemplateXml(clip->referencedClip()->getProperty("xmltemplate"), item->text(2)).toString());*/
547                 oldprops.insert("templatetext", clip->referencedClip()->getProperty("templatetext"));
548                 newprops.insert("templatetext", item->text(1));
549             }
550             slotUpdateClipProperties(clip->clipId(), newprops);
551             EditClipCommand *command = new EditClipCommand(this, clip->clipId(), oldprops, newprops, false);
552             m_commandStack->push(command);
553         }
554     } else if (column == 0) {
555         if (clip->referencedClip()) {
556             QMap <QString, QString> oldprops;
557             QMap <QString, QString> newprops;
558             oldprops["name"] = clip->referencedClip()->getProperty("name");
559             newprops["name"] = item->text(0);
560             slotUpdateClipProperties(clip, newprops);
561             emit projectModified();
562             EditClipCommand *command = new EditClipCommand(this, clip->clipId(), oldprops, newprops, false);
563             m_commandStack->push(command);
564         }
565     }
566 }
567
568 void ProjectList::slotContextMenu(const QPoint &pos, QTreeWidgetItem *item)
569 {
570     bool enable = false;
571     if (item) {
572         enable = true;
573     }
574     m_editAction->setEnabled(enable);
575     m_deleteAction->setEnabled(enable);
576     m_reloadAction->setEnabled(enable);
577     m_transcodeAction->setEnabled(enable);
578     if (enable) {
579         ProjectItem *clip = NULL;
580         if (m_listView->currentItem()->type() == PROJECTSUBCLIPTYPE) {
581             clip = static_cast <ProjectItem*>(item->parent());
582             m_transcodeAction->setEnabled(false);
583         } else if (m_listView->currentItem()->type() == PROJECTCLIPTYPE) {
584             clip = static_cast <ProjectItem*>(item);
585             // Display relevant transcoding actions only
586             adjustTranscodeActions(clip);
587         } else m_transcodeAction->setEnabled(false);
588         if (clip && clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) {
589             m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
590             m_openAction->setEnabled(true);
591         } else if (clip && clip->clipType() == AUDIO && !KdenliveSettings::defaultaudioapp().isEmpty()) {
592             m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
593             m_openAction->setEnabled(true);
594         } else m_openAction->setEnabled(false);
595
596     } else m_openAction->setEnabled(false);
597     m_menu->popup(pos);
598 }
599
600 void ProjectList::slotRemoveClip()
601 {
602     if (!m_listView->currentItem()) return;
603     QStringList ids;
604     QMap <QString, QString> folderids;
605     QList<QTreeWidgetItem *> selected = m_listView->selectedItems();
606
607     QUndoCommand *delCommand = new QUndoCommand();
608     delCommand->setText(i18n("Delete Clip Zone"));
609
610     for (int i = 0; i < selected.count(); i++) {
611         if (selected.at(i)->type() == PROJECTSUBCLIPTYPE) {
612             // subitem
613             SubProjectItem *sub = static_cast <SubProjectItem *>(selected.at(i));
614             ProjectItem *item = static_cast <ProjectItem *>(sub->parent());
615             new AddClipCutCommand(this, item->clipId(), sub->zone().x(), sub->zone().y(), sub->description(), false, true, delCommand);
616         } else if (selected.at(i)->type() == PROJECTFOLDERTYPE) {
617             // folder
618             FolderProjectItem *folder = static_cast <FolderProjectItem *>(selected.at(i));
619             folderids[folder->groupName()] = folder->clipId();
620             int children = folder->childCount();
621
622             if (children > 0 && 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, folder->text(1)), i18n("Delete Folder")) != KMessageBox::Yes) return;
623             for (int i = 0; i < children; ++i) {
624                 ProjectItem *child = static_cast <ProjectItem *>(folder->child(i));
625                 ids << child->clipId();
626             }
627         } else {
628             ProjectItem *item = static_cast <ProjectItem *>(selected.at(i));
629             ids << item->clipId();
630             if (item->numReferences() > 0) {
631                 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;
632             }
633         }
634     }
635
636     if (delCommand->childCount() == 0) delete delCommand;
637     else m_commandStack->push(delCommand);
638     emit deleteProjectClips(ids, folderids);
639 }
640
641 void ProjectList::updateButtons() const
642 {
643     if (m_listView->topLevelItemCount() == 0) {
644         m_deleteAction->setEnabled(false);
645     } else {
646         m_deleteAction->setEnabled(true);
647         if (!m_listView->currentItem()) m_listView->setCurrentItem(m_listView->topLevelItem(0));
648         QTreeWidgetItem *item = m_listView->currentItem();
649         if (item && item->type() == PROJECTCLIPTYPE) {
650             m_editAction->setEnabled(true);
651             m_openAction->setEnabled(true);
652             m_reloadAction->setEnabled(true);
653             m_transcodeAction->setEnabled(true);
654             return;
655         }
656     }
657
658     m_editAction->setEnabled(false);
659     m_openAction->setEnabled(false);
660     m_reloadAction->setEnabled(false);
661     m_transcodeAction->setEnabled(false);
662 }
663
664 void ProjectList::selectItemById(const QString &clipId)
665 {
666     ProjectItem *item = getItemById(clipId);
667     if (item) m_listView->setCurrentItem(item);
668 }
669
670
671 void ProjectList::slotDeleteClip(const QString &clipId)
672 {
673     ProjectItem *item = getItemById(clipId);
674     if (!item) {
675         kDebug() << "/// Cannot find clip to delete";
676         return;
677     }
678     m_listView->blockSignals(true);
679     QTreeWidgetItem *newSelectedItem = m_listView->itemAbove(item);
680     if (!newSelectedItem) newSelectedItem = m_listView->itemBelow(item);
681     delete item;
682     m_doc->clipManager()->deleteClip(clipId);
683     m_listView->blockSignals(false);
684     if (newSelectedItem) m_listView->setCurrentItem(newSelectedItem);
685     else updateButtons();
686 }
687
688
689 void ProjectList::editFolder(const QString folderName, const QString oldfolderName, const QString &clipId)
690 {
691     EditFolderCommand *command = new EditFolderCommand(this, folderName, oldfolderName, clipId, false);
692     m_commandStack->push(command);
693     m_doc->setModified(true);
694 }
695
696 void ProjectList::slotAddFolder()
697 {
698     AddFolderCommand *command = new AddFolderCommand(this, i18n("Folder"), QString::number(m_doc->clipManager()->getFreeFolderId()), true);
699     m_commandStack->push(command);
700 }
701
702 void ProjectList::slotAddFolder(const QString foldername, const QString &clipId, bool remove, bool edit)
703 {
704     if (remove) {
705         FolderProjectItem *item = getFolderItemById(clipId);
706         if (item) {
707             m_doc->clipManager()->deleteFolder(clipId);
708             QTreeWidgetItem *newSelectedItem = m_listView->itemAbove(item);
709             if (!newSelectedItem) newSelectedItem = m_listView->itemBelow(item);
710             delete item;
711             if (newSelectedItem) m_listView->setCurrentItem(newSelectedItem);
712             else updateButtons();
713         }
714     } else {
715         if (edit) {
716             FolderProjectItem *item = getFolderItemById(clipId);
717             if (item) {
718                 m_listView->blockSignals(true);
719                 item->setGroupName(foldername);
720                 m_listView->blockSignals(false);
721                 m_doc->clipManager()->addFolder(clipId, foldername);
722                 const int children = item->childCount();
723                 for (int i = 0; i < children; i++) {
724                     ProjectItem *child = static_cast <ProjectItem *>(item->child(i));
725                     child->setProperty("groupname", foldername);
726                 }
727             }
728         } else {
729             QStringList text;
730             text << foldername;
731             m_listView->blockSignals(true);
732             m_listView->setCurrentItem(new FolderProjectItem(m_listView, text, clipId));
733             m_doc->clipManager()->addFolder(clipId, foldername);
734             m_listView->blockSignals(false);
735         }
736         updateButtons();
737     }
738     m_doc->setModified(true);
739 }
740
741
742
743 void ProjectList::deleteProjectFolder(QMap <QString, QString> map)
744 {
745     QMapIterator<QString, QString> i(map);
746     QUndoCommand *delCommand = new QUndoCommand();
747     delCommand->setText(i18n("Delete Folder"));
748     while (i.hasNext()) {
749         i.next();
750         new AddFolderCommand(this, i.key(), i.value(), false, delCommand);
751     }
752     m_commandStack->push(delCommand);
753 }
754
755 void ProjectList::slotAddClip(DocClipBase *clip, bool getProperties)
756 {
757     m_listView->setEnabled(false);
758     if (getProperties) {
759         m_listView->blockSignals(true);
760         m_refreshed = false;
761         // remove file_hash so that we load all properties for the clip
762         QDomElement e = clip->toXML().cloneNode().toElement();
763         e.removeAttribute("file_hash");
764         m_infoQueue.insert(clip->getId(), e);
765         clip->askForAudioThumbs();
766         //m_render->getFileProperties(clip->toXML(), clip->getId(), true);
767     }
768     const QString parent = clip->getProperty("groupid");
769     ProjectItem *item = NULL;
770     if (!parent.isEmpty()) {
771         FolderProjectItem *parentitem = getFolderItemById(parent);
772         if (!parentitem) {
773             QStringList text;
774             QString groupName = clip->getProperty("groupname");
775             //kDebug() << "Adding clip to new group: " << groupName;
776             if (groupName.isEmpty()) groupName = i18n("Folder");
777             text << groupName;
778             parentitem = new FolderProjectItem(m_listView, text, parent);
779         } else {
780             //kDebug() << "Adding clip to existing group: " << parentitem->groupName();
781         }
782         if (parentitem) item = new ProjectItem(parentitem, clip);
783     }
784     if (item == NULL) item = new ProjectItem(m_listView, clip);
785     KUrl url = clip->fileURL();
786
787     if (getProperties == false && !clip->getClipHash().isEmpty()) {
788         QString cachedPixmap = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "thumbs/" + clip->getClipHash() + ".png";
789         if (QFile::exists(cachedPixmap)) {
790             QPixmap pix(cachedPixmap);
791             if (pix.isNull()) KIO::NetAccess::del(KUrl(cachedPixmap), this);
792             item->setData(0, Qt::DecorationRole, pix);
793         }
794     }
795 #ifdef NEPOMUK
796     if (!url.isEmpty() && KdenliveSettings::activate_nepomuk()) {
797         // if file has Nepomuk comment, use it
798         Nepomuk::Resource f(url.path());
799         QString annotation = f.description();
800         if (!annotation.isEmpty()) item->setText(1, annotation);
801         item->setText(2, QString::number(f.rating()));
802     }
803 #endif
804     // Add cut zones
805     QList <CutZoneInfo> cuts = clip->cutZones();
806     if (!cuts.isEmpty()) {
807         for (int i = 0; i < cuts.count(); i++) {
808             SubProjectItem *sub = new SubProjectItem(item, cuts.at(i).zone.x(), cuts.at(i).zone.y(), cuts.at(i).description);
809             if (!clip->getClipHash().isEmpty()) {
810                 QString cachedPixmap = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "thumbs/" + clip->getClipHash() + '#' + QString::number(cuts.at(i).zone.x()) + ".png";
811                 if (QFile::exists(cachedPixmap)) {
812                     QPixmap pix(cachedPixmap);
813                     if (pix.isNull()) KIO::NetAccess::del(KUrl(cachedPixmap), this);
814                     sub->setData(0, Qt::DecorationRole, pix);
815                 }
816             }
817         }
818     }
819     if (m_listView->isEnabled()) {
820         updateButtons();
821         if (getProperties) m_listView->blockSignals(false);
822     }
823     if (getProperties && !m_queueTimer.isActive()) m_queueTimer.start();
824 }
825
826 void ProjectList::slotResetProjectList()
827 {
828     m_listView->clear();
829     emit clipSelected(NULL);
830     m_thumbnailQueue.clear();
831     m_infoQueue.clear();
832     m_refreshed = false;
833 }
834
835 void ProjectList::requestClipInfo(const QDomElement xml, const QString id)
836 {
837     m_refreshed = false;
838     m_infoQueue.insert(id, xml);
839     //if (m_infoQueue.count() == 1 || ) QTimer::singleShot(300, this, SLOT(slotProcessNextClipInQueue()));
840 }
841
842 void ProjectList::slotProcessNextClipInQueue()
843 {
844     if (m_infoQueue.isEmpty()) {
845         slotProcessNextThumbnail();
846         return;
847     }
848
849     QMap<QString, QDomElement>::const_iterator j = m_infoQueue.constBegin();
850     if (j != m_infoQueue.constEnd()) {
851         const QDomElement dom = j.value();
852         const QString id = j.key();
853         m_infoQueue.remove(j.key());
854         emit getFileProperties(dom, id, m_listView->iconSize().height(), false);
855     }
856 }
857
858 void ProjectList::slotUpdateClip(const QString &id)
859 {
860     ProjectItem *item = getItemById(id);
861     m_listView->blockSignals(true);
862     if (item) item->setData(0, UsageRole, QString::number(item->numReferences()));
863     m_listView->blockSignals(false);
864 }
865
866 void ProjectList::updateAllClips()
867 {
868     m_listView->setSortingEnabled(false);
869     kDebug() << "// UPDATE ALL CLPY";
870
871     QTreeWidgetItemIterator it(m_listView);
872     DocClipBase *clip;
873     ProjectItem *item;
874     m_listView->blockSignals(true);
875     while (*it) {
876         if ((*it)->type() == PROJECTSUBCLIPTYPE) {
877             // subitem
878             SubProjectItem *sub = static_cast <SubProjectItem *>(*it);
879             if (sub->data(0, Qt::DecorationRole).isNull()) {
880                 item = static_cast <ProjectItem *>((*it)->parent());
881                 requestClipThumbnail(item->clipId() + '#' + QString::number(sub->zone().x()));
882             }
883             ++it;
884             continue;
885         } else if ((*it)->type() == PROJECTFOLDERTYPE) {
886             // folder
887             ++it;
888             continue;
889         } else {
890             item = static_cast <ProjectItem *>(*it);
891             clip = item->referencedClip();
892             if (item->referencedClip()->producer() == NULL) {
893                 if (clip->isPlaceHolder() == false) {
894                     requestClipInfo(clip->toXML(), clip->getId());
895                 } else if (!clip->isPlaceHolder()) item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
896             } else {
897                 if (item->data(0, Qt::DecorationRole).isNull()) {
898                     requestClipThumbnail(clip->getId());
899                 }
900                 if (item->data(0, DurationRole).toString().isEmpty()) {
901                     item->changeDuration(item->referencedClip()->producer()->get_playtime());
902                 }
903             }
904             item->setData(0, UsageRole, QString::number(item->numReferences()));
905         }
906         //qApp->processEvents();
907         ++it;
908     }
909     if (!m_queueTimer.isActive()) m_queueTimer.start();
910     if (m_listView->isEnabled()) m_listView->blockSignals(false);
911     m_listView->setSortingEnabled(true);
912     if (m_infoQueue.isEmpty()) slotProcessNextThumbnail();
913 }
914
915 void ProjectList::slotAddClip(const QList <QUrl> givenList, const QString &groupName, const QString &groupId)
916 {
917     if (!m_commandStack) {
918         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
919     }
920     KUrl::List list;
921     if (givenList.isEmpty()) {
922         // Build list of mime types
923         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" << "image/x-xcf-gimp" << "image/x-vnd.adobe.photoshop" << "image/x-pcx" << "image/x-exr";
924
925         QString allExtensions;
926         foreach(const QString& mimeType, mimeTypes) {
927             KMimeType::Ptr mime(KMimeType::mimeType(mimeType));
928             if (mime) {
929                 allExtensions.append(mime->patterns().join(" "));
930                 allExtensions.append(' ');
931             }
932         }
933         const QString dialogFilter = allExtensions.simplified() + ' ' + QLatin1Char('|') + i18n("All Supported Files") + "\n* " + QLatin1Char('|') + i18n("All Files");
934         list = KFileDialog::getOpenUrls(KUrl("kfiledialog:///clipfolder"), dialogFilter, this);
935
936     } else {
937         for (int i = 0; i < givenList.count(); i++)
938             list << givenList.at(i);
939     }
940
941     foreach(const KUrl &file, list) {
942         // Check there is no folder here
943         KMimeType::Ptr type = KMimeType::findByUrl(file);
944         if (type->is("inode/directory")) {
945             // user dropped a folder
946             list.removeAll(file);
947         }
948     }
949
950     if (list.isEmpty()) return;
951
952     if (givenList.isEmpty()) {
953         QStringList groupInfo = getGroup();
954         m_doc->slotAddClipList(list, groupInfo.at(0), groupInfo.at(1));
955     } else m_doc->slotAddClipList(list, groupName, groupId);
956 }
957
958 void ProjectList::slotRemoveInvalidClip(const QString &id, bool replace)
959 {
960     ProjectItem *item = getItemById(id);
961     QTimer::singleShot(300, this, SLOT(slotProcessNextClipInQueue()));
962     if (item) {
963         const QString path = item->referencedClip()->fileURL().path();
964         if (item->referencedClip()->isPlaceHolder()) replace = false;
965         if (!path.isEmpty()) {
966             if (replace) KMessageBox::sorry(this, i18n("Clip <b>%1</b><br />is invalid, will be removed from project.", path));
967             else {
968                 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;
969             }
970         }
971         QStringList ids;
972         ids << id;
973         if (replace) emit deleteProjectClips(ids, QMap <QString, QString>());
974     }
975 }
976
977 void ProjectList::slotAddColorClip()
978 {
979     if (!m_commandStack) {
980         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
981     }
982     QDialog *dia = new QDialog(this);
983     Ui::ColorClip_UI dia_ui;
984     dia_ui.setupUi(dia);
985     dia->setWindowTitle(i18n("Color Clip"));
986     dia_ui.clip_name->setText(i18n("Color Clip"));
987     dia_ui.clip_duration->setInputMask(m_timecode.inputMask());
988     dia_ui.clip_duration->setText(m_timecode.reformatSeparators(KdenliveSettings::color_duration()));
989     if (dia->exec() == QDialog::Accepted) {
990         QString color = dia_ui.clip_color->color().name();
991         color = color.replace(0, 1, "0x") + "ff";
992         QStringList groupInfo = getGroup();
993         m_doc->slotCreateColorClip(dia_ui.clip_name->text(), color, dia_ui.clip_duration->text(), groupInfo.at(0), groupInfo.at(1));
994     }
995     delete dia;
996 }
997
998
999 void ProjectList::slotAddSlideshowClip()
1000 {
1001     if (!m_commandStack) {
1002         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1003     }
1004     SlideshowClip *dia = new SlideshowClip(m_timecode, this);
1005
1006     if (dia->exec() == QDialog::Accepted) {
1007         QStringList groupInfo = getGroup();
1008         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));
1009     }
1010     delete dia;
1011 }
1012
1013 void ProjectList::slotAddTitleClip()
1014 {
1015     QStringList groupInfo = getGroup();
1016     m_doc->slotCreateTextClip(groupInfo.at(0), groupInfo.at(1));
1017 }
1018
1019 void ProjectList::slotAddTitleTemplateClip()
1020 {
1021     QStringList groupInfo = getGroup();
1022     if (!m_commandStack) {
1023         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1024     }
1025
1026     // Get the list of existing templates
1027     QStringList filter;
1028     filter << "*.kdenlivetitle";
1029     const QString path = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1030     QStringList templateFiles = QDir(path).entryList(filter, QDir::Files);
1031
1032     QDialog *dia = new QDialog(this);
1033     Ui::TemplateClip_UI dia_ui;
1034     dia_ui.setupUi(dia);
1035     for (int i = 0; i < templateFiles.size(); ++i) {
1036         dia_ui.template_list->comboBox()->addItem(templateFiles.at(i), path + templateFiles.at(i));
1037     }
1038     dia_ui.template_list->fileDialog()->setFilter("*.kdenlivetitle");
1039     //warning: setting base directory doesn't work??
1040     KUrl startDir(path);
1041     dia_ui.template_list->fileDialog()->setUrl(startDir);
1042     dia_ui.text_box->setHidden(true);
1043     if (dia->exec() == QDialog::Accepted) {
1044         QString textTemplate = dia_ui.template_list->comboBox()->itemData(dia_ui.template_list->comboBox()->currentIndex()).toString();
1045         if (textTemplate.isEmpty()) textTemplate = dia_ui.template_list->comboBox()->currentText();
1046         // Create a cloned template clip
1047         m_doc->slotCreateTextTemplateClip(groupInfo.at(0), groupInfo.at(1), KUrl(textTemplate));
1048     }
1049     delete dia;
1050 }
1051
1052 QStringList ProjectList::getGroup() const
1053 {
1054     QStringList result;
1055     QTreeWidgetItem *item = m_listView->currentItem();
1056     while (item && item->type() != PROJECTFOLDERTYPE) {
1057         item = item->parent();
1058     }
1059
1060     if (item) {
1061         FolderProjectItem *folder = static_cast <FolderProjectItem *>(item);
1062         result << folder->groupName();
1063         result << folder->clipId();
1064     } else result << QString() << QString();
1065     return result;
1066 }
1067
1068 void ProjectList::setDocument(KdenliveDoc *doc)
1069 {
1070     m_listView->blockSignals(true);
1071     m_listView->clear();
1072     m_listView->setSortingEnabled(false);
1073     emit clipSelected(NULL);
1074     m_thumbnailQueue.clear();
1075     m_infoQueue.clear();
1076     m_refreshed = false;
1077     m_fps = doc->fps();
1078     m_timecode = doc->timecode();
1079     m_commandStack = doc->commandStack();
1080     m_doc = doc;
1081
1082     QMap <QString, QString> flist = doc->clipManager()->documentFolderList();
1083     QMapIterator<QString, QString> f(flist);
1084     while (f.hasNext()) {
1085         f.next();
1086         (void) new FolderProjectItem(m_listView, QStringList() << f.value(), f.key());
1087     }
1088
1089     QList <DocClipBase*> list = doc->clipManager()->documentClipList();
1090     for (int i = 0; i < list.count(); i++) {
1091         slotAddClip(list.at(i), false);
1092     }
1093
1094     m_listView->blockSignals(false);
1095     m_toolbar->setEnabled(true);
1096     connect(m_doc->clipManager(), SIGNAL(reloadClip(const QString &)), this, SLOT(slotReloadClip(const QString &)));
1097     connect(m_doc->clipManager(), SIGNAL(checkAllClips()), this, SLOT(updateAllClips()));
1098 }
1099
1100 QList <DocClipBase*> ProjectList::documentClipList() const
1101 {
1102     if (m_doc == NULL) return QList <DocClipBase*> ();
1103     return m_doc->clipManager()->documentClipList();
1104 }
1105
1106 QDomElement ProjectList::producersList()
1107 {
1108     QDomDocument doc;
1109     QDomElement prods = doc.createElement("producerlist");
1110     doc.appendChild(prods);
1111     kDebug() << "////////////  PRO LIST BUILD PRDSLIST ";
1112     QTreeWidgetItemIterator it(m_listView);
1113     while (*it) {
1114         if ((*it)->type() != PROJECTCLIPTYPE) {
1115             // subitem
1116             ++it;
1117             continue;
1118         }
1119         prods.appendChild(doc.importNode(((ProjectItem *)(*it))->toXml(), true));
1120         ++it;
1121     }
1122     return prods;
1123 }
1124
1125 void ProjectList::slotCheckForEmptyQueue()
1126 {
1127     if (!m_refreshed && m_thumbnailQueue.isEmpty() && m_infoQueue.isEmpty()) {
1128         m_refreshed = true;
1129         emit loadingIsOver();
1130         emit displayMessage(QString(), -1);
1131         m_listView->blockSignals(false);
1132         m_listView->setEnabled(true);
1133         updateButtons();
1134     } else if (!m_refreshed) QTimer::singleShot(300, this, SLOT(slotCheckForEmptyQueue()));
1135 }
1136
1137 void ProjectList::reloadClipThumbnails()
1138 {
1139     kDebug() << "//////////////  RELOAD CLIPS THUMBNAILS!!!";
1140     m_thumbnailQueue.clear();
1141     QTreeWidgetItemIterator it(m_listView);
1142     while (*it) {
1143         if ((*it)->type() != PROJECTCLIPTYPE) {
1144             // subitem
1145             ++it;
1146             continue;
1147         }
1148         m_thumbnailQueue << ((ProjectItem *)(*it))->clipId();
1149         ++it;
1150     }
1151     QTimer::singleShot(300, this, SLOT(slotProcessNextThumbnail()));
1152 }
1153
1154 void ProjectList::requestClipThumbnail(const QString id)
1155 {
1156     if (!m_thumbnailQueue.contains(id)) m_thumbnailQueue.append(id);
1157 }
1158
1159 void ProjectList::slotProcessNextThumbnail()
1160 {
1161     if (m_thumbnailQueue.isEmpty() && m_infoQueue.isEmpty()) {
1162         slotCheckForEmptyQueue();
1163         return;
1164     }
1165     if (!m_infoQueue.isEmpty()) {
1166         //QTimer::singleShot(300, this, SLOT(slotProcessNextThumbnail()));
1167         return;
1168     }
1169     if (m_thumbnailQueue.count() > 1) {
1170         int max = m_doc->clipManager()->clipsCount();
1171         emit displayMessage(i18n("Loading thumbnails"), (int)(100 *(max - m_thumbnailQueue.count()) / max));
1172     }
1173     slotRefreshClipThumbnail(m_thumbnailQueue.takeFirst(), false);
1174 }
1175
1176 void ProjectList::slotRefreshClipThumbnail(const QString &clipId, bool update)
1177 {
1178     QTreeWidgetItem *item = getAnyItemById(clipId);
1179     if (item) slotRefreshClipThumbnail(item, update);
1180     else slotProcessNextThumbnail();
1181 }
1182
1183 void ProjectList::slotRefreshClipThumbnail(QTreeWidgetItem *it, bool update)
1184 {
1185     if (it == NULL) return;
1186     ProjectItem *item = NULL;
1187     bool isSubItem = false;
1188     int frame;
1189     if (it->type() == PROJECTFOLDERTYPE) return;
1190     if (it->type() == PROJECTSUBCLIPTYPE) {
1191         item = static_cast <ProjectItem *>(it->parent());
1192         frame = static_cast <SubProjectItem *>(it)->zone().x();
1193         isSubItem = true;
1194     } else {
1195         item = static_cast <ProjectItem *>(it);
1196         frame = item->referencedClip()->getClipThumbFrame();
1197     }
1198
1199     if (item) {
1200         DocClipBase *clip = item->referencedClip();
1201         if (!clip) {
1202             slotProcessNextThumbnail();
1203             return;
1204         }
1205         QPixmap pix;
1206         int height = m_listView->iconSize().height();
1207         int width = (int)(height  * m_render->dar());
1208         if (clip->clipType() == AUDIO) pix = KIcon("audio-x-generic").pixmap(QSize(width, height));
1209         else if (clip->clipType() == IMAGE) pix = QPixmap::fromImage(KThumb::getFrame(item->referencedClip()->producer(), 0, width, height));
1210         else pix = item->referencedClip()->thumbProducer()->extractImage(frame, width, height);
1211
1212         if (!pix.isNull()) {
1213             m_listView->blockSignals(true);
1214             it->setData(0, Qt::DecorationRole, pix);
1215             if (m_listView->isEnabled()) m_listView->blockSignals(false);
1216             if (!isSubItem) m_doc->cachePixmap(item->getClipHash(), pix);
1217             else m_doc->cachePixmap(item->getClipHash() + '#' + QString::number(frame), pix);
1218         }
1219         if (update) emit projectModified();
1220         QTimer::singleShot(30, this, SLOT(slotProcessNextThumbnail()));
1221     }
1222 }
1223
1224 void ProjectList::slotReplyGetFileProperties(const QString &clipId, Mlt::Producer *producer, const QMap < QString, QString > &properties, const QMap < QString, QString > &metadata, bool replace)
1225 {
1226     QString toReload;
1227     ProjectItem *item = getItemById(clipId);
1228     if (item && producer) {
1229         m_listView->blockSignals(true);
1230         item->setProperties(properties, metadata);
1231         if (item->referencedClip()->isPlaceHolder() && producer->is_valid()) {
1232             item->referencedClip()->setValid();
1233             item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | Qt::ItemIsEditable);
1234             toReload = clipId;
1235         }
1236         //Q_ASSERT_X(item->referencedClip(), "void ProjectList::slotReplyGetFileProperties", QString("Item with groupName %1 does not have a clip associated").arg(item->groupName()).toLatin1());
1237         item->referencedClip()->setProducer(producer, replace);
1238         item->referencedClip()->askForAudioThumbs();
1239         if (!replace && item->data(0, Qt::DecorationRole).isNull()) {
1240             requestClipThumbnail(clipId);
1241         }
1242         //emit receivedClipDuration(clipId);
1243         if (m_listView->isEnabled() && replace) {
1244             // update clip in clip monitor
1245             emit clipSelected(NULL);
1246             emit clipSelected(item->referencedClip());
1247             //TODO: Make sure the line below has no side effect
1248             toReload = clipId;
1249         }
1250         /*else {
1251             // Check if duration changed.
1252             emit receivedClipDuration(clipId);
1253             delete producer;
1254         }*/
1255         if (m_listView->isEnabled()) m_listView->blockSignals(false);
1256         /*if (item->icon(0).isNull()) {
1257             requestClipThumbnail(clipId);
1258         }*/
1259     } else kDebug() << "////////  COULD NOT FIND CLIP TO UPDATE PRPS...";
1260     int max = m_doc->clipManager()->clipsCount();
1261     if (item && m_infoQueue.isEmpty() && m_thumbnailQueue.isEmpty()) {
1262         m_listView->setCurrentItem(item);
1263         emit clipSelected(item->referencedClip());
1264     } else emit displayMessage(i18n("Loading clips"), (int)(100 *(max - m_infoQueue.count()) / max));
1265     if (!toReload.isEmpty()) emit clipNeedsReload(toReload, true);
1266     // small delay so that the app can display the progress info
1267     QTimer::singleShot(30, this, SLOT(slotProcessNextClipInQueue()));
1268 }
1269
1270 void ProjectList::slotReplyGetImage(const QString &clipId, const QPixmap &pix)
1271 {
1272     ProjectItem *item = getItemById(clipId);
1273     if (item && !pix.isNull()) {
1274         m_listView->blockSignals(true);
1275         item->setData(0, Qt::DecorationRole, pix);
1276         m_doc->cachePixmap(item->getClipHash(), pix);
1277         if (m_listView->isEnabled()) m_listView->blockSignals(false);
1278     }
1279 }
1280
1281 QTreeWidgetItem *ProjectList::getAnyItemById(const QString &id)
1282 {
1283     QTreeWidgetItemIterator it(m_listView);
1284     QString lookId = id;
1285     if (id.contains('#')) {
1286         lookId = id.section('#', 0, 0);
1287     }
1288
1289     ProjectItem *result = NULL;
1290     while (*it) {
1291         if ((*it)->type() != PROJECTCLIPTYPE) {
1292             // subitem
1293             ++it;
1294             continue;
1295         }
1296         ProjectItem *item = static_cast<ProjectItem *>(*it);
1297         if (item->clipId() == lookId) {
1298             result = item;
1299             break;
1300         }
1301         ++it;
1302     }
1303     if (result == NULL || !id.contains('#')) return result;
1304     else for (int i = 0; i < result->childCount(); i++) {
1305             SubProjectItem *sub = static_cast <SubProjectItem *>(result->child(i));
1306             if (sub && sub->zone().x() == id.section('#', 1, 1).toInt()) {
1307                 return sub;
1308             }
1309         }
1310
1311     return NULL;
1312 }
1313
1314
1315 ProjectItem *ProjectList::getItemById(const QString &id)
1316 {
1317     ProjectItem *item;
1318     QTreeWidgetItemIterator it(m_listView);
1319     while (*it) {
1320         if ((*it)->type() != PROJECTCLIPTYPE) {
1321             // subitem
1322             ++it;
1323             continue;
1324         }
1325         item = static_cast<ProjectItem *>(*it);
1326         if (item->clipId() == id)
1327             return item;
1328         ++it;
1329     }
1330     return NULL;
1331 }
1332
1333 FolderProjectItem *ProjectList::getFolderItemById(const QString &id)
1334 {
1335     FolderProjectItem *item;
1336     QTreeWidgetItemIterator it(m_listView);
1337     while (*it) {
1338         if ((*it)->type() == PROJECTFOLDERTYPE) {
1339             item = static_cast<FolderProjectItem *>(*it);
1340             if (item->clipId() == id) return item;
1341         }
1342         ++it;
1343     }
1344     return NULL;
1345 }
1346
1347 void ProjectList::slotSelectClip(const QString &ix)
1348 {
1349     ProjectItem *clip = getItemById(ix);
1350     if (clip) {
1351         m_listView->setCurrentItem(clip);
1352         m_listView->scrollToItem(clip);
1353         m_editAction->setEnabled(true);
1354         m_deleteAction->setEnabled(true);
1355         m_reloadAction->setEnabled(true);
1356         m_transcodeAction->setEnabled(true);
1357         if (clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) {
1358             m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
1359             m_openAction->setEnabled(true);
1360         } else if (clip->clipType() == AUDIO && !KdenliveSettings::defaultaudioapp().isEmpty()) {
1361             m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
1362             m_openAction->setEnabled(true);
1363         } else m_openAction->setEnabled(false);
1364     }
1365 }
1366
1367 QString ProjectList::currentClipUrl() const
1368 {
1369     ProjectItem *item;
1370     if (!m_listView->currentItem() || m_listView->currentItem()->type() == PROJECTFOLDERTYPE) return QString();
1371     if (m_listView->currentItem()->type() == PROJECTSUBCLIPTYPE) {
1372         // subitem
1373         item = static_cast <ProjectItem*>(m_listView->currentItem()->parent());
1374     } else item = static_cast <ProjectItem*>(m_listView->currentItem());
1375     if (item == NULL) return QString();
1376     return item->clipUrl().path();
1377 }
1378
1379 KUrl::List ProjectList::getConditionalUrls(const QString &condition) const
1380 {
1381     KUrl::List result;
1382     ProjectItem *item;
1383     QList<QTreeWidgetItem *> list = m_listView->selectedItems();
1384     for (int i = 0; i < list.count(); i++) {
1385         if (list.at(i)->type() == PROJECTFOLDERTYPE) continue;
1386         if (list.at(i)->type() == PROJECTSUBCLIPTYPE) {
1387             // subitem
1388             item = static_cast <ProjectItem*>(list.at(i)->parent());
1389         } else item = static_cast <ProjectItem*>(list.at(i));
1390         if (item == NULL) continue;
1391         if (item->type() == COLOR || item->type() == SLIDESHOW || item->type() == TEXT) continue;
1392         DocClipBase *clip = item->referencedClip();
1393         if (!condition.isEmpty()) {
1394             if (condition.startsWith("vcodec") && !clip->hasVideoCodec(condition.section("=", 1, 1))) continue;
1395             else if (condition.startsWith("acodec") && !clip->hasAudioCodec(condition.section("=", 1, 1))) continue;
1396         }
1397         result.append(item->clipUrl());
1398     }
1399     return result;
1400 }
1401
1402 void ProjectList::regenerateTemplate(const QString &id)
1403 {
1404     ProjectItem *clip = getItemById(id);
1405     if (clip) regenerateTemplate(clip);
1406 }
1407
1408 void ProjectList::regenerateTemplate(ProjectItem *clip)
1409 {
1410     //TODO: remove this unused method, only force_reload is necessary
1411     clip->referencedClip()->producer()->set("force_reload", 1);
1412 }
1413
1414 QDomDocument ProjectList::generateTemplateXml(QString path, const QString &replaceString)
1415 {
1416     QDomDocument doc;
1417     QFile file(path);
1418     if (!file.open(QIODevice::ReadOnly)) {
1419         kWarning() << "ERROR, CANNOT READ: " << path;
1420         return doc;
1421     }
1422     if (!doc.setContent(&file)) {
1423         kWarning() << "ERROR, CANNOT READ: " << path;
1424         file.close();
1425         return doc;
1426     }
1427     file.close();
1428     QDomNodeList texts = doc.elementsByTagName("content");
1429     for (int i = 0; i < texts.count(); i++) {
1430         QString data = texts.item(i).firstChild().nodeValue();
1431         data.replace("%s", replaceString);
1432         texts.item(i).firstChild().setNodeValue(data);
1433     }
1434     return doc;
1435 }
1436
1437
1438 void ProjectList::slotAddClipCut(const QString &id, int in, int out)
1439 {
1440     ProjectItem *clip = getItemById(id);
1441     if (clip == NULL) return;
1442     if (clip->referencedClip()->hasCutZone(QPoint(in, out))) return;
1443     AddClipCutCommand *command = new AddClipCutCommand(this, id, in, out, QString(), true, false);
1444     m_commandStack->push(command);
1445 }
1446
1447 void ProjectList::addClipCut(const QString &id, int in, int out, const QString desc, bool newItem)
1448 {
1449     ProjectItem *clip = getItemById(id);
1450     if (clip) {
1451         DocClipBase *base = clip->referencedClip();
1452         base->addCutZone(in, out);
1453         m_listView->blockSignals(true);
1454         SubProjectItem *sub = new SubProjectItem(clip, in, out, desc);
1455         if (newItem && desc.isEmpty() && !m_listView->isColumnHidden(1)) {
1456             if (!clip->isExpanded()) clip->setExpanded(true);
1457             m_listView->editItem(sub, 1);
1458         }
1459         QPixmap p = clip->referencedClip()->thumbProducer()->extractImage(in, (int)(sub->sizeHint(0).height()  * m_render->dar()), sub->sizeHint(0).height() - 2);
1460         sub->setData(0, Qt::DecorationRole, p);
1461         m_doc->cachePixmap(clip->getClipHash() + '#' + QString::number(in), p);
1462         m_listView->blockSignals(false);
1463     }
1464     emit projectModified();
1465 }
1466
1467 void ProjectList::removeClipCut(const QString &id, int in, int out)
1468 {
1469     ProjectItem *clip = getItemById(id);
1470     if (clip) {
1471         DocClipBase *base = clip->referencedClip();
1472         base->removeCutZone(in, out);
1473         SubProjectItem *sub = getSubItem(clip, QPoint(in, out));
1474         if (sub) {
1475             m_listView->blockSignals(true);
1476             delete sub;
1477             m_listView->blockSignals(false);
1478         }
1479     }
1480     emit projectModified();
1481 }
1482
1483 SubProjectItem *ProjectList::getSubItem(ProjectItem *clip, QPoint zone)
1484 {
1485     SubProjectItem *sub = NULL;
1486     if (clip) {
1487         for (int i = 0; i < clip->childCount(); i++) {
1488             QTreeWidgetItem *it = clip->child(i);
1489             if (it->type() == PROJECTSUBCLIPTYPE) {
1490                 sub = static_cast <SubProjectItem*>(it);
1491                 if (sub->zone() == zone) break;
1492                 else sub = NULL;
1493             }
1494         }
1495     }
1496     return sub;
1497 }
1498
1499 void ProjectList::slotUpdateClipCut(QPoint p)
1500 {
1501     if (!m_listView->currentItem() || m_listView->currentItem()->type() != PROJECTSUBCLIPTYPE) return;
1502     SubProjectItem *sub = static_cast <SubProjectItem*>(m_listView->currentItem());
1503     ProjectItem *item = static_cast <ProjectItem *>(sub->parent());
1504     EditClipCutCommand *command = new EditClipCutCommand(this, item->clipId(), sub->zone(), p, sub->text(1), sub->text(1), true);
1505     m_commandStack->push(command);
1506 }
1507
1508 void ProjectList::doUpdateClipCut(const QString &id, const QPoint oldzone, const QPoint zone, const QString &comment)
1509 {
1510     ProjectItem *clip = getItemById(id);
1511     SubProjectItem *sub = getSubItem(clip, oldzone);
1512     if (sub == NULL || clip == NULL) return;
1513     DocClipBase *base = clip->referencedClip();
1514     base->updateCutZone(oldzone.x(), oldzone.y(), zone.x(), zone.y(), comment);
1515     m_listView->blockSignals(true);
1516     sub->setZone(zone);
1517     sub->setDescription(comment);
1518     m_listView->blockSignals(false);
1519     emit projectModified();
1520 }
1521
1522 #include "projectlist.moc"