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