]> git.sesse.net Git - kdenlive/blob - src/projectlist.cpp
Fix dropframe timecode, patch from John T. Mertz
[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->currentItem()) {
395         if (m_listView->currentItem()->type() == PROJECTFOLDERTYPE) {
396             emit clipSelected(NULL);
397             m_editAction->setEnabled(false);
398             m_deleteAction->setEnabled(true);
399             m_openAction->setEnabled(false);
400             m_reloadAction->setEnabled(false);
401             m_transcodeAction->setEnabled(false);
402         } else {
403             ProjectItem *clip;
404             if (m_listView->currentItem()->type() == PROJECTSUBCLIPTYPE) {
405                 // this is a sub item, use base clip
406                 m_deleteAction->setEnabled(true);
407                 clip = static_cast <ProjectItem*>(m_listView->currentItem()->parent());
408                 if (clip == NULL) kDebug() << "-----------ERROR";
409                 SubProjectItem *sub = static_cast <SubProjectItem*>(m_listView->currentItem());
410                 emit clipSelected(clip->referencedClip(), sub->zone());
411                 m_transcodeAction->setEnabled(false);
412                 return;
413             }
414             clip = static_cast <ProjectItem*>(m_listView->currentItem());
415             if (clip) emit clipSelected(clip->referencedClip());
416             m_editAction->setEnabled(true);
417             m_deleteAction->setEnabled(true);
418             m_reloadAction->setEnabled(true);
419             m_transcodeAction->setEnabled(true);
420             if (clip && clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) {
421                 m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
422                 m_openAction->setEnabled(true);
423             } else if (clip && clip->clipType() == AUDIO && !KdenliveSettings::defaultaudioapp().isEmpty()) {
424                 m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
425                 m_openAction->setEnabled(true);
426             } else m_openAction->setEnabled(false);
427             // Display relevant transcoding actions only
428             adjustTranscodeActions(clip);
429         }
430     } else {
431         emit clipSelected(NULL);
432         m_editAction->setEnabled(false);
433         m_deleteAction->setEnabled(false);
434         m_openAction->setEnabled(false);
435         m_reloadAction->setEnabled(false);
436         m_transcodeAction->setEnabled(false);
437     }
438 }
439
440 void ProjectList::adjustTranscodeActions(ProjectItem *clip) const
441 {
442     if (clip == NULL || clip->type() != PROJECTCLIPTYPE || clip->clipType() == COLOR || clip->clipType() == TEXT || clip->clipType() == PLAYLIST) {
443         m_transcodeAction->setEnabled(false);
444         return;
445     }
446     m_transcodeAction->setEnabled(true);
447     QList<QAction *> transcodeActions = m_transcodeAction->actions();
448     QStringList data;
449     QString condition;
450     for (int i = 0; i < transcodeActions.count(); i++) {
451         data = transcodeActions.at(i)->data().toStringList();
452         if (data.count() > 2) {
453             condition = data.at(2);
454             if (condition.startsWith("vcodec")) transcodeActions.at(i)->setEnabled(clip->referencedClip()->hasVideoCodec(condition.section("=", 1, 1)));
455             else if (condition.startsWith("acodec")) transcodeActions.at(i)->setEnabled(clip->referencedClip()->hasVideoCodec(condition.section("=", 1, 1)));
456         }
457     }
458
459 }
460
461 void ProjectList::slotPauseMonitor()
462 {
463     if (m_render) m_render->pause();
464 }
465
466 void ProjectList::slotUpdateClipProperties(const QString &id, QMap <QString, QString> properties)
467 {
468     ProjectItem *item = getItemById(id);
469     if (item) {
470         slotUpdateClipProperties(item, properties);
471         if (properties.contains("out") || properties.contains("force_fps")) {
472             slotReloadClip(id);
473         } else if (properties.contains("colour") || properties.contains("resource") || properties.contains("xmldata") || properties.contains("force_aspect_ratio") || properties.contains("templatetext")) {
474             slotRefreshClipThumbnail(item);
475             emit refreshClip();
476         }
477     }
478 }
479
480 void ProjectList::slotUpdateClipProperties(ProjectItem *clip, QMap <QString, QString> properties)
481 {
482     if (!clip) return;
483     clip->setProperties(properties);
484     if (properties.contains("name")) {
485         m_listView->blockSignals(true);
486         clip->setText(0, properties.value("name"));
487         m_listView->blockSignals(false);
488         emit clipNameChanged(clip->clipId(), properties.value("name"));
489     }
490     if (properties.contains("description")) {
491         CLIPTYPE type = clip->clipType();
492         m_listView->blockSignals(true);
493         clip->setText(1, properties.value("description"));
494         m_listView->blockSignals(false);
495 #ifdef NEPOMUK
496         if (KdenliveSettings::activate_nepomuk() && (type == AUDIO || type == VIDEO || type == AV || type == IMAGE || type == PLAYLIST)) {
497             // Use Nepomuk system to store clip description
498             Nepomuk::Resource f(clip->clipUrl().path());
499             f.setDescription(properties.value("description"));
500         }
501 #endif
502         emit projectModified();
503     }
504 }
505
506 void ProjectList::slotItemEdited(QTreeWidgetItem *item, int column)
507 {
508     if (item->type() == PROJECTSUBCLIPTYPE) {
509         // this is a sub-item
510         if (column == 1) {
511             // user edited description
512             SubProjectItem *sub = static_cast <SubProjectItem*>(item);
513             ProjectItem *item = static_cast <ProjectItem *>(sub->parent());
514             EditClipCutCommand *command = new EditClipCutCommand(this, item->clipId(), sub->zone(), sub->zone(), sub->description(), sub->text(1), true);
515             m_commandStack->push(command);
516             //slotUpdateCutClipProperties(sub->clipId(), sub->zone(), sub->text(1), sub->text(1));
517         }
518         return;
519     }
520     if (item->type() == PROJECTFOLDERTYPE) {
521         if (column != 0) return;
522         FolderProjectItem *folder = static_cast <FolderProjectItem*>(item);
523         editFolder(item->text(0), folder->groupName(), folder->clipId());
524         folder->setGroupName(item->text(0));
525         m_doc->clipManager()->addFolder(folder->clipId(), item->text(0));
526         const int children = item->childCount();
527         for (int i = 0; i < children; i++) {
528             ProjectItem *child = static_cast <ProjectItem *>(item->child(i));
529             child->setProperty("groupname", item->text(0));
530         }
531         return;
532     }
533
534     ProjectItem *clip = static_cast <ProjectItem*>(item);
535     if (column == 1) {
536         if (clip->referencedClip()) {
537             QMap <QString, QString> oldprops;
538             QMap <QString, QString> newprops;
539             oldprops["description"] = clip->referencedClip()->getProperty("description");
540             newprops["description"] = item->text(1);
541
542             if (clip->clipType() == TEXT) {
543                 // This is a text template clip, update the image
544                 /*oldprops.insert("xmldata", clip->referencedClip()->getProperty("xmldata"));
545                 newprops.insert("xmldata", generateTemplateXml(clip->referencedClip()->getProperty("xmltemplate"), item->text(2)).toString());*/
546                 oldprops.insert("templatetext", clip->referencedClip()->getProperty("templatetext"));
547                 newprops.insert("templatetext", item->text(1));
548             }
549             slotUpdateClipProperties(clip->clipId(), newprops);
550             EditClipCommand *command = new EditClipCommand(this, clip->clipId(), oldprops, newprops, false);
551             m_commandStack->push(command);
552         }
553     } else if (column == 0) {
554         if (clip->referencedClip()) {
555             QMap <QString, QString> oldprops;
556             QMap <QString, QString> newprops;
557             oldprops["name"] = clip->referencedClip()->getProperty("name");
558             newprops["name"] = item->text(0);
559             slotUpdateClipProperties(clip, newprops);
560             emit projectModified();
561             EditClipCommand *command = new EditClipCommand(this, clip->clipId(), oldprops, newprops, false);
562             m_commandStack->push(command);
563         }
564     }
565 }
566
567 void ProjectList::slotContextMenu(const QPoint &pos, QTreeWidgetItem *item)
568 {
569     bool enable = false;
570     if (item) {
571         enable = true;
572     }
573     m_editAction->setEnabled(enable);
574     m_deleteAction->setEnabled(enable);
575     m_reloadAction->setEnabled(enable);
576     m_transcodeAction->setEnabled(enable);
577     if (enable) {
578         ProjectItem *clip = NULL;
579         if (m_listView->currentItem()->type() == PROJECTSUBCLIPTYPE) {
580             clip = static_cast <ProjectItem*>(item->parent());
581             m_transcodeAction->setEnabled(false);
582         } else if (m_listView->currentItem()->type() == PROJECTCLIPTYPE) {
583             clip = static_cast <ProjectItem*>(item);
584             // Display relevant transcoding actions only
585             adjustTranscodeActions(clip);
586         } else m_transcodeAction->setEnabled(false);
587         if (clip && clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) {
588             m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
589             m_openAction->setEnabled(true);
590         } else if (clip && clip->clipType() == AUDIO && !KdenliveSettings::defaultaudioapp().isEmpty()) {
591             m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
592             m_openAction->setEnabled(true);
593         } else m_openAction->setEnabled(false);
594
595     } else m_openAction->setEnabled(false);
596     m_menu->popup(pos);
597 }
598
599 void ProjectList::slotRemoveClip()
600 {
601     if (!m_listView->currentItem()) return;
602     QStringList ids;
603     QMap <QString, QString> folderids;
604     QList<QTreeWidgetItem *> selected = m_listView->selectedItems();
605
606     QUndoCommand *delCommand = new QUndoCommand();
607     delCommand->setText(i18n("Delete Clip Zone"));
608
609     for (int i = 0; i < selected.count(); i++) {
610         if (selected.at(i)->type() == PROJECTSUBCLIPTYPE) {
611             // subitem
612             SubProjectItem *sub = static_cast <SubProjectItem *>(selected.at(i));
613             ProjectItem *item = static_cast <ProjectItem *>(sub->parent());
614             new AddClipCutCommand(this, item->clipId(), sub->zone().x(), sub->zone().y(), sub->description(), false, true, delCommand);
615         } else if (selected.at(i)->type() == PROJECTFOLDERTYPE) {
616             // folder
617             FolderProjectItem *folder = static_cast <FolderProjectItem *>(selected.at(i));
618             folderids[folder->groupName()] = folder->clipId();
619             int children = folder->childCount();
620
621             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;
622             for (int i = 0; i < children; ++i) {
623                 ProjectItem *child = static_cast <ProjectItem *>(folder->child(i));
624                 ids << child->clipId();
625             }
626         } else {
627             ProjectItem *item = static_cast <ProjectItem *>(selected.at(i));
628             ids << item->clipId();
629             if (item->numReferences() > 0) {
630                 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;
631             }
632         }
633     }
634
635     if (delCommand->childCount() == 0) delete delCommand;
636     else m_commandStack->push(delCommand);
637     emit deleteProjectClips(ids, folderids);
638 }
639
640 void ProjectList::updateButtons() const
641 {
642     if (m_listView->topLevelItemCount() == 0) {
643         m_deleteAction->setEnabled(false);
644     } else {
645         m_deleteAction->setEnabled(true);
646         if (!m_listView->currentItem()) m_listView->setCurrentItem(m_listView->topLevelItem(0));
647         QTreeWidgetItem *item = m_listView->currentItem();
648         if (item && item->type() == PROJECTCLIPTYPE) {
649             m_editAction->setEnabled(true);
650             m_openAction->setEnabled(true);
651             m_reloadAction->setEnabled(true);
652             m_transcodeAction->setEnabled(true);
653             return;
654         }
655     }
656
657     m_editAction->setEnabled(false);
658     m_openAction->setEnabled(false);
659     m_reloadAction->setEnabled(false);
660     m_transcodeAction->setEnabled(false);
661 }
662
663 void ProjectList::selectItemById(const QString &clipId)
664 {
665     ProjectItem *item = getItemById(clipId);
666     if (item) m_listView->setCurrentItem(item);
667 }
668
669
670 void ProjectList::slotDeleteClip(const QString &clipId)
671 {
672     ProjectItem *item = getItemById(clipId);
673     if (!item) {
674         kDebug() << "/// Cannot find clip to delete";
675         return;
676     }
677     m_listView->blockSignals(true);
678     QTreeWidgetItem *newSelectedItem = m_listView->itemAbove(item);
679     if (!newSelectedItem) newSelectedItem = m_listView->itemBelow(item);
680     delete item;
681     m_doc->clipManager()->deleteClip(clipId);
682     m_listView->blockSignals(false);
683     if (newSelectedItem) m_listView->setCurrentItem(newSelectedItem);
684     else updateButtons();
685 }
686
687
688 void ProjectList::editFolder(const QString folderName, const QString oldfolderName, const QString &clipId)
689 {
690     EditFolderCommand *command = new EditFolderCommand(this, folderName, oldfolderName, clipId, false);
691     m_commandStack->push(command);
692     m_doc->setModified(true);
693 }
694
695 void ProjectList::slotAddFolder()
696 {
697     AddFolderCommand *command = new AddFolderCommand(this, i18n("Folder"), QString::number(m_doc->clipManager()->getFreeFolderId()), true);
698     m_commandStack->push(command);
699 }
700
701 void ProjectList::slotAddFolder(const QString foldername, const QString &clipId, bool remove, bool edit)
702 {
703     if (remove) {
704         FolderProjectItem *item = getFolderItemById(clipId);
705         if (item) {
706             m_doc->clipManager()->deleteFolder(clipId);
707             QTreeWidgetItem *newSelectedItem = m_listView->itemAbove(item);
708             if (!newSelectedItem) newSelectedItem = m_listView->itemBelow(item);
709             delete item;
710             if (newSelectedItem) m_listView->setCurrentItem(newSelectedItem);
711             else updateButtons();
712         }
713     } else {
714         if (edit) {
715             FolderProjectItem *item = getFolderItemById(clipId);
716             if (item) {
717                 m_listView->blockSignals(true);
718                 item->setGroupName(foldername);
719                 m_listView->blockSignals(false);
720                 m_doc->clipManager()->addFolder(clipId, foldername);
721                 const int children = item->childCount();
722                 for (int i = 0; i < children; i++) {
723                     ProjectItem *child = static_cast <ProjectItem *>(item->child(i));
724                     child->setProperty("groupname", foldername);
725                 }
726             }
727         } else {
728             QStringList text;
729             text << foldername;
730             m_listView->blockSignals(true);
731             m_listView->setCurrentItem(new FolderProjectItem(m_listView, text, clipId));
732             m_doc->clipManager()->addFolder(clipId, foldername);
733             m_listView->blockSignals(false);
734         }
735         updateButtons();
736     }
737     m_doc->setModified(true);
738 }
739
740
741
742 void ProjectList::deleteProjectFolder(QMap <QString, QString> map)
743 {
744     QMapIterator<QString, QString> i(map);
745     QUndoCommand *delCommand = new QUndoCommand();
746     delCommand->setText(i18n("Delete Folder"));
747     while (i.hasNext()) {
748         i.next();
749         new AddFolderCommand(this, i.key(), i.value(), false, delCommand);
750     }
751     m_commandStack->push(delCommand);
752 }
753
754 void ProjectList::slotAddClip(DocClipBase *clip, bool getProperties)
755 {
756     m_listView->setEnabled(false);
757     if (getProperties) {
758         m_listView->blockSignals(true);
759         m_refreshed = false;
760         // remove file_hash so that we load all properties for the clip
761         QDomElement e = clip->toXML().cloneNode().toElement();
762         e.removeAttribute("file_hash");
763         m_infoQueue.insert(clip->getId(), e);
764         clip->askForAudioThumbs();
765         //m_render->getFileProperties(clip->toXML(), clip->getId(), true);
766     }
767     const QString parent = clip->getProperty("groupid");
768     ProjectItem *item = NULL;
769     if (!parent.isEmpty()) {
770         FolderProjectItem *parentitem = getFolderItemById(parent);
771         if (!parentitem) {
772             QStringList text;
773             QString groupName = clip->getProperty("groupname");
774             //kDebug() << "Adding clip to new group: " << groupName;
775             if (groupName.isEmpty()) groupName = i18n("Folder");
776             text << groupName;
777             parentitem = new FolderProjectItem(m_listView, text, parent);
778         } else {
779             //kDebug() << "Adding clip to existing group: " << parentitem->groupName();
780         }
781         if (parentitem) item = new ProjectItem(parentitem, clip);
782     }
783     if (item == NULL) item = new ProjectItem(m_listView, clip);
784     KUrl url = clip->fileURL();
785
786     if (getProperties == false && !clip->getClipHash().isEmpty()) {
787         QString cachedPixmap = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "thumbs/" + clip->getClipHash() + ".png";
788         if (QFile::exists(cachedPixmap)) {
789             QPixmap pix(cachedPixmap);
790             if (pix.isNull()) KIO::NetAccess::del(KUrl(cachedPixmap), this);
791             item->setData(0, Qt::DecorationRole, pix);
792         }
793     }
794 #ifdef NEPOMUK
795     if (!url.isEmpty() && KdenliveSettings::activate_nepomuk()) {
796         // if file has Nepomuk comment, use it
797         Nepomuk::Resource f(url.path());
798         QString annotation = f.description();
799         if (!annotation.isEmpty()) item->setText(1, annotation);
800         item->setText(2, QString::number(f.rating()));
801     }
802 #endif
803     // Add cut zones
804     QList <CutZoneInfo> cuts = clip->cutZones();
805     if (!cuts.isEmpty()) {
806         for (int i = 0; i < cuts.count(); i++) {
807             SubProjectItem *sub = new SubProjectItem(item, cuts.at(i).zone.x(), cuts.at(i).zone.y(), cuts.at(i).description);
808             if (!clip->getClipHash().isEmpty()) {
809                 QString cachedPixmap = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "thumbs/" + clip->getClipHash() + '#' + QString::number(cuts.at(i).zone.x()) + ".png";
810                 if (QFile::exists(cachedPixmap)) {
811                     QPixmap pix(cachedPixmap);
812                     if (pix.isNull()) KIO::NetAccess::del(KUrl(cachedPixmap), this);
813                     sub->setData(0, Qt::DecorationRole, pix);
814                 }
815             }
816         }
817     }
818     if (m_listView->isEnabled()) {
819         updateButtons();
820         if (getProperties) m_listView->blockSignals(false);
821     }
822     if (getProperties && !m_queueTimer.isActive()) m_queueTimer.start();
823 }
824
825 void ProjectList::slotResetProjectList()
826 {
827     m_listView->clear();
828     emit clipSelected(NULL);
829     m_thumbnailQueue.clear();
830     m_infoQueue.clear();
831     m_refreshed = false;
832 }
833
834 void ProjectList::requestClipInfo(const QDomElement xml, const QString id)
835 {
836     m_refreshed = false;
837     m_infoQueue.insert(id, xml);
838     //if (m_infoQueue.count() == 1 || ) QTimer::singleShot(300, this, SLOT(slotProcessNextClipInQueue()));
839 }
840
841 void ProjectList::slotProcessNextClipInQueue()
842 {
843     if (m_infoQueue.isEmpty()) {
844         slotProcessNextThumbnail();
845         return;
846     }
847
848     QMap<QString, QDomElement>::const_iterator j = m_infoQueue.constBegin();
849     if (j != m_infoQueue.constEnd()) {
850         const QDomElement dom = j.value();
851         const QString id = j.key();
852         m_infoQueue.remove(j.key());
853         emit getFileProperties(dom, id, m_listView->iconSize().height(), false);
854     }
855 }
856
857 void ProjectList::slotUpdateClip(const QString &id)
858 {
859     ProjectItem *item = getItemById(id);
860     m_listView->blockSignals(true);
861     if (item) item->setData(0, UsageRole, QString::number(item->numReferences()));
862     m_listView->blockSignals(false);
863 }
864
865 void ProjectList::updateAllClips()
866 {
867     m_listView->setSortingEnabled(false);
868     kDebug() << "// UPDATE ALL CLPY";
869
870     QTreeWidgetItemIterator it(m_listView);
871     DocClipBase *clip;
872     ProjectItem *item;
873     m_listView->blockSignals(true);
874     while (*it) {
875         if ((*it)->type() == PROJECTSUBCLIPTYPE) {
876             // subitem
877             SubProjectItem *sub = static_cast <SubProjectItem *>(*it);
878             if (sub->data(0, Qt::DecorationRole).isNull()) {
879                 item = static_cast <ProjectItem *>((*it)->parent());
880                 requestClipThumbnail(item->clipId() + '#' + QString::number(sub->zone().x()));
881             }
882             ++it;
883             continue;
884         } else if ((*it)->type() == PROJECTFOLDERTYPE) {
885             // folder
886             ++it;
887             continue;
888         } else {
889             item = static_cast <ProjectItem *>(*it);
890             clip = item->referencedClip();
891             if (item->referencedClip()->producer() == NULL) {
892                 if (clip->isPlaceHolder() == false) {
893                     requestClipInfo(clip->toXML(), clip->getId());
894                 } else if (!clip->isPlaceHolder()) item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
895             } else {
896                 if (item->data(0, Qt::DecorationRole).isNull()) {
897                     requestClipThumbnail(clip->getId());
898                 }
899                 if (item->data(0, DurationRole).toString().isEmpty()) {
900                     item->changeDuration(item->referencedClip()->producer()->get_playtime());
901                 }
902             }
903             item->setData(0, UsageRole, QString::number(item->numReferences()));
904         }
905         //qApp->processEvents();
906         ++it;
907     }
908     if (!m_queueTimer.isActive()) m_queueTimer.start();
909     if (m_listView->isEnabled()) m_listView->blockSignals(false);
910     m_listView->setSortingEnabled(true);
911     if (m_infoQueue.isEmpty()) slotProcessNextThumbnail();
912 }
913
914 void ProjectList::slotAddClip(const QList <QUrl> givenList, const QString &groupName, const QString &groupId)
915 {
916     if (!m_commandStack) {
917         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
918     }
919     KUrl::List list;
920     if (givenList.isEmpty()) {
921         // Build list of mime types
922         QStringList mimeTypes = QStringList() << "application/x-kdenlive" << "application/x-kdenlivetitle" << "video/x-flv" << "application/vnd.rn-realmedia" << "video/x-dv" << "video/dv" << "video/x-msvideo" << "video/x-matroska" << "video/mlt-playlist" << "video/mpeg" << "video/ogg" << "video/x-ms-wmv" << "audio/x-flac" << "audio/x-matroska" << "audio/mp4" << "audio/mpeg" << "audio/x-mp3" << "audio/ogg" << "audio/x-wav" << "application/ogg" << "video/mp4" << "video/quicktime" << "image/gif" << "image/jpeg" << "image/png" << "image/x-tga" << "image/x-bmp" << "image/svg+xml" << "image/tiff" << "image/x-xcf-gimp" << "image/x-vnd.adobe.photoshop" << "image/x-pcx" << "image/x-exr";
923
924         QString allExtensions;
925         foreach(const QString& mimeType, mimeTypes) {
926             KMimeType::Ptr mime(KMimeType::mimeType(mimeType));
927             if (mime) {
928                 allExtensions.append(mime->patterns().join(" "));
929                 allExtensions.append(' ');
930             }
931         }
932         const QString dialogFilter = allExtensions.simplified() + ' ' + QLatin1Char('|') + i18n("All Supported Files") + "\n* " + QLatin1Char('|') + i18n("All Files");
933         list = KFileDialog::getOpenUrls(KUrl("kfiledialog:///clipfolder"), dialogFilter, this);
934
935     } else {
936         for (int i = 0; i < givenList.count(); i++)
937             list << givenList.at(i);
938     }
939
940     foreach(const KUrl &file, list) {
941         // Check there is no folder here
942         KMimeType::Ptr type = KMimeType::findByUrl(file);
943         if (type->is("inode/directory")) {
944             // user dropped a folder
945             list.removeAll(file);
946         }
947     }
948
949     if (list.isEmpty()) return;
950
951     if (givenList.isEmpty()) {
952         QStringList groupInfo = getGroup();
953         m_doc->slotAddClipList(list, groupInfo.at(0), groupInfo.at(1));
954     } else m_doc->slotAddClipList(list, groupName, groupId);
955 }
956
957 void ProjectList::slotRemoveInvalidClip(const QString &id, bool replace)
958 {
959     ProjectItem *item = getItemById(id);
960     QTimer::singleShot(300, this, SLOT(slotProcessNextClipInQueue()));
961     if (item) {
962         const QString path = item->referencedClip()->fileURL().path();
963         if (item->referencedClip()->isPlaceHolder()) replace = false;
964         if (!path.isEmpty()) {
965             if (replace) KMessageBox::sorry(this, i18n("Clip <b>%1</b><br />is invalid, will be removed from project.", path));
966             else {
967                 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;
968             }
969         }
970         QStringList ids;
971         ids << id;
972         if (replace) emit deleteProjectClips(ids, QMap <QString, QString>());
973     }
974 }
975
976 void ProjectList::slotAddColorClip()
977 {
978     if (!m_commandStack) {
979         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
980     }
981     QDialog *dia = new QDialog(this);
982     Ui::ColorClip_UI dia_ui;
983     dia_ui.setupUi(dia);
984     dia->setWindowTitle(i18n("Color Clip"));
985     dia_ui.clip_name->setText(i18n("Color Clip"));
986     dia_ui.clip_duration->setInputMask(m_timecode.inputMask());
987     dia_ui.clip_duration->setText(m_timecode.reformatSeparators(KdenliveSettings::color_duration()));
988     if (dia->exec() == QDialog::Accepted) {
989         QString color = dia_ui.clip_color->color().name();
990         color = color.replace(0, 1, "0x") + "ff";
991         QStringList groupInfo = getGroup();
992         m_doc->slotCreateColorClip(dia_ui.clip_name->text(), color, dia_ui.clip_duration->text(), groupInfo.at(0), groupInfo.at(1));
993     }
994     delete dia;
995 }
996
997
998 void ProjectList::slotAddSlideshowClip()
999 {
1000     if (!m_commandStack) {
1001         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1002     }
1003     SlideshowClip *dia = new SlideshowClip(m_timecode, this);
1004
1005     if (dia->exec() == QDialog::Accepted) {
1006         QStringList groupInfo = getGroup();
1007         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));
1008     }
1009     delete dia;
1010 }
1011
1012 void ProjectList::slotAddTitleClip()
1013 {
1014     QStringList groupInfo = getGroup();
1015     m_doc->slotCreateTextClip(groupInfo.at(0), groupInfo.at(1));
1016 }
1017
1018 void ProjectList::slotAddTitleTemplateClip()
1019 {
1020     QStringList groupInfo = getGroup();
1021     if (!m_commandStack) {
1022         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1023     }
1024
1025     // Get the list of existing templates
1026     QStringList filter;
1027     filter << "*.kdenlivetitle";
1028     const QString path = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1029     QStringList templateFiles = QDir(path).entryList(filter, QDir::Files);
1030
1031     QDialog *dia = new QDialog(this);
1032     Ui::TemplateClip_UI dia_ui;
1033     dia_ui.setupUi(dia);
1034     for (int i = 0; i < templateFiles.size(); ++i) {
1035         dia_ui.template_list->comboBox()->addItem(templateFiles.at(i), path + templateFiles.at(i));
1036     }
1037     dia_ui.template_list->fileDialog()->setFilter("*.kdenlivetitle");
1038     //warning: setting base directory doesn't work??
1039     KUrl startDir(path);
1040     dia_ui.template_list->fileDialog()->setUrl(startDir);
1041     dia_ui.text_box->setHidden(true);
1042     if (dia->exec() == QDialog::Accepted) {
1043         QString textTemplate = dia_ui.template_list->comboBox()->itemData(dia_ui.template_list->comboBox()->currentIndex()).toString();
1044         if (textTemplate.isEmpty()) textTemplate = dia_ui.template_list->comboBox()->currentText();
1045         // Create a cloned template clip
1046         m_doc->slotCreateTextTemplateClip(groupInfo.at(0), groupInfo.at(1), KUrl(textTemplate));
1047     }
1048     delete dia;
1049 }
1050
1051 QStringList ProjectList::getGroup() const
1052 {
1053     QStringList result;
1054     QTreeWidgetItem *item = m_listView->currentItem();
1055     while (item && item->type() != PROJECTFOLDERTYPE) {
1056         item = item->parent();
1057     }
1058
1059     if (item) {
1060         FolderProjectItem *folder = static_cast <FolderProjectItem *>(item);
1061         result << folder->groupName();
1062         result << folder->clipId();
1063     } else result << QString() << QString();
1064     return result;
1065 }
1066
1067 void ProjectList::setDocument(KdenliveDoc *doc)
1068 {
1069     m_listView->blockSignals(true);
1070     m_listView->clear();
1071     m_listView->setSortingEnabled(false);
1072     emit clipSelected(NULL);
1073     m_thumbnailQueue.clear();
1074     m_infoQueue.clear();
1075     m_refreshed = false;
1076     m_fps = doc->fps();
1077     m_timecode = doc->timecode();
1078     m_commandStack = doc->commandStack();
1079     m_doc = doc;
1080
1081     QMap <QString, QString> flist = doc->clipManager()->documentFolderList();
1082     QMapIterator<QString, QString> f(flist);
1083     while (f.hasNext()) {
1084         f.next();
1085         (void) new FolderProjectItem(m_listView, QStringList() << f.value(), f.key());
1086     }
1087
1088     QList <DocClipBase*> list = doc->clipManager()->documentClipList();
1089     for (int i = 0; i < list.count(); i++) {
1090         slotAddClip(list.at(i), false);
1091     }
1092
1093     m_listView->blockSignals(false);
1094     m_toolbar->setEnabled(true);
1095     connect(m_doc->clipManager(), SIGNAL(reloadClip(const QString &)), this, SLOT(slotReloadClip(const QString &)));
1096     connect(m_doc->clipManager(), SIGNAL(checkAllClips()), this, SLOT(updateAllClips()));
1097 }
1098
1099 QList <DocClipBase*> ProjectList::documentClipList() const
1100 {
1101     if (m_doc == NULL) return QList <DocClipBase*> ();
1102     return m_doc->clipManager()->documentClipList();
1103 }
1104
1105 QDomElement ProjectList::producersList()
1106 {
1107     QDomDocument doc;
1108     QDomElement prods = doc.createElement("producerlist");
1109     doc.appendChild(prods);
1110     kDebug() << "////////////  PRO LIST BUILD PRDSLIST ";
1111     QTreeWidgetItemIterator it(m_listView);
1112     while (*it) {
1113         if ((*it)->type() != PROJECTCLIPTYPE) {
1114             // subitem
1115             ++it;
1116             continue;
1117         }
1118         prods.appendChild(doc.importNode(((ProjectItem *)(*it))->toXml(), true));
1119         ++it;
1120     }
1121     return prods;
1122 }
1123
1124 void ProjectList::slotCheckForEmptyQueue()
1125 {
1126     if (!m_refreshed && m_thumbnailQueue.isEmpty() && m_infoQueue.isEmpty()) {
1127         m_refreshed = true;
1128         emit loadingIsOver();
1129         emit displayMessage(QString(), -1);
1130         m_listView->blockSignals(false);
1131         m_listView->setEnabled(true);
1132         updateButtons();
1133     } else if (!m_refreshed) QTimer::singleShot(300, this, SLOT(slotCheckForEmptyQueue()));
1134 }
1135
1136 void ProjectList::reloadClipThumbnails()
1137 {
1138     kDebug() << "//////////////  RELOAD CLIPS THUMBNAILS!!!";
1139     m_thumbnailQueue.clear();
1140     QTreeWidgetItemIterator it(m_listView);
1141     while (*it) {
1142         if ((*it)->type() != PROJECTCLIPTYPE) {
1143             // subitem
1144             ++it;
1145             continue;
1146         }
1147         m_thumbnailQueue << ((ProjectItem *)(*it))->clipId();
1148         ++it;
1149     }
1150     QTimer::singleShot(300, this, SLOT(slotProcessNextThumbnail()));
1151 }
1152
1153 void ProjectList::requestClipThumbnail(const QString id)
1154 {
1155     if (!m_thumbnailQueue.contains(id)) m_thumbnailQueue.append(id);
1156 }
1157
1158 void ProjectList::slotProcessNextThumbnail()
1159 {
1160     if (m_thumbnailQueue.isEmpty() && m_infoQueue.isEmpty()) {
1161         slotCheckForEmptyQueue();
1162         return;
1163     }
1164     if (!m_infoQueue.isEmpty()) {
1165         //QTimer::singleShot(300, this, SLOT(slotProcessNextThumbnail()));
1166         return;
1167     }
1168     if (m_thumbnailQueue.count() > 1) {
1169         int max = m_doc->clipManager()->clipsCount();
1170         emit displayMessage(i18n("Loading thumbnails"), (int)(100 *(max - m_thumbnailQueue.count()) / max));
1171     }
1172     slotRefreshClipThumbnail(m_thumbnailQueue.takeFirst(), false);
1173 }
1174
1175 void ProjectList::slotRefreshClipThumbnail(const QString &clipId, bool update)
1176 {
1177     QTreeWidgetItem *item = getAnyItemById(clipId);
1178     if (item) slotRefreshClipThumbnail(item, update);
1179     else slotProcessNextThumbnail();
1180 }
1181
1182 void ProjectList::slotRefreshClipThumbnail(QTreeWidgetItem *it, bool update)
1183 {
1184     if (it == NULL) return;
1185     ProjectItem *item = NULL;
1186     bool isSubItem = false;
1187     int frame;
1188     if (it->type() == PROJECTFOLDERTYPE) return;
1189     if (it->type() == PROJECTSUBCLIPTYPE) {
1190         item = static_cast <ProjectItem *>(it->parent());
1191         frame = static_cast <SubProjectItem *>(it)->zone().x();
1192         isSubItem = true;
1193     } else {
1194         item = static_cast <ProjectItem *>(it);
1195         frame = item->referencedClip()->getClipThumbFrame();
1196     }
1197
1198     if (item) {
1199         DocClipBase *clip = item->referencedClip();
1200         if (!clip) {
1201             slotProcessNextThumbnail();
1202             return;
1203         }
1204         QPixmap pix;
1205         int height = m_listView->iconSize().height();
1206         int width = (int)(height  * m_render->dar());
1207         if (clip->clipType() == AUDIO) pix = KIcon("audio-x-generic").pixmap(QSize(width, height));
1208         else if (clip->clipType() == IMAGE) pix = QPixmap::fromImage(KThumb::getFrame(item->referencedClip()->producer(), 0, width, height));
1209         else pix = item->referencedClip()->thumbProducer()->extractImage(frame, width, height);
1210
1211         if (!pix.isNull()) {
1212             m_listView->blockSignals(true);
1213             it->setData(0, Qt::DecorationRole, pix);
1214             if (m_listView->isEnabled()) m_listView->blockSignals(false);
1215             if (!isSubItem) m_doc->cachePixmap(item->getClipHash(), pix);
1216             else m_doc->cachePixmap(item->getClipHash() + '#' + QString::number(frame), pix);
1217         }
1218         if (update) emit projectModified();
1219         QTimer::singleShot(30, this, SLOT(slotProcessNextThumbnail()));
1220     }
1221 }
1222
1223 void ProjectList::slotReplyGetFileProperties(const QString &clipId, Mlt::Producer *producer, const QMap < QString, QString > &properties, const QMap < QString, QString > &metadata, bool replace)
1224 {
1225     QString toReload;
1226     ProjectItem *item = getItemById(clipId);
1227     if (item && producer) {
1228         m_listView->blockSignals(true);
1229         item->setProperties(properties, metadata);
1230         if (item->referencedClip()->isPlaceHolder() && producer->is_valid()) {
1231             item->referencedClip()->setValid();
1232             item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | Qt::ItemIsEditable);
1233             toReload = clipId;
1234         }
1235         //Q_ASSERT_X(item->referencedClip(), "void ProjectList::slotReplyGetFileProperties", QString("Item with groupName %1 does not have a clip associated").arg(item->groupName()).toLatin1());
1236         item->referencedClip()->setProducer(producer, replace);
1237         item->referencedClip()->askForAudioThumbs();
1238         if (!replace && item->data(0, Qt::DecorationRole).isNull()) {
1239             requestClipThumbnail(clipId);
1240         }
1241         //emit receivedClipDuration(clipId);
1242         if (m_listView->isEnabled() && replace) {
1243             // update clip in clip monitor
1244             emit clipSelected(NULL);
1245             emit clipSelected(item->referencedClip());
1246         }
1247         /*else {
1248             // Check if duration changed.
1249             emit receivedClipDuration(clipId);
1250             delete producer;
1251         }*/
1252         if (m_listView->isEnabled()) m_listView->blockSignals(false);
1253         /*if (item->icon(0).isNull()) {
1254             requestClipThumbnail(clipId);
1255         }*/
1256     } else kDebug() << "////////  COULD NOT FIND CLIP TO UPDATE PRPS...";
1257     int max = m_doc->clipManager()->clipsCount();
1258     emit displayMessage(i18n("Loading clips"), (int)(100 *(max - m_infoQueue.count()) / max));
1259     // small delay so that the app can display the progress info
1260     if (item && m_infoQueue.isEmpty() && m_thumbnailQueue.isEmpty()) {
1261         m_listView->setCurrentItem(item);
1262         emit clipSelected(item->referencedClip());
1263     }
1264     if (!toReload.isEmpty()) emit clipNeedsReload(toReload, true);
1265     QTimer::singleShot(30, this, SLOT(slotProcessNextClipInQueue()));
1266 }
1267
1268 void ProjectList::slotReplyGetImage(const QString &clipId, const QPixmap &pix)
1269 {
1270     ProjectItem *item = getItemById(clipId);
1271     if (item && !pix.isNull()) {
1272         m_listView->blockSignals(true);
1273         item->setData(0, Qt::DecorationRole, pix);
1274         m_doc->cachePixmap(item->getClipHash(), pix);
1275         if (m_listView->isEnabled()) m_listView->blockSignals(false);
1276     }
1277 }
1278
1279 QTreeWidgetItem *ProjectList::getAnyItemById(const QString &id)
1280 {
1281     QTreeWidgetItemIterator it(m_listView);
1282     QString lookId = id;
1283     if (id.contains('#')) {
1284         lookId = id.section('#', 0, 0);
1285     }
1286
1287     ProjectItem *result = NULL;
1288     while (*it) {
1289         if ((*it)->type() != PROJECTCLIPTYPE) {
1290             // subitem
1291             ++it;
1292             continue;
1293         }
1294         ProjectItem *item = static_cast<ProjectItem *>(*it);
1295         if (item->clipId() == lookId) {
1296             result = item;
1297             break;
1298         }
1299         ++it;
1300     }
1301     if (result == NULL || !id.contains('#')) return result;
1302     else for (int i = 0; i < result->childCount(); i++) {
1303             SubProjectItem *sub = static_cast <SubProjectItem *>(result->child(i));
1304             if (sub && sub->zone().x() == id.section('#', 1, 1).toInt()) {
1305                 return sub;
1306             }
1307         }
1308
1309     return NULL;
1310 }
1311
1312
1313 ProjectItem *ProjectList::getItemById(const QString &id)
1314 {
1315     ProjectItem *item;
1316     QTreeWidgetItemIterator it(m_listView);
1317     while (*it) {
1318         if ((*it)->type() != PROJECTCLIPTYPE) {
1319             // subitem
1320             ++it;
1321             continue;
1322         }
1323         item = static_cast<ProjectItem *>(*it);
1324         if (item->clipId() == id)
1325             return item;
1326         ++it;
1327     }
1328     return NULL;
1329 }
1330
1331 FolderProjectItem *ProjectList::getFolderItemById(const QString &id)
1332 {
1333     FolderProjectItem *item;
1334     QTreeWidgetItemIterator it(m_listView);
1335     while (*it) {
1336         if ((*it)->type() == PROJECTFOLDERTYPE) {
1337             item = static_cast<FolderProjectItem *>(*it);
1338             if (item->clipId() == id) return item;
1339         }
1340         ++it;
1341     }
1342     return NULL;
1343 }
1344
1345 void ProjectList::slotSelectClip(const QString &ix)
1346 {
1347     ProjectItem *clip = getItemById(ix);
1348     if (clip) {
1349         m_listView->setCurrentItem(clip);
1350         m_listView->scrollToItem(clip);
1351         m_editAction->setEnabled(true);
1352         m_deleteAction->setEnabled(true);
1353         m_reloadAction->setEnabled(true);
1354         m_transcodeAction->setEnabled(true);
1355         if (clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) {
1356             m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
1357             m_openAction->setEnabled(true);
1358         } else if (clip->clipType() == AUDIO && !KdenliveSettings::defaultaudioapp().isEmpty()) {
1359             m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
1360             m_openAction->setEnabled(true);
1361         } else m_openAction->setEnabled(false);
1362     }
1363 }
1364
1365 QString ProjectList::currentClipUrl() const
1366 {
1367     ProjectItem *item;
1368     if (!m_listView->currentItem() || m_listView->currentItem()->type() == PROJECTFOLDERTYPE) return QString();
1369     if (m_listView->currentItem()->type() == PROJECTSUBCLIPTYPE) {
1370         // subitem
1371         item = static_cast <ProjectItem*>(m_listView->currentItem()->parent());
1372     } else item = static_cast <ProjectItem*>(m_listView->currentItem());
1373     if (item == NULL) return QString();
1374     return item->clipUrl().path();
1375 }
1376
1377 KUrl::List ProjectList::getConditionalUrls(const QString &condition) const
1378 {
1379     KUrl::List result;
1380     ProjectItem *item;
1381     QList<QTreeWidgetItem *> list = m_listView->selectedItems();
1382     for (int i = 0; i < list.count(); i++) {
1383         if (list.at(i)->type() == PROJECTFOLDERTYPE) continue;
1384         if (list.at(i)->type() == PROJECTSUBCLIPTYPE) {
1385             // subitem
1386             item = static_cast <ProjectItem*>(list.at(i)->parent());
1387         } else item = static_cast <ProjectItem*>(list.at(i));
1388         if (item == NULL) continue;
1389         if (item->type() == COLOR || item->type() == SLIDESHOW || item->type() == TEXT) continue;
1390         DocClipBase *clip = item->referencedClip();
1391         if (!condition.isEmpty()) {
1392             if (condition.startsWith("vcodec") && !clip->hasVideoCodec(condition.section("=", 1, 1))) continue;
1393             else if (condition.startsWith("acodec") && !clip->hasAudioCodec(condition.section("=", 1, 1))) continue;
1394         }
1395         result.append(item->clipUrl());
1396     }
1397     return result;
1398 }
1399
1400 void ProjectList::regenerateTemplate(const QString &id)
1401 {
1402     ProjectItem *clip = getItemById(id);
1403     if (clip) regenerateTemplate(clip);
1404 }
1405
1406 void ProjectList::regenerateTemplate(ProjectItem *clip)
1407 {
1408     //TODO: remove this unused method, only force_reload is necessary
1409     clip->referencedClip()->producer()->set("force_reload", 1);
1410 }
1411
1412 QDomDocument ProjectList::generateTemplateXml(QString path, const QString &replaceString)
1413 {
1414     QDomDocument doc;
1415     QFile file(path);
1416     if (!file.open(QIODevice::ReadOnly)) {
1417         kWarning() << "ERROR, CANNOT READ: " << path;
1418         return doc;
1419     }
1420     if (!doc.setContent(&file)) {
1421         kWarning() << "ERROR, CANNOT READ: " << path;
1422         file.close();
1423         return doc;
1424     }
1425     file.close();
1426     QDomNodeList texts = doc.elementsByTagName("content");
1427     for (int i = 0; i < texts.count(); i++) {
1428         QString data = texts.item(i).firstChild().nodeValue();
1429         data.replace("%s", replaceString);
1430         texts.item(i).firstChild().setNodeValue(data);
1431     }
1432     return doc;
1433 }
1434
1435
1436 void ProjectList::slotAddClipCut(const QString &id, int in, int out)
1437 {
1438     ProjectItem *clip = getItemById(id);
1439     if (clip == NULL) return;
1440     if (clip->referencedClip()->hasCutZone(QPoint(in, out))) return;
1441     AddClipCutCommand *command = new AddClipCutCommand(this, id, in, out, QString(), true, false);
1442     m_commandStack->push(command);
1443 }
1444
1445 void ProjectList::addClipCut(const QString &id, int in, int out, const QString desc, bool newItem)
1446 {
1447     ProjectItem *clip = getItemById(id);
1448     if (clip) {
1449         DocClipBase *base = clip->referencedClip();
1450         base->addCutZone(in, out);
1451         m_listView->blockSignals(true);
1452         SubProjectItem *sub = new SubProjectItem(clip, in, out, desc);
1453         if (newItem && desc.isEmpty() && !m_listView->isColumnHidden(1)) {
1454             if (!clip->isExpanded()) clip->setExpanded(true);
1455             m_listView->editItem(sub, 1);
1456         }
1457         QPixmap p = clip->referencedClip()->thumbProducer()->extractImage(in, (int)(sub->sizeHint(0).height()  * m_render->dar()), sub->sizeHint(0).height() - 2);
1458         sub->setData(0, Qt::DecorationRole, p);
1459         m_doc->cachePixmap(clip->getClipHash() + '#' + QString::number(in), p);
1460         m_listView->blockSignals(false);
1461     }
1462     emit projectModified();
1463 }
1464
1465 void ProjectList::removeClipCut(const QString &id, int in, int out)
1466 {
1467     ProjectItem *clip = getItemById(id);
1468     if (clip) {
1469         DocClipBase *base = clip->referencedClip();
1470         base->removeCutZone(in, out);
1471         SubProjectItem *sub = getSubItem(clip, QPoint(in, out));
1472         if (sub) {
1473             m_listView->blockSignals(true);
1474             delete sub;
1475             m_listView->blockSignals(false);
1476         }
1477     }
1478     emit projectModified();
1479 }
1480
1481 SubProjectItem *ProjectList::getSubItem(ProjectItem *clip, QPoint zone)
1482 {
1483     SubProjectItem *sub = NULL;
1484     if (clip) {
1485         for (int i = 0; i < clip->childCount(); i++) {
1486             QTreeWidgetItem *it = clip->child(i);
1487             if (it->type() == PROJECTSUBCLIPTYPE) {
1488                 sub = static_cast <SubProjectItem*>(it);
1489                 if (sub->zone() == zone) break;
1490                 else sub = NULL;
1491             }
1492         }
1493     }
1494     return sub;
1495 }
1496
1497 void ProjectList::slotUpdateClipCut(QPoint p)
1498 {
1499     if (!m_listView->currentItem() || m_listView->currentItem()->type() != PROJECTSUBCLIPTYPE) return;
1500     SubProjectItem *sub = static_cast <SubProjectItem*>(m_listView->currentItem());
1501     ProjectItem *item = static_cast <ProjectItem *>(sub->parent());
1502     EditClipCutCommand *command = new EditClipCutCommand(this, item->clipId(), sub->zone(), p, sub->text(1), sub->text(1), true);
1503     m_commandStack->push(command);
1504 }
1505
1506 void ProjectList::doUpdateClipCut(const QString &id, const QPoint oldzone, const QPoint zone, const QString &comment)
1507 {
1508     ProjectItem *clip = getItemById(id);
1509     SubProjectItem *sub = getSubItem(clip, oldzone);
1510     if (sub == NULL || clip == NULL) return;
1511     DocClipBase *base = clip->referencedClip();
1512     base->updateCutZone(oldzone.x(), oldzone.y(), zone.x(), zone.y(), comment);
1513     m_listView->blockSignals(true);
1514     sub->setZone(zone);
1515     sub->setDescription(comment);
1516     m_listView->blockSignals(false);
1517     emit projectModified();
1518 }
1519
1520 #include "projectlist.moc"