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