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