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