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