]> git.sesse.net Git - kdenlive/blob - src/projectlist.cpp
Fix timeline thumbs not reloaded on clip change:
[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 "profilesdialog.h"
36 #include "editclipcommand.h"
37 #include "editclipcutcommand.h"
38 #include "editfoldercommand.h"
39 #include "addclipcutcommand.h"
40
41 #include "ui_templateclip_ui.h"
42
43 #include <KDebug>
44 #include <KAction>
45 #include <KLocale>
46 #include <KFileDialog>
47 #include <KInputDialog>
48 #include <KMessageBox>
49 #include <KIO/NetAccess>
50 #include <KFileItem>
51 #include <KApplication>
52 #ifdef NEPOMUK
53 #include <nepomuk/global.h>
54 #include <nepomuk/resourcemanager.h>
55 //#include <nepomuk/tag.h>
56 #endif
57
58 #include <QMouseEvent>
59 #include <QStylePainter>
60 #include <QPixmap>
61 #include <QIcon>
62 #include <QMenu>
63 #include <QProcess>
64 #include <QHeaderView>
65 #include <QInputDialog>
66
67 ProjectList::ProjectList(QWidget *parent) :
68     QWidget(parent),
69     m_render(NULL),
70     m_fps(-1),
71     m_commandStack(NULL),
72     m_openAction(NULL),
73     m_reloadAction(NULL),
74     m_transcodeAction(NULL),
75     m_doc(NULL),
76     m_refreshed(false),
77     m_infoQueue(),
78     m_thumbnailQueue()
79 {
80     QVBoxLayout *layout = new QVBoxLayout;
81     layout->setContentsMargins(0, 0, 0, 0);
82     layout->setSpacing(0);
83
84     // setup toolbar
85     QFrame *frame = new QFrame;
86     frame->setFrameStyle(QFrame::NoFrame);
87     QHBoxLayout *box = new QHBoxLayout;
88     KTreeWidgetSearchLine *searchView = new KTreeWidgetSearchLine;
89
90     box->addWidget(searchView);
91     //int s = style()->pixelMetric(QStyle::PM_SmallIconSize);
92     //m_toolbar->setIconSize(QSize(s, s));
93
94     m_addButton = new QToolButton;
95     m_addButton->setPopupMode(QToolButton::MenuButtonPopup);
96     m_addButton->setAutoRaise(true);
97     box->addWidget(m_addButton);
98
99     m_editButton = new QToolButton;
100     m_editButton->setAutoRaise(true);
101     box->addWidget(m_editButton);
102
103     m_deleteButton = new QToolButton;
104     m_deleteButton->setAutoRaise(true);
105     box->addWidget(m_deleteButton);
106     frame->setLayout(box);
107     layout->addWidget(frame);
108
109     m_listView = new ProjectListView;
110     layout->addWidget(m_listView);
111     setLayout(layout);
112     searchView->setTreeWidget(m_listView);
113
114     m_proxyAction = new QAction(i18n("Proxy clip"), this);
115     m_proxyAction->setCheckable(true);
116     m_proxyAction->setChecked(false);
117     connect(m_proxyAction, SIGNAL(toggled(bool)), this, SLOT(slotProxyCurrentItem(bool)));
118     
119     
120     m_queueTimer.setInterval(100);
121     connect(&m_queueTimer, SIGNAL(timeout()), this, SLOT(slotProcessNextClipInQueue()));
122     m_queueTimer.setSingleShot(true);
123
124
125     connect(m_listView, SIGNAL(projectModified()), this, SIGNAL(projectModified()));
126     connect(m_listView, SIGNAL(itemSelectionChanged()), this, SLOT(slotClipSelected()));
127     connect(m_listView, SIGNAL(focusMonitor()), this, SLOT(slotClipSelected()));
128     connect(m_listView, SIGNAL(pauseMonitor()), this, SLOT(slotPauseMonitor()));
129     connect(m_listView, SIGNAL(requestMenu(const QPoint &, QTreeWidgetItem *)), this, SLOT(slotContextMenu(const QPoint &, QTreeWidgetItem *)));
130     connect(m_listView, SIGNAL(addClip()), this, SLOT(slotAddClip()));
131     connect(m_listView, SIGNAL(addClip(const QList <QUrl>, const QString &, const QString &)), this, SLOT(slotAddClip(const QList <QUrl>, const QString &, const QString &)));
132     connect(m_listView, SIGNAL(addClipCut(const QString &, int, int)), this, SLOT(slotAddClipCut(const QString &, int, int)));
133     connect(m_listView, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this, SLOT(slotItemEdited(QTreeWidgetItem *, int)));
134     connect(m_listView, SIGNAL(showProperties(DocClipBase *)), this, SIGNAL(showClipProperties(DocClipBase *)));
135
136     m_listViewDelegate = new ItemDelegate(m_listView);
137     m_listView->setItemDelegate(m_listViewDelegate);
138 #ifdef NEPOMUK
139     if (KdenliveSettings::activate_nepomuk()) {
140         Nepomuk::ResourceManager::instance()->init();
141         if (!Nepomuk::ResourceManager::instance()->initialized()) {
142             kDebug() << "Cannot communicate with Nepomuk, DISABLING it";
143             KdenliveSettings::setActivate_nepomuk(false);
144         }
145     }
146 #endif
147 }
148
149 ProjectList::~ProjectList()
150 {
151     delete m_menu;
152     m_listView->blockSignals(true);
153     m_listView->clear();
154     delete m_listViewDelegate;
155 }
156
157 void ProjectList::focusTree() const
158 {
159     m_listView->setFocus();
160 }
161
162 void ProjectList::setupMenu(QMenu *addMenu, QAction *defaultAction)
163 {
164     QList <QAction *> actions = addMenu->actions();
165     for (int i = 0; i < actions.count(); i++) {
166         if (actions.at(i)->data().toString() == "clip_properties") {
167             m_editButton->setDefaultAction(actions.at(i));
168             actions.removeAt(i);
169             i--;
170         } else if (actions.at(i)->data().toString() == "delete_clip") {
171             m_deleteButton->setDefaultAction(actions.at(i));
172             actions.removeAt(i);
173             i--;
174         } else if (actions.at(i)->data().toString() == "edit_clip") {
175             m_openAction = actions.at(i);
176             actions.removeAt(i);
177             i--;
178         } else if (actions.at(i)->data().toString() == "reload_clip") {
179             m_reloadAction = actions.at(i);
180             actions.removeAt(i);
181             i--;
182         }
183     }
184
185     QMenu *m = new QMenu();
186     m->addActions(actions);
187     m_addButton->setMenu(m);
188     m_addButton->setDefaultAction(defaultAction);
189     m_menu = new QMenu();
190     m_menu->addActions(addMenu->actions());
191 }
192
193 void ProjectList::setupGeneratorMenu(QMenu *addMenu, QMenu *transcodeMenu, QMenu *inTimelineMenu)
194 {
195     if (!addMenu)
196         return;
197     QMenu *menu = m_addButton->menu();
198     menu->addMenu(addMenu);
199     m_addButton->setMenu(menu);
200
201     m_menu->addMenu(addMenu);
202     if (addMenu->isEmpty())
203         addMenu->setEnabled(false);
204     m_menu->addMenu(transcodeMenu);
205     if (transcodeMenu->isEmpty())
206         transcodeMenu->setEnabled(false);
207     m_transcodeAction = transcodeMenu;
208     m_menu->addAction(m_reloadAction);
209     m_menu->addAction(m_proxyAction);
210     m_menu->addMenu(inTimelineMenu);
211     inTimelineMenu->setEnabled(false);
212     m_menu->addAction(m_editButton->defaultAction());
213     m_menu->addAction(m_openAction);
214     m_menu->addAction(m_deleteButton->defaultAction());
215     m_menu->insertSeparator(m_deleteButton->defaultAction());
216 }
217
218
219 QByteArray ProjectList::headerInfo() const
220 {
221     return m_listView->header()->saveState();
222 }
223
224 void ProjectList::setHeaderInfo(const QByteArray &state)
225 {
226     m_listView->header()->restoreState(state);
227 }
228
229 void ProjectList::updateProjectFormat(Timecode t)
230 {
231     m_timecode = t;
232 }
233
234 void ProjectList::slotEditClip()
235 {
236     QList<QTreeWidgetItem *> list = m_listView->selectedItems();
237     if (list.count() > 1) {
238         editClipSelection(list);
239         return;
240     }
241     ProjectItem *item;
242     if (!m_listView->currentItem() || m_listView->currentItem()->type() == PROJECTFOLDERTYPE)
243         return;
244     if (m_listView->currentItem()->type() == PROJECTSUBCLIPTYPE)
245         item = static_cast <ProjectItem*>(m_listView->currentItem()->parent());
246     else
247         item = static_cast <ProjectItem*>(m_listView->currentItem());
248     if (item && (item->flags() & Qt::ItemIsDragEnabled)) {
249         emit clipSelected(item->referencedClip());
250         emit showClipProperties(item->referencedClip());
251     }
252 }
253
254 void ProjectList::editClipSelection(QList<QTreeWidgetItem *> list)
255 {
256     // Gather all common properties
257     QMap <QString, QString> commonproperties;
258     QList <DocClipBase *> clipList;
259     commonproperties.insert("force_aspect_num", "-");
260     commonproperties.insert("force_aspect_den", "-");
261     commonproperties.insert("force_fps", "-");
262     commonproperties.insert("force_progressive", "-");
263     commonproperties.insert("force_tff", "-");
264     commonproperties.insert("threads", "-");
265     commonproperties.insert("video_index", "-");
266     commonproperties.insert("audio_index", "-");
267     commonproperties.insert("force_colorspace", "-");
268     commonproperties.insert("full_luma", "-");
269
270     bool allowDurationChange = true;
271     int commonDuration = -1;
272     ProjectItem *item;
273     for (int i = 0; i < list.count(); i++) {
274         item = NULL;
275         if (list.at(i)->type() == PROJECTFOLDERTYPE)
276             continue;
277         if (list.at(i)->type() == PROJECTSUBCLIPTYPE)
278             item = static_cast <ProjectItem*>(list.at(i)->parent());
279         else
280             item = static_cast <ProjectItem*>(list.at(i));
281         if (!(item->flags() & Qt::ItemIsDragEnabled))
282             continue;
283         if (item) {
284             // check properties
285             DocClipBase *clip = item->referencedClip();
286             if (clipList.contains(clip)) continue;
287             if (clip->clipType() != COLOR && clip->clipType() != IMAGE && clip->clipType() != TEXT)
288                 allowDurationChange = false;
289             if (allowDurationChange && commonDuration != 0) {
290                 if (commonDuration == -1)
291                     commonDuration = clip->duration().frames(m_fps);
292                 else if (commonDuration != clip->duration().frames(m_fps))
293                     commonDuration = 0;
294             }
295             clipList.append(clip);
296             QMap <QString, QString> clipprops = clip->properties();
297             QMapIterator<QString, QString> p(commonproperties);
298             while (p.hasNext()) {
299                 p.next();
300                 if (p.value().isEmpty()) continue;
301                 if (clipprops.contains(p.key())) {
302                     if (p.value() == "-")
303                         commonproperties.insert(p.key(), clipprops.value(p.key()));
304                     else if (p.value() != clipprops.value(p.key()))
305                         commonproperties.insert(p.key(), QString());
306                 } else {
307                     commonproperties.insert(p.key(), QString());
308                 }
309             }
310         }
311     }
312     if (allowDurationChange)
313         commonproperties.insert("out", QString::number(commonDuration));
314     QMapIterator<QString, QString> p(commonproperties);
315     while (p.hasNext()) {
316         p.next();
317         kDebug() << "Result: " << p.key() << " = " << p.value();
318     }
319     emit showClipProperties(clipList, commonproperties);
320 }
321
322 void ProjectList::slotOpenClip()
323 {
324     ProjectItem *item;
325     if (!m_listView->currentItem() || m_listView->currentItem()->type() == PROJECTFOLDERTYPE)
326         return;
327     if (m_listView->currentItem()->type() == QTreeWidgetItem::UserType + 1)
328         item = static_cast <ProjectItem*>(m_listView->currentItem()->parent());
329     else
330         item = static_cast <ProjectItem*>(m_listView->currentItem());
331     if (item) {
332         if (item->clipType() == IMAGE) {
333             if (KdenliveSettings::defaultimageapp().isEmpty())
334                 KMessageBox::sorry(kapp->activeWindow(), i18n("Please set a default application to open images in the Settings dialog"));
335             else
336                 QProcess::startDetached(KdenliveSettings::defaultimageapp(), QStringList() << item->clipUrl().path());
337         }
338         if (item->clipType() == AUDIO) {
339             if (KdenliveSettings::defaultaudioapp().isEmpty())
340                 KMessageBox::sorry(kapp->activeWindow(), i18n("Please set a default application to open audio files in the Settings dialog"));
341             else
342                 QProcess::startDetached(KdenliveSettings::defaultaudioapp(), QStringList() << item->clipUrl().path());
343         }
344     }
345 }
346
347 void ProjectList::cleanup()
348 {
349     m_listView->clearSelection();
350     QTreeWidgetItemIterator it(m_listView);
351     ProjectItem *item;
352     while (*it) {
353         if ((*it)->type() != PROJECTCLIPTYPE) {
354             it++;
355             continue;
356         }
357         item = static_cast <ProjectItem *>(*it);
358         if (item->numReferences() == 0)
359             item->setSelected(true);
360         it++;
361     }
362     slotRemoveClip();
363 }
364
365 void ProjectList::trashUnusedClips()
366 {
367     QTreeWidgetItemIterator it(m_listView);
368     ProjectItem *item;
369     QStringList ids;
370     QStringList urls;
371     while (*it) {
372         if ((*it)->type() != PROJECTCLIPTYPE) {
373             it++;
374             continue;
375         }
376         item = static_cast <ProjectItem *>(*it);
377         if (item->numReferences() == 0) {
378             ids << item->clipId();
379             KUrl url = item->clipUrl();
380             if (!url.isEmpty() && !urls.contains(url.path()))
381                 urls << url.path();
382         }
383         it++;
384     }
385
386     // Check that we don't use the URL in another clip
387     QTreeWidgetItemIterator it2(m_listView);
388     while (*it2) {
389         if ((*it2)->type() != PROJECTCLIPTYPE) {
390             it2++;
391             continue;
392         }
393         item = static_cast <ProjectItem *>(*it2);
394         if (item->numReferences() > 0) {
395             KUrl url = item->clipUrl();
396             if (!url.isEmpty() && urls.contains(url.path())) urls.removeAll(url.path());
397         }
398         it2++;
399     }
400
401     emit deleteProjectClips(ids, QMap <QString, QString>());
402     for (int i = 0; i < urls.count(); i++)
403         KIO::NetAccess::del(KUrl(urls.at(i)), this);
404 }
405
406 void ProjectList::slotReloadClip(const QString &id)
407 {
408     QList<QTreeWidgetItem *> selected;
409     if (id.isEmpty())
410         selected = m_listView->selectedItems();
411     else {
412         ProjectItem *itemToReLoad = getItemById(id);
413         if (itemToReLoad) selected.append(itemToReLoad);
414     }
415     ProjectItem *item;
416     for (int i = 0; i < selected.count(); i++) {
417         if (selected.at(i)->type() != PROJECTCLIPTYPE) {
418             if (selected.at(i)->type() == PROJECTFOLDERTYPE) {
419                 for (int j = 0; j < selected.at(i)->childCount(); j++)
420                     selected.append(selected.at(i)->child(j));
421             }
422             continue;
423         }
424         item = static_cast <ProjectItem *>(selected.at(i));
425         if (item) {
426             CLIPTYPE t = item->clipType();
427             if (t == TEXT) {
428                 if (!item->referencedClip()->getProperty("xmltemplate").isEmpty())
429                     regenerateTemplate(item);
430             } else if (t != COLOR && t != SLIDESHOW && item->referencedClip() &&  item->referencedClip()->checkHash() == false) {
431                 item->referencedClip()->setPlaceHolder(true);
432                 item->setProperty("file_hash", QString());
433             } else if (t == IMAGE) {
434                 item->referencedClip()->producer()->set("force_reload", 1);
435             }
436
437             QDomElement e = item->toXml();
438             // Make sure we get the correct producer length if it was adjusted in timeline
439             if (t == COLOR || t == IMAGE || t == SLIDESHOW || t == TEXT) {
440                 int length = QString(item->referencedClip()->producerProperty("length")).toInt();
441                 if (length > 0 && !e.hasAttribute("length")) {
442                     e.setAttribute("length", length);
443                     e.setAttribute("out", length - 1);
444                 }
445             }
446             
447             emit getFileProperties(e, item->clipId(), m_listView->iconSize().height(), true);
448         }
449     }
450 }
451
452 void ProjectList::slotModifiedClip(const QString &id)
453 {
454     ProjectItem *item = getItemById(id);
455     if (item) {
456         QPixmap pixmap = qVariantValue<QPixmap>(item->data(0, Qt::DecorationRole));
457         if (!pixmap.isNull()) {
458             QPainter p(&pixmap);
459             p.fillRect(0, 0, pixmap.width(), pixmap.height(), QColor(255, 255, 255, 200));
460             p.drawPixmap(0, 0, KIcon("view-refresh").pixmap(m_listView->iconSize()));
461             p.end();
462         } else {
463             pixmap = KIcon("view-refresh").pixmap(m_listView->iconSize());
464         }
465         item->setData(0, Qt::DecorationRole, pixmap);
466     }
467 }
468
469 void ProjectList::slotMissingClip(const QString &id)
470 {
471     ProjectItem *item = getItemById(id);
472     if (item) {
473         item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsDropEnabled);
474         if (item->referencedClip()) {
475             item->referencedClip()->setPlaceHolder(true);
476             if (m_render == NULL) kDebug() << "*********  ERROR, NULL RENDR";
477             item->referencedClip()->setProducer(m_render->invalidProducer(id), true);
478             item->slotSetToolTip();
479             emit clipNeedsReload(id, true);
480         }
481     }
482     update();
483     emit displayMessage(i18n("Check missing clips"), -2);
484     emit updateRenderStatus();
485 }
486
487 void ProjectList::slotAvailableClip(const QString &id)
488 {
489     ProjectItem *item = getItemById(id);
490     if (item == NULL)
491         return;
492     item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsDropEnabled);
493     if (item->referencedClip()) { // && item->referencedClip()->checkHash() == false) {
494         item->setProperty("file_hash", QString());
495         slotReloadClip(id);
496     }
497     /*else {
498     item->referencedClip()->setValid();
499     item->slotSetToolTip();
500     }
501     update();*/
502     emit updateRenderStatus();
503 }
504
505 bool ProjectList::hasMissingClips()
506 {
507     bool missing = false;
508     QTreeWidgetItemIterator it(m_listView);
509     while (*it) {
510         if ((*it)->type() == PROJECTCLIPTYPE && !((*it)->flags() & Qt::ItemIsDragEnabled)) {
511             missing = true;
512             break;
513         }
514         it++;
515     }
516     return missing;
517 }
518
519 void ProjectList::setRenderer(Render *projectRender)
520 {
521     m_render = projectRender;
522     m_listView->setIconSize(QSize((ProjectItem::itemDefaultHeight() - 2) * m_render->dar(), ProjectItem::itemDefaultHeight() - 2));
523 }
524
525 void ProjectList::slotClipSelected()
526 {
527     if (!m_listView->isEnabled()) return;
528     if (m_listView->currentItem()) {
529         if (m_listView->currentItem()->type() == PROJECTFOLDERTYPE) {
530             emit clipSelected(NULL);
531             m_editButton->defaultAction()->setEnabled(false);
532             m_deleteButton->defaultAction()->setEnabled(true);
533             m_openAction->setEnabled(false);
534             m_reloadAction->setEnabled(false);
535             m_transcodeAction->setEnabled(false);
536             m_proxyAction->setEnabled(false);
537         } else {
538             ProjectItem *clip;
539             if (m_listView->currentItem()->type() == PROJECTSUBCLIPTYPE) {
540                 // this is a sub item, use base clip
541                 m_deleteButton->defaultAction()->setEnabled(true);
542                 clip = static_cast <ProjectItem*>(m_listView->currentItem()->parent());
543                 if (clip == NULL) kDebug() << "-----------ERROR";
544                 SubProjectItem *sub = static_cast <SubProjectItem*>(m_listView->currentItem());
545                 emit clipSelected(clip->referencedClip(), sub->zone());
546                 m_transcodeAction->setEnabled(false);
547                 return;
548             }
549             clip = static_cast <ProjectItem*>(m_listView->currentItem());
550             if (clip)
551                 emit clipSelected(clip->referencedClip());
552             m_editButton->defaultAction()->setEnabled(true);
553             m_deleteButton->defaultAction()->setEnabled(true);
554             m_reloadAction->setEnabled(true);
555             m_transcodeAction->setEnabled(true);
556             if (clip && clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) {
557                 m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
558                 m_openAction->setEnabled(true);
559             } else if (clip && clip->clipType() == AUDIO && !KdenliveSettings::defaultaudioapp().isEmpty()) {
560                 m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
561                 m_openAction->setEnabled(true);
562             } else {
563                 m_openAction->setEnabled(false);
564             }
565             // Display relevant transcoding actions only
566             adjustTranscodeActions(clip);
567             // Display uses in timeline
568             emit findInTimeline(clip->clipId());
569         }
570     } else {
571         emit clipSelected(NULL);
572         m_editButton->defaultAction()->setEnabled(false);
573         m_deleteButton->defaultAction()->setEnabled(false);
574         m_openAction->setEnabled(false);
575         m_reloadAction->setEnabled(false);
576         m_transcodeAction->setEnabled(false);
577     }
578 }
579
580 void ProjectList::adjustProxyActions(ProjectItem *clip) const
581 {
582     if (clip == NULL || clip->type() != PROJECTCLIPTYPE || clip->clipType() == COLOR || clip->clipType() == TEXT || clip->clipType() == PLAYLIST || clip->clipType() == SLIDESHOW || clip->clipType() == AUDIO) {
583         m_proxyAction->setEnabled(false);
584         return;
585     }
586     m_proxyAction->setEnabled(true);
587     m_proxyAction->setChecked(clip->hasProxy());
588 }
589
590 void ProjectList::adjustTranscodeActions(ProjectItem *clip) const
591 {
592     if (clip == NULL || clip->type() != PROJECTCLIPTYPE || clip->clipType() == COLOR || clip->clipType() == TEXT || clip->clipType() == PLAYLIST || clip->clipType() == SLIDESHOW) {
593         m_transcodeAction->setEnabled(false);
594         return;
595     }
596     m_transcodeAction->setEnabled(true);
597     QList<QAction *> transcodeActions = m_transcodeAction->actions();
598     QStringList data;
599     QString condition;
600     for (int i = 0; i < transcodeActions.count(); i++) {
601         data = transcodeActions.at(i)->data().toStringList();
602         if (data.count() > 2) {
603             condition = data.at(2);
604             if (condition.startsWith("vcodec"))
605                 transcodeActions.at(i)->setEnabled(clip->referencedClip()->hasVideoCodec(condition.section('=', 1, 1)));
606             else if (condition.startsWith("acodec"))
607                 transcodeActions.at(i)->setEnabled(clip->referencedClip()->hasVideoCodec(condition.section('=', 1, 1)));
608         }
609     }
610
611 }
612
613 void ProjectList::slotPauseMonitor()
614 {
615     if (m_render)
616         m_render->pause();
617 }
618
619 void ProjectList::slotUpdateClipProperties(const QString &id, QMap <QString, QString> properties)
620 {
621     ProjectItem *item = getItemById(id);
622     if (item) {
623         slotUpdateClipProperties(item, properties);
624         if (properties.contains("out") || properties.contains("force_fps") || properties.contains("resource")) {
625             slotReloadClip(id);
626         } else if (properties.contains("colour") ||
627                    properties.contains("xmldata") ||
628                    properties.contains("force_aspect_num") ||
629                    properties.contains("force_aspect_den") ||
630                    properties.contains("templatetext")) {
631             slotRefreshClipThumbnail(item);
632             emit refreshClip(id);
633         } else if (properties.contains("full_luma") || properties.contains("force_colorspace")) {
634             emit refreshClip(id);
635         }
636     }
637 }
638
639 void ProjectList::slotUpdateClipProperties(ProjectItem *clip, QMap <QString, QString> properties)
640 {
641     if (!clip)
642         return;
643     clip->setProperties(properties);
644     if (properties.contains("name")) {
645         m_listView->blockSignals(true);
646         clip->setText(0, properties.value("name"));
647         m_listView->blockSignals(false);
648         emit clipNameChanged(clip->clipId(), properties.value("name"));
649     }
650     if (properties.contains("description")) {
651         CLIPTYPE type = clip->clipType();
652         m_listView->blockSignals(true);
653         clip->setText(1, properties.value("description"));
654         m_listView->blockSignals(false);
655 #ifdef NEPOMUK
656         if (KdenliveSettings::activate_nepomuk() && (type == AUDIO || type == VIDEO || type == AV || type == IMAGE || type == PLAYLIST)) {
657             // Use Nepomuk system to store clip description
658             Nepomuk::Resource f(clip->clipUrl().path());
659             f.setDescription(properties.value("description"));
660         }
661 #endif
662         emit projectModified();
663     }
664 }
665
666 void ProjectList::slotItemEdited(QTreeWidgetItem *item, int column)
667 {
668     if (item->type() == PROJECTSUBCLIPTYPE) {
669         // this is a sub-item
670         if (column == 1) {
671             // user edited description
672             SubProjectItem *sub = static_cast <SubProjectItem*>(item);
673             ProjectItem *item = static_cast <ProjectItem *>(sub->parent());
674             EditClipCutCommand *command = new EditClipCutCommand(this, item->clipId(), sub->zone(), sub->zone(), sub->description(), sub->text(1), true);
675             m_commandStack->push(command);
676             //slotUpdateCutClipProperties(sub->clipId(), sub->zone(), sub->text(1), sub->text(1));
677         }
678         return;
679     }
680     if (item->type() == PROJECTFOLDERTYPE) {
681         if (column == 0) {
682             FolderProjectItem *folder = static_cast <FolderProjectItem*>(item);
683             editFolder(item->text(0), folder->groupName(), folder->clipId());
684             folder->setGroupName(item->text(0));
685             m_doc->clipManager()->addFolder(folder->clipId(), item->text(0));
686             const int children = item->childCount();
687             for (int i = 0; i < children; i++) {
688                 ProjectItem *child = static_cast <ProjectItem *>(item->child(i));
689                 child->setProperty("groupname", item->text(0));
690             }
691         }
692         return;
693     }
694
695     ProjectItem *clip = static_cast <ProjectItem*>(item);
696     if (column == 1) {
697         if (clip->referencedClip()) {
698             QMap <QString, QString> oldprops;
699             QMap <QString, QString> newprops;
700             oldprops["description"] = clip->referencedClip()->getProperty("description");
701             newprops["description"] = item->text(1);
702
703             if (clip->clipType() == TEXT) {
704                 // This is a text template clip, update the image
705                 /*oldprops.insert("xmldata", clip->referencedClip()->getProperty("xmldata"));
706                 newprops.insert("xmldata", generateTemplateXml(clip->referencedClip()->getProperty("xmltemplate"), item->text(2)).toString());*/
707                 oldprops.insert("templatetext", clip->referencedClip()->getProperty("templatetext"));
708                 newprops.insert("templatetext", item->text(1));
709             }
710             slotUpdateClipProperties(clip->clipId(), newprops);
711             EditClipCommand *command = new EditClipCommand(this, clip->clipId(), oldprops, newprops, false);
712             m_commandStack->push(command);
713         }
714     } else if (column == 0) {
715         if (clip->referencedClip()) {
716             QMap <QString, QString> oldprops;
717             QMap <QString, QString> newprops;
718             oldprops["name"] = clip->referencedClip()->getProperty("name");
719             newprops["name"] = item->text(0);
720             slotUpdateClipProperties(clip, newprops);
721             emit projectModified();
722             EditClipCommand *command = new EditClipCommand(this, clip->clipId(), oldprops, newprops, false);
723             m_commandStack->push(command);
724         }
725     }
726 }
727
728 void ProjectList::slotContextMenu(const QPoint &pos, QTreeWidgetItem *item)
729 {
730     bool enable = item ? true : false;
731     m_editButton->defaultAction()->setEnabled(enable);
732     m_deleteButton->defaultAction()->setEnabled(enable);
733     m_reloadAction->setEnabled(enable);
734     m_transcodeAction->setEnabled(enable);
735     if (enable) {
736         ProjectItem *clip = NULL;
737         if (m_listView->currentItem()->type() == PROJECTSUBCLIPTYPE) {
738             clip = static_cast <ProjectItem*>(item->parent());
739             m_transcodeAction->setEnabled(false);
740         } else if (m_listView->currentItem()->type() == PROJECTCLIPTYPE) {
741             clip = static_cast <ProjectItem*>(item);
742             // Display relevant transcoding actions only
743             adjustTranscodeActions(clip);
744             adjustProxyActions(clip);
745             // Display uses in timeline
746             emit findInTimeline(clip->clipId());
747         } else {
748             m_transcodeAction->setEnabled(false);
749         }
750         if (clip && clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) {
751             m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
752             m_openAction->setEnabled(true);
753         } else if (clip && clip->clipType() == AUDIO && !KdenliveSettings::defaultaudioapp().isEmpty()) {
754             m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
755             m_openAction->setEnabled(true);
756         } else {
757             m_openAction->setEnabled(false);
758         }
759
760     } else {
761         m_openAction->setEnabled(false);
762     }
763     m_menu->popup(pos);
764 }
765
766 void ProjectList::slotRemoveClip()
767 {
768     if (!m_listView->currentItem())
769         return;
770     QStringList ids;
771     QMap <QString, QString> folderids;
772     QList<QTreeWidgetItem *> selected = m_listView->selectedItems();
773
774     QUndoCommand *delCommand = new QUndoCommand();
775     delCommand->setText(i18n("Delete Clip Zone"));
776     for (int i = 0; i < selected.count(); i++) {
777         if (selected.at(i)->type() == PROJECTSUBCLIPTYPE) {
778             // subitem
779             SubProjectItem *sub = static_cast <SubProjectItem *>(selected.at(i));
780             ProjectItem *item = static_cast <ProjectItem *>(sub->parent());
781             new AddClipCutCommand(this, item->clipId(), sub->zone().x(), sub->zone().y(), sub->description(), false, true, delCommand);
782         } else if (selected.at(i)->type() == PROJECTFOLDERTYPE) {
783             // folder
784             FolderProjectItem *folder = static_cast <FolderProjectItem *>(selected.at(i));
785             folderids[folder->groupName()] = folder->clipId();
786             int children = folder->childCount();
787
788             if (children > 0 && KMessageBox::questionYesNo(kapp->activeWindow(), 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)
789                 return;
790             for (int i = 0; i < children; ++i) {
791                 ProjectItem *child = static_cast <ProjectItem *>(folder->child(i));
792                 ids << child->clipId();
793             }
794         } else {
795             ProjectItem *item = static_cast <ProjectItem *>(selected.at(i));
796             ids << item->clipId();
797             if (item->numReferences() > 0 && KMessageBox::questionYesNo(kapp->activeWindow(), 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"), KStandardGuiItem::yes(), KStandardGuiItem::no(), "DeleteAll") == KMessageBox::No) {
798                 KMessageBox::enableMessage("DeleteAll");
799                 return;
800             }
801         }
802     }
803     KMessageBox::enableMessage("DeleteAll");
804     if (delCommand->childCount() == 0)
805         delete delCommand;
806     else
807         m_commandStack->push(delCommand);
808     emit deleteProjectClips(ids, folderids);
809 }
810
811 void ProjectList::updateButtons() const
812 {
813     if (m_listView->topLevelItemCount() == 0) {
814         m_deleteButton->defaultAction()->setEnabled(false);
815     } else {
816         m_deleteButton->defaultAction()->setEnabled(true);
817         if (!m_listView->currentItem())
818             m_listView->setCurrentItem(m_listView->topLevelItem(0));
819         QTreeWidgetItem *item = m_listView->currentItem();
820         if (item && item->type() == PROJECTCLIPTYPE) {
821             m_editButton->defaultAction()->setEnabled(true);
822             m_openAction->setEnabled(true);
823             m_reloadAction->setEnabled(true);
824             m_transcodeAction->setEnabled(true);
825             m_proxyAction->setEnabled(true);
826             return;
827         }
828     }
829
830     m_editButton->defaultAction()->setEnabled(false);
831     m_openAction->setEnabled(false);
832     m_reloadAction->setEnabled(false);
833     m_transcodeAction->setEnabled(false);
834     m_proxyAction->setEnabled(false);
835 }
836
837 void ProjectList::selectItemById(const QString &clipId)
838 {
839     ProjectItem *item = getItemById(clipId);
840     if (item)
841         m_listView->setCurrentItem(item);
842 }
843
844
845 void ProjectList::slotDeleteClip(const QString &clipId)
846 {
847     ProjectItem *item = getItemById(clipId);
848     if (!item) {
849         kDebug() << "/// Cannot find clip to delete";
850         return;
851     }
852     m_listView->blockSignals(true);
853     QTreeWidgetItem *newSelectedItem = m_listView->itemAbove(item);
854     if (!newSelectedItem)
855         newSelectedItem = m_listView->itemBelow(item);
856     delete item;
857     m_doc->clipManager()->deleteClip(clipId);
858     m_listView->blockSignals(false);
859     if (newSelectedItem) {
860         m_listView->setCurrentItem(newSelectedItem);
861     } else {
862         updateButtons();
863         emit clipSelected(NULL);
864     }
865 }
866
867
868 void ProjectList::editFolder(const QString folderName, const QString oldfolderName, const QString &clipId)
869 {
870     EditFolderCommand *command = new EditFolderCommand(this, folderName, oldfolderName, clipId, false);
871     m_commandStack->push(command);
872     m_doc->setModified(true);
873 }
874
875 void ProjectList::slotAddFolder()
876 {
877     AddFolderCommand *command = new AddFolderCommand(this, i18n("Folder"), QString::number(m_doc->clipManager()->getFreeFolderId()), true);
878     m_commandStack->push(command);
879 }
880
881 void ProjectList::slotAddFolder(const QString foldername, const QString &clipId, bool remove, bool edit)
882 {
883     if (remove) {
884         FolderProjectItem *item = getFolderItemById(clipId);
885         if (item) {
886             m_doc->clipManager()->deleteFolder(clipId);
887             QTreeWidgetItem *newSelectedItem = m_listView->itemAbove(item);
888             if (!newSelectedItem)
889                 newSelectedItem = m_listView->itemBelow(item);
890             delete item;
891             if (newSelectedItem)
892                 m_listView->setCurrentItem(newSelectedItem);
893             else
894                 updateButtons();
895         }
896     } else {
897         if (edit) {
898             FolderProjectItem *item = getFolderItemById(clipId);
899             if (item) {
900                 m_listView->blockSignals(true);
901                 item->setGroupName(foldername);
902                 m_listView->blockSignals(false);
903                 m_doc->clipManager()->addFolder(clipId, foldername);
904                 const int children = item->childCount();
905                 for (int i = 0; i < children; i++) {
906                     ProjectItem *child = static_cast <ProjectItem *>(item->child(i));
907                     child->setProperty("groupname", foldername);
908                 }
909             }
910         } else {
911             m_listView->blockSignals(true);
912             m_listView->setCurrentItem(new FolderProjectItem(m_listView, QStringList() << foldername, clipId));
913             m_doc->clipManager()->addFolder(clipId, foldername);
914             m_listView->blockSignals(false);
915             m_listView->editItem(m_listView->currentItem(), 0);
916         }
917         updateButtons();
918     }
919     m_doc->setModified(true);
920 }
921
922
923
924 void ProjectList::deleteProjectFolder(QMap <QString, QString> map)
925 {
926     QMapIterator<QString, QString> i(map);
927     QUndoCommand *delCommand = new QUndoCommand();
928     delCommand->setText(i18n("Delete Folder"));
929     while (i.hasNext()) {
930         i.next();
931         new AddFolderCommand(this, i.key(), i.value(), false, delCommand);
932     }
933     m_commandStack->push(delCommand);
934 }
935
936 void ProjectList::slotAddClip(DocClipBase *clip, bool getProperties)
937 {
938     m_listView->setEnabled(false);
939     if (getProperties) m_listView->blockSignals(true);
940     const QString parent = clip->getProperty("groupid");
941     ProjectItem *item = NULL;
942     if (!parent.isEmpty()) {
943         FolderProjectItem *parentitem = getFolderItemById(parent);
944         if (!parentitem) {
945             QStringList text;
946             QString groupName = clip->getProperty("groupname");
947             //kDebug() << "Adding clip to new group: " << groupName;
948             if (groupName.isEmpty()) groupName = i18n("Folder");
949             text << groupName;
950             parentitem = new FolderProjectItem(m_listView, text, parent);
951         }
952
953         if (parentitem)
954             item = new ProjectItem(parentitem, clip);
955     }
956     if (item == NULL)
957         item = new ProjectItem(m_listView, clip);
958     if (item->data(0, DurationRole).isNull()) item->setData(0, DurationRole, i18n("Loading"));
959     if (getProperties) {
960         m_listView->blockSignals(true);
961         m_refreshed = false;
962         
963         // Proxy clips
964         CLIPTYPE t = clip->clipType();
965         if ((t == VIDEO || t == AV || t == UNKNOWN) && KdenliveSettings::enableproxy()) {
966             if (clip->getProperty("proxy").isEmpty()) {
967                 connect(clip, SIGNAL(proxyReady(const QString, bool)), this, SLOT(slotGotProxy(const QString, bool)));
968                 item->setProxyStatus(1);
969                 clip->generateProxy(m_doc->projectFolder());
970             }
971             else {
972                 // Proxy clip already created
973                 item->setProxyStatus(2);
974                 QDomElement e = clip->toXML().cloneNode().toElement();
975                 e.removeAttribute("file_hash");
976                 m_infoQueue.insert(clip->getId(), e);
977                 
978             }
979         }
980         else {
981             // We don't use proxies
982             // remove file_hash so that we load all properties for the clip
983             QDomElement e = clip->toXML().cloneNode().toElement();
984             e.removeAttribute("file_hash");
985             m_infoQueue.insert(clip->getId(), e);
986         }
987         //m_render->getFileProperties(clip->toXML(), clip->getId(), true);
988     }
989     clip->askForAudioThumbs();
990     
991     KUrl url = clip->fileURL();
992     if (getProperties == false && !clip->getClipHash().isEmpty()) {
993         QString cachedPixmap = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "thumbs/" + clip->getClipHash() + ".png";
994         if (QFile::exists(cachedPixmap)) {
995             QPixmap pix(cachedPixmap);
996             if (pix.isNull())
997                 KIO::NetAccess::del(KUrl(cachedPixmap), this);
998             item->setData(0, Qt::DecorationRole, pix);
999         }
1000     }
1001 #ifdef NEPOMUK
1002     if (!url.isEmpty() && KdenliveSettings::activate_nepomuk()) {
1003         // if file has Nepomuk comment, use it
1004         Nepomuk::Resource f(url.path());
1005         QString annotation = f.description();
1006         if (!annotation.isEmpty()) item->setText(1, annotation);
1007         item->setText(2, QString::number(f.rating()));
1008     }
1009 #endif
1010     // Add cut zones
1011     QList <CutZoneInfo> cuts = clip->cutZones();
1012     if (!cuts.isEmpty()) {
1013         for (int i = 0; i < cuts.count(); i++) {
1014             SubProjectItem *sub = new SubProjectItem(item, cuts.at(i).zone.x(), cuts.at(i).zone.y(), cuts.at(i).description);
1015             if (!clip->getClipHash().isEmpty()) {
1016                 QString cachedPixmap = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "thumbs/" + clip->getClipHash() + '#' + QString::number(cuts.at(i).zone.x()) + ".png";
1017                 if (QFile::exists(cachedPixmap)) {
1018                     QPixmap pix(cachedPixmap);
1019                     if (pix.isNull())
1020                         KIO::NetAccess::del(KUrl(cachedPixmap), this);
1021                     sub->setData(0, Qt::DecorationRole, pix);
1022                 }
1023             }
1024         }
1025     }
1026     if (m_listView->isEnabled()) {
1027         updateButtons();
1028         if (getProperties)
1029             m_listView->blockSignals(false);
1030     }
1031     
1032     if (getProperties && !m_queueTimer.isActive())
1033         slotProcessNextClipInQueue();
1034 }
1035
1036 void ProjectList::slotGotProxy(const QString id, bool success)
1037 {
1038     ProjectItem *item = getItemById(id);
1039     if (item) {
1040         disconnect(m_listView, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this, SLOT(slotItemEdited(QTreeWidgetItem *, int)));
1041         if (success) {
1042             // Proxy clip successfully created
1043             item->setProxyStatus(2);
1044             QDomElement e = item->referencedClip()->toXML().cloneNode().toElement();  
1045             e.removeAttribute("file_hash");
1046             e.setAttribute("replace", 1);
1047             m_infoQueue.insert(id, e);
1048             if (!m_queueTimer.isActive()) slotProcessNextClipInQueue();
1049         }
1050         else item->setProxyStatus(0);
1051         connect(m_listView, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this, SLOT(slotItemEdited(QTreeWidgetItem *, int)));
1052         update();
1053     }
1054 }
1055
1056 void ProjectList::slotResetProjectList()
1057 {
1058     m_listView->clear();
1059     emit clipSelected(NULL);
1060     m_thumbnailQueue.clear();
1061     m_infoQueue.clear();
1062     m_refreshed = false;
1063 }
1064
1065 void ProjectList::requestClipInfo(const QDomElement xml, const QString id)
1066 {
1067     m_refreshed = false;
1068     m_infoQueue.insert(id, xml);
1069     //if (m_infoQueue.count() == 1 || ) QTimer::singleShot(300, this, SLOT(slotProcessNextClipInQueue()));
1070 }
1071
1072 void ProjectList::slotProcessNextClipInQueue()
1073 {
1074     if (m_infoQueue.isEmpty()) {
1075         slotProcessNextThumbnail();
1076         return;
1077     }
1078
1079     QMap<QString, QDomElement>::const_iterator j = m_infoQueue.constBegin();
1080     if (j != m_infoQueue.constEnd()) {
1081         QDomElement dom = j.value();
1082         const QString id = j.key();
1083         m_infoQueue.remove(j.key());
1084         bool replace;
1085         if (dom.hasAttribute("replace")) {
1086             dom.removeAttribute("replace");
1087             replace = true;
1088         }
1089         else replace = false;
1090         emit getFileProperties(dom, id, m_listView->iconSize().height(), replace);
1091     }
1092     if (!m_infoQueue.isEmpty()) m_queueTimer.start();
1093 }
1094
1095 void ProjectList::slotUpdateClip(const QString &id)
1096 {
1097     ProjectItem *item = getItemById(id);
1098     m_listView->blockSignals(true);
1099     if (item) item->setData(0, UsageRole, QString::number(item->numReferences()));
1100     m_listView->blockSignals(false);
1101 }
1102
1103 void ProjectList::updateAllClips()
1104 {
1105     m_listView->setSortingEnabled(false);
1106     kDebug() << "// UPDATE ALL CLPY";
1107
1108     QTreeWidgetItemIterator it(m_listView);
1109     DocClipBase *clip;
1110     ProjectItem *item;
1111     m_listView->blockSignals(true);
1112     while (*it) {
1113         if ((*it)->type() == PROJECTSUBCLIPTYPE) {
1114             // subitem
1115             SubProjectItem *sub = static_cast <SubProjectItem *>(*it);
1116             if (sub->data(0, Qt::DecorationRole).isNull()) {
1117                 item = static_cast <ProjectItem *>((*it)->parent());
1118                 requestClipThumbnail(item->clipId() + '#' + QString::number(sub->zone().x()));
1119             }
1120             ++it;
1121             continue;
1122         } else if ((*it)->type() == PROJECTFOLDERTYPE) {
1123             // folder
1124             ++it;
1125             continue;
1126         } else {
1127             item = static_cast <ProjectItem *>(*it);
1128             clip = item->referencedClip();
1129             if (item->referencedClip()->producer() == NULL) {
1130                 if (clip->isPlaceHolder() == false)
1131                     requestClipInfo(clip->toXML(), clip->getId());
1132                 else if (!clip->isPlaceHolder())
1133                     item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsDropEnabled);
1134             } else {
1135                 if (item->data(0, Qt::DecorationRole).isNull())
1136                     requestClipThumbnail(clip->getId());
1137                 if (item->data(0, DurationRole).toString().isEmpty())
1138                     item->changeDuration(item->referencedClip()->producer()->get_playtime());
1139             }
1140             item->setData(0, UsageRole, QString::number(item->numReferences()));
1141         }
1142         //qApp->processEvents();
1143         ++it;
1144     }
1145     if (!m_queueTimer.isActive())
1146         m_queueTimer.start();
1147     if (m_listView->isEnabled())
1148         m_listView->blockSignals(false);
1149     m_listView->setSortingEnabled(true);
1150     if (m_infoQueue.isEmpty())
1151         slotProcessNextThumbnail();
1152 }
1153
1154 // static
1155 QString ProjectList::getExtensions()
1156 {
1157     // Build list of mime types
1158     QStringList mimeTypes = QStringList() << "application/x-kdenlive" << "application/x-kdenlivetitle" << "video/mlt-playlist" << "text/plain"
1159                             << "video/x-flv" << "application/vnd.rn-realmedia" << "video/x-dv" << "video/dv" << "video/x-msvideo" << "video/x-matroska" << "video/mpeg" << "video/ogg" << "video/x-ms-wmv" << "video/mp4" << "video/quicktime" << "video/webm"
1160                             << "audio/x-flac" << "audio/x-matroska" << "audio/mp4" << "audio/mpeg" << "audio/x-mp3" << "audio/ogg" << "audio/x-wav" << "application/ogg" << "application/mxf" << "application/x-shockwave-flash"
1161                             << "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";
1162
1163     QString allExtensions;
1164     foreach(const QString & mimeType, mimeTypes) {
1165         KMimeType::Ptr mime(KMimeType::mimeType(mimeType));
1166         if (mime) {
1167             allExtensions.append(mime->patterns().join(" "));
1168             allExtensions.append(' ');
1169         }
1170     }
1171     return allExtensions.simplified();
1172 }
1173
1174 void ProjectList::slotAddClip(const QList <QUrl> givenList, const QString &groupName, const QString &groupId)
1175 {
1176     if (!m_commandStack)
1177         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1178
1179     KUrl::List list;
1180     if (givenList.isEmpty()) {
1181         QString allExtensions = getExtensions();
1182         const QString dialogFilter = allExtensions + ' ' + QLatin1Char('|') + i18n("All Supported Files") + "\n* " + QLatin1Char('|') + i18n("All Files");
1183         QCheckBox *b = new QCheckBox(i18n("Import image sequence"));
1184         b->setChecked(KdenliveSettings::autoimagesequence());
1185         KFileDialog *d = new KFileDialog(KUrl("kfiledialog:///clipfolder"), dialogFilter, kapp->activeWindow(), b);
1186         d->setOperationMode(KFileDialog::Opening);
1187         d->setMode(KFile::Files);
1188         d->exec();
1189         list = d->selectedUrls();
1190         if (b->isChecked() && list.count() == 1) {
1191             // Check for image sequence
1192             KUrl url = list.at(0);
1193             QString fileName = url.fileName().section('.', 0, -2);
1194             if (fileName.at(fileName.size() - 1).isDigit()) {
1195                 KFileItem item(KFileItem::Unknown, KFileItem::Unknown, url);
1196                 if (item.mimetype().startsWith("image")) {
1197                     // import as sequence if we found more than one image in the sequence
1198                     QStringList list;
1199                     QString pattern = SlideshowClip::selectedPath(url.path(), false, QString(), &list);
1200                     int count = list.count();
1201                     if (count > 1) {
1202                         delete d;
1203                         QStringList groupInfo = getGroup();
1204
1205                         // get image sequence base name
1206                         while (fileName.at(fileName.size() - 1).isDigit()) {
1207                             fileName.chop(1);
1208                         }
1209
1210                         m_doc->slotCreateSlideshowClipFile(fileName, pattern, count, m_timecode.reformatSeparators(KdenliveSettings::sequence_duration()),
1211                                                            false, false, false,
1212                                                            m_timecode.getTimecodeFromFrames(int(ceil(m_timecode.fps()))), QString(), 0,
1213                                                            QString(), groupInfo.at(0), groupInfo.at(1));
1214                         return;
1215                     }
1216                 }
1217             }
1218         }
1219         delete d;
1220     } else {
1221         for (int i = 0; i < givenList.count(); i++)
1222             list << givenList.at(i);
1223     }
1224
1225     foreach(const KUrl & file, list) {
1226         // Check there is no folder here
1227         KMimeType::Ptr type = KMimeType::findByUrl(file);
1228         if (type->is("inode/directory")) {
1229             // user dropped a folder
1230             list.removeAll(file);
1231         }
1232     }
1233
1234     if (list.isEmpty())
1235         return;
1236
1237     if (givenList.isEmpty()) {
1238         QStringList groupInfo = getGroup();
1239         m_doc->slotAddClipList(list, groupInfo.at(0), groupInfo.at(1));
1240     } else {
1241         m_doc->slotAddClipList(list, groupName, groupId);
1242     }
1243 }
1244
1245 void ProjectList::slotRemoveInvalidClip(const QString &id, bool replace)
1246 {
1247     ProjectItem *item = getItemById(id);
1248     QTimer::singleShot(300, this, SLOT(slotProcessNextClipInQueue()));
1249     if (item) {
1250         const QString path = item->referencedClip()->fileURL().path();
1251         if (item->referencedClip()->isPlaceHolder()) replace = false;
1252         if (!path.isEmpty()) {
1253             if (replace)
1254                 KMessageBox::sorry(kapp->activeWindow(), i18n("Clip <b>%1</b><br />is invalid, will be removed from project.", path));
1255             else if (KMessageBox::questionYesNo(kapp->activeWindow(), i18n("Clip <b>%1</b><br />is missing or invalid. Remove it from project?", path), i18n("Invalid clip")) == KMessageBox::Yes)
1256                 replace = true;
1257         }
1258         if (replace)
1259             emit deleteProjectClips(QStringList() << id, QMap <QString, QString>());
1260     }
1261 }
1262
1263 void ProjectList::slotAddColorClip()
1264 {
1265     if (!m_commandStack)
1266         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1267
1268     QDialog *dia = new QDialog(this);
1269     Ui::ColorClip_UI dia_ui;
1270     dia_ui.setupUi(dia);
1271     dia->setWindowTitle(i18n("Color Clip"));
1272     dia_ui.clip_name->setText(i18n("Color Clip"));
1273
1274     TimecodeDisplay *t = new TimecodeDisplay(m_timecode);
1275     t->setValue(KdenliveSettings::color_duration());
1276     t->setTimeCodeFormat(false);
1277     dia_ui.clip_durationBox->addWidget(t);
1278     dia_ui.clip_color->setColor(KdenliveSettings::colorclipcolor());
1279
1280     if (dia->exec() == QDialog::Accepted) {
1281         QString color = dia_ui.clip_color->color().name();
1282         KdenliveSettings::setColorclipcolor(color);
1283         color = color.replace(0, 1, "0x") + "ff";
1284         QStringList groupInfo = getGroup();
1285         m_doc->slotCreateColorClip(dia_ui.clip_name->text(), color, m_timecode.getTimecode(t->gentime()), groupInfo.at(0), groupInfo.at(1));
1286     }
1287     delete t;
1288     delete dia;
1289 }
1290
1291
1292 void ProjectList::slotAddSlideshowClip()
1293 {
1294     if (!m_commandStack)
1295         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1296
1297     SlideshowClip *dia = new SlideshowClip(m_timecode, this);
1298
1299     if (dia->exec() == QDialog::Accepted) {
1300         QStringList groupInfo = getGroup();
1301         m_doc->slotCreateSlideshowClipFile(dia->clipName(), dia->selectedPath(), dia->imageCount(), dia->clipDuration(),
1302                                            dia->loop(), dia->crop(), dia->fade(),
1303                                            dia->lumaDuration(), dia->lumaFile(), dia->softness(),
1304                                            dia->animation(), groupInfo.at(0), groupInfo.at(1));
1305     }
1306     delete dia;
1307 }
1308
1309 void ProjectList::slotAddTitleClip()
1310 {
1311     QStringList groupInfo = getGroup();
1312     m_doc->slotCreateTextClip(groupInfo.at(0), groupInfo.at(1));
1313 }
1314
1315 void ProjectList::slotAddTitleTemplateClip()
1316 {
1317     if (!m_commandStack)
1318         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1319
1320     QStringList groupInfo = getGroup();
1321
1322     // Get the list of existing templates
1323     QStringList filter;
1324     filter << "*.kdenlivetitle";
1325     const QString path = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1326     QStringList templateFiles = QDir(path).entryList(filter, QDir::Files);
1327
1328     QDialog *dia = new QDialog(this);
1329     Ui::TemplateClip_UI dia_ui;
1330     dia_ui.setupUi(dia);
1331     for (int i = 0; i < templateFiles.size(); ++i)
1332         dia_ui.template_list->comboBox()->addItem(templateFiles.at(i), path + templateFiles.at(i));
1333
1334     if (!templateFiles.isEmpty())
1335         dia_ui.buttonBox->button(QDialogButtonBox::Ok)->setFocus();
1336     dia_ui.template_list->fileDialog()->setFilter("application/x-kdenlivetitle");
1337     //warning: setting base directory doesn't work??
1338     KUrl startDir(path);
1339     dia_ui.template_list->fileDialog()->setUrl(startDir);
1340     dia_ui.text_box->setHidden(true);
1341     if (dia->exec() == QDialog::Accepted) {
1342         QString textTemplate = dia_ui.template_list->comboBox()->itemData(dia_ui.template_list->comboBox()->currentIndex()).toString();
1343         if (textTemplate.isEmpty()) textTemplate = dia_ui.template_list->comboBox()->currentText();
1344         // Create a cloned template clip
1345         m_doc->slotCreateTextTemplateClip(groupInfo.at(0), groupInfo.at(1), KUrl(textTemplate));
1346     }
1347     delete dia;
1348 }
1349
1350 QStringList ProjectList::getGroup() const
1351 {
1352     QStringList result;
1353     QTreeWidgetItem *item = m_listView->currentItem();
1354     while (item && item->type() != PROJECTFOLDERTYPE)
1355         item = item->parent();
1356
1357     if (item) {
1358         FolderProjectItem *folder = static_cast <FolderProjectItem *>(item);
1359         result << folder->groupName() << folder->clipId();
1360     } else {
1361         result << QString() << QString();
1362     }
1363     return result;
1364 }
1365
1366 void ProjectList::setDocument(KdenliveDoc *doc)
1367 {
1368     m_listView->blockSignals(true);
1369     m_listView->clear();
1370     m_listView->setSortingEnabled(false);
1371     emit clipSelected(NULL);
1372     m_thumbnailQueue.clear();
1373     m_infoQueue.clear();
1374     m_refreshed = false;
1375     m_fps = doc->fps();
1376     m_timecode = doc->timecode();
1377     m_commandStack = doc->commandStack();
1378     m_doc = doc;
1379
1380     QMap <QString, QString> flist = doc->clipManager()->documentFolderList();
1381     QMapIterator<QString, QString> f(flist);
1382     while (f.hasNext()) {
1383         f.next();
1384         (void) new FolderProjectItem(m_listView, QStringList() << f.value(), f.key());
1385     }
1386
1387     QList <DocClipBase*> list = doc->clipManager()->documentClipList();
1388     for (int i = 0; i < list.count(); i++)
1389         slotAddClip(list.at(i), false);
1390
1391     m_listView->blockSignals(false);
1392     connect(m_doc->clipManager(), SIGNAL(reloadClip(const QString &)), this, SLOT(slotReloadClip(const QString &)));
1393     connect(m_doc->clipManager(), SIGNAL(modifiedClip(const QString &)), this, SLOT(slotModifiedClip(const QString &)));
1394     connect(m_doc->clipManager(), SIGNAL(missingClip(const QString &)), this, SLOT(slotMissingClip(const QString &)));
1395     connect(m_doc->clipManager(), SIGNAL(availableClip(const QString &)), this, SLOT(slotAvailableClip(const QString &)));
1396     connect(m_doc->clipManager(), SIGNAL(checkAllClips()), this, SLOT(updateAllClips()));
1397 }
1398
1399 QList <DocClipBase*> ProjectList::documentClipList() const
1400 {
1401     if (m_doc == NULL)
1402         return QList <DocClipBase*> ();
1403
1404     return m_doc->clipManager()->documentClipList();
1405 }
1406
1407 QDomElement ProjectList::producersList()
1408 {
1409     QDomDocument doc;
1410     QDomElement prods = doc.createElement("producerlist");
1411     doc.appendChild(prods);
1412     kDebug() << "////////////  PRO LIST BUILD PRDSLIST ";
1413     QTreeWidgetItemIterator it(m_listView);
1414     while (*it) {
1415         if ((*it)->type() != PROJECTCLIPTYPE) {
1416             // subitem
1417             ++it;
1418             continue;
1419         }
1420         prods.appendChild(doc.importNode(((ProjectItem *)(*it))->toXml(), true));
1421         ++it;
1422     }
1423     return prods;
1424 }
1425
1426 void ProjectList::slotCheckForEmptyQueue()
1427 {
1428     if (!m_refreshed && m_thumbnailQueue.isEmpty() && m_infoQueue.isEmpty()) {
1429         m_refreshed = true;
1430         emit loadingIsOver();
1431         emit displayMessage(QString(), -1);
1432         m_listView->blockSignals(false);
1433         m_listView->setEnabled(true);
1434         updateButtons();
1435     } else if (!m_refreshed) {
1436         QTimer::singleShot(300, this, SLOT(slotCheckForEmptyQueue()));
1437     }
1438 }
1439
1440 void ProjectList::reloadClipThumbnails()
1441 {
1442     m_thumbnailQueue.clear();
1443     QTreeWidgetItemIterator it(m_listView);
1444     while (*it) {
1445         if ((*it)->type() != PROJECTCLIPTYPE) {
1446             // subitem
1447             ++it;
1448             continue;
1449         }
1450         m_thumbnailQueue << ((ProjectItem *)(*it))->clipId();
1451         ++it;
1452     }
1453     QTimer::singleShot(300, this, SLOT(slotProcessNextThumbnail()));
1454 }
1455
1456 void ProjectList::requestClipThumbnail(const QString id)
1457 {
1458     if (!m_thumbnailQueue.contains(id)) m_thumbnailQueue.append(id);
1459 }
1460
1461 void ProjectList::slotProcessNextThumbnail()
1462 {
1463     if (m_thumbnailQueue.isEmpty() && m_infoQueue.isEmpty()) {
1464         slotCheckForEmptyQueue();
1465         return;
1466     }
1467     if (!m_infoQueue.isEmpty()) {
1468         //QTimer::singleShot(300, this, SLOT(slotProcessNextThumbnail()));
1469         return;
1470     }
1471     if (m_thumbnailQueue.count() > 1) {
1472         int max = m_doc->clipManager()->clipsCount();
1473         emit displayMessage(i18n("Loading thumbnails"), (int)(100 *(max - m_thumbnailQueue.count()) / max));
1474     }
1475     slotRefreshClipThumbnail(m_thumbnailQueue.takeFirst(), false);
1476 }
1477
1478 void ProjectList::slotRefreshClipThumbnail(const QString &clipId, bool update)
1479 {
1480     QTreeWidgetItem *item = getAnyItemById(clipId);
1481     if (item)
1482         slotRefreshClipThumbnail(item, update);
1483     else
1484         slotProcessNextThumbnail();
1485 }
1486
1487 void ProjectList::slotRefreshClipThumbnail(QTreeWidgetItem *it, bool update)
1488 {
1489     if (it == NULL) return;
1490     ProjectItem *item = NULL;
1491     bool isSubItem = false;
1492     int frame;
1493     if (it->type() == PROJECTFOLDERTYPE) return;
1494     if (it->type() == PROJECTSUBCLIPTYPE) {
1495         item = static_cast <ProjectItem *>(it->parent());
1496         frame = static_cast <SubProjectItem *>(it)->zone().x();
1497         isSubItem = true;
1498     } else {
1499         item = static_cast <ProjectItem *>(it);
1500         frame = item->referencedClip()->getClipThumbFrame();
1501     }
1502
1503     if (item) {
1504         DocClipBase *clip = item->referencedClip();
1505         if (!clip) {
1506             slotProcessNextThumbnail();
1507             return;
1508         }
1509         QPixmap pix;
1510         int height = m_listView->iconSize().height();
1511         int width = (int)(height  * m_render->dar());
1512         if (clip->clipType() == AUDIO)
1513             pix = KIcon("audio-x-generic").pixmap(QSize(width, height));
1514         else if (clip->clipType() == IMAGE)
1515             pix = QPixmap::fromImage(KThumb::getFrame(item->referencedClip()->producer(), 0, width, height));
1516         else
1517             pix = item->referencedClip()->thumbProducer()->extractImage(frame, width, height);
1518
1519         if (!pix.isNull()) {
1520             m_listView->blockSignals(true);
1521             it->setData(0, Qt::DecorationRole, pix);
1522             if (m_listView->isEnabled())
1523                 m_listView->blockSignals(false);
1524             if (!isSubItem)
1525                 m_doc->cachePixmap(item->getClipHash(), pix);
1526             else
1527                 m_doc->cachePixmap(item->getClipHash() + '#' + QString::number(frame), pix);
1528         }
1529         if (update)
1530             emit projectModified();
1531
1532         slotProcessNextThumbnail();
1533     }
1534 }
1535
1536 void ProjectList::slotReplyGetFileProperties(const QString &clipId, Mlt::Producer *producer, const QMap < QString, QString > &properties, const QMap < QString, QString > &metadata, bool replace)
1537 {
1538     QString toReload;
1539     ProjectItem *item = getItemById(clipId);
1540     if (item && producer) {
1541         m_listView->blockSignals(true);
1542         item->setProperties(properties, metadata);
1543         if (item->referencedClip()->isPlaceHolder() && producer->is_valid()) {
1544             item->referencedClip()->setValid();
1545             item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsDropEnabled);
1546             toReload = clipId;
1547         }
1548         if (item->referencedClip()->getProperty("proxy").isEmpty()) item->setProxyStatus(0);
1549         item->referencedClip()->setProducer(producer, replace);
1550         item->referencedClip()->askForAudioThumbs();
1551         if (!replace && item->data(0, Qt::DecorationRole).isNull())
1552             requestClipThumbnail(clipId);
1553         if (!toReload.isEmpty())
1554             item->slotSetToolTip();
1555
1556         if (m_listView->isEnabled() && replace) {
1557             // update clip in clip monitor
1558             emit clipSelected(NULL);
1559             emit clipSelected(item->referencedClip());
1560             //TODO: Make sure the line below has no side effect
1561             toReload = clipId;
1562         }
1563         /*else {
1564             // Check if duration changed.
1565             emit receivedClipDuration(clipId);
1566             delete producer;
1567         }*/
1568         if (m_listView->isEnabled())
1569             m_listView->blockSignals(false);
1570         /*if (item->icon(0).isNull()) {
1571             requestClipThumbnail(clipId);
1572         }*/
1573     } else kDebug() << "////////  COULD NOT FIND CLIP TO UPDATE PRPS...";
1574     if (item && m_infoQueue.isEmpty() && m_thumbnailQueue.isEmpty()) {
1575         m_listView->setCurrentItem(item);
1576         bool updatedProfile = false;
1577         if (item->parent()) {
1578             if (item->parent()->type() == PROJECTFOLDERTYPE)
1579                 static_cast <FolderProjectItem *>(item->parent())->switchIcon();
1580         } else if (KdenliveSettings::checkfirstprojectclip() &&  m_listView->topLevelItemCount() == 1) {
1581             // this is the first clip loaded in project, check if we want to adjust project settings to the clip
1582             updatedProfile = adjustProjectProfileToItem(item);
1583         }
1584         if (updatedProfile == false) emit clipSelected(item->referencedClip());
1585     } else {
1586         int max = m_doc->clipManager()->clipsCount();
1587         emit displayMessage(i18n("Loading clips"), (int)(100 *(max - m_infoQueue.count()) / max));
1588     }
1589     if (!toReload.isEmpty())
1590         emit clipNeedsReload(toReload, true);
1591
1592     qApp->processEvents();
1593     slotProcessNextClipInQueue();
1594 }
1595
1596 bool ProjectList::adjustProjectProfileToItem(ProjectItem *item)
1597 {
1598     if (item == NULL) {
1599         if (m_listView->currentItem() && m_listView->currentItem()->type() != PROJECTFOLDERTYPE)
1600             item = static_cast <ProjectItem*>(m_listView->currentItem());
1601     }
1602     if (item == NULL || item->referencedClip() == NULL) {
1603         KMessageBox::information(kapp->activeWindow(), i18n("Cannot find profile from current clip"));
1604         return false;
1605     }
1606     bool profileUpdated = false;
1607     QString size = item->referencedClip()->getProperty("frame_size");
1608     int width = size.section('x', 0, 0).toInt();
1609     int height = size.section('x', -1).toInt();
1610     double fps = item->referencedClip()->getProperty("fps").toDouble();
1611     double par = item->referencedClip()->getProperty("aspect_ratio").toDouble();
1612     if (item->clipType() == IMAGE || item->clipType() == AV || item->clipType() == VIDEO) {
1613         if (ProfilesDialog::matchProfile(width, height, fps, par, item->clipType() == IMAGE, m_doc->mltProfile()) == false) {
1614             // get a list of compatible profiles
1615             QMap <QString, QString> suggestedProfiles = ProfilesDialog::getProfilesFromProperties(width, height, fps, par, item->clipType() == IMAGE);
1616             if (!suggestedProfiles.isEmpty()) {
1617                 KDialog *dialog = new KDialog(this);
1618                 dialog->setCaption(i18n("Change project profile"));
1619                 dialog->setButtons(KDialog::Ok | KDialog::Cancel);
1620
1621                 QWidget container;
1622                 QVBoxLayout *l = new QVBoxLayout;
1623                 QLabel *label = new QLabel(i18n("Your clip does not match current project's profile.\nDo you want to change the project profile?\n\nThe following profiles match the clip (size: %1, fps: %2)", size, fps));
1624                 l->addWidget(label);
1625                 QListWidget *list = new QListWidget;
1626                 list->setAlternatingRowColors(true);
1627                 QMapIterator<QString, QString> i(suggestedProfiles);
1628                 while (i.hasNext()) {
1629                     i.next();
1630                     QListWidgetItem *item = new QListWidgetItem(i.value(), list);
1631                     item->setData(Qt::UserRole, i.key());
1632                     item->setToolTip(i.key());
1633                 }
1634                 list->setCurrentRow(0);
1635                 l->addWidget(list);
1636                 container.setLayout(l);
1637                 dialog->setButtonText(KDialog::Ok, i18n("Update profile"));
1638                 dialog->setMainWidget(&container);
1639                 if (dialog->exec() == QDialog::Accepted) {
1640                     //Change project profile
1641                     profileUpdated = true;
1642                     if (list->currentItem())
1643                         emit updateProfile(list->currentItem()->data(Qt::UserRole).toString());
1644                 }
1645                 delete list;
1646                 delete label;
1647             } else if (fps > 0) {
1648                 KMessageBox::information(kapp->activeWindow(), i18n("Your clip does not match current project's profile.\nNo existing profile found to match the clip's properties.\nClip size: %1\nFps: %2\n", size, fps));
1649             }
1650         }
1651     }
1652     return profileUpdated;
1653 }
1654
1655 void ProjectList::slotReplyGetImage(const QString &clipId, const QPixmap &pix)
1656 {
1657     ProjectItem *item = getItemById(clipId);
1658     if (item && !pix.isNull()) {
1659         m_listView->blockSignals(true);
1660         item->setData(0, Qt::DecorationRole, pix);
1661         m_doc->cachePixmap(item->getClipHash(), pix);
1662         if (m_listView->isEnabled())
1663             m_listView->blockSignals(false);
1664     }
1665 }
1666
1667 QTreeWidgetItem *ProjectList::getAnyItemById(const QString &id)
1668 {
1669     QTreeWidgetItemIterator it(m_listView);
1670     QString lookId = id;
1671     if (id.contains('#'))
1672         lookId = id.section('#', 0, 0);
1673
1674     ProjectItem *result = NULL;
1675     while (*it) {
1676         if ((*it)->type() != PROJECTCLIPTYPE) {
1677             // subitem
1678             ++it;
1679             continue;
1680         }
1681         ProjectItem *item = static_cast<ProjectItem *>(*it);
1682         if (item->clipId() == lookId) {
1683             result = item;
1684             break;
1685         }
1686         ++it;
1687     }
1688     if (result == NULL || !id.contains('#')) {
1689         return result;
1690     } else {
1691         for (int i = 0; i < result->childCount(); i++) {
1692             SubProjectItem *sub = static_cast <SubProjectItem *>(result->child(i));
1693             if (sub && sub->zone().x() == id.section('#', 1, 1).toInt())
1694                 return sub;
1695         }
1696     }
1697
1698     return NULL;
1699 }
1700
1701
1702 ProjectItem *ProjectList::getItemById(const QString &id)
1703 {
1704     ProjectItem *item;
1705     QTreeWidgetItemIterator it(m_listView);
1706     while (*it) {
1707         if ((*it)->type() != PROJECTCLIPTYPE) {
1708             // subitem
1709             ++it;
1710             continue;
1711         }
1712         item = static_cast<ProjectItem *>(*it);
1713         if (item->clipId() == id)
1714             return item;
1715         ++it;
1716     }
1717     return NULL;
1718 }
1719
1720 FolderProjectItem *ProjectList::getFolderItemById(const QString &id)
1721 {
1722     FolderProjectItem *item;
1723     QTreeWidgetItemIterator it(m_listView);
1724     while (*it) {
1725         if ((*it)->type() == PROJECTFOLDERTYPE) {
1726             item = static_cast<FolderProjectItem *>(*it);
1727             if (item->clipId() == id)
1728                 return item;
1729         }
1730         ++it;
1731     }
1732     return NULL;
1733 }
1734
1735 void ProjectList::slotSelectClip(const QString &ix)
1736 {
1737     ProjectItem *clip = getItemById(ix);
1738     if (clip) {
1739         m_listView->setCurrentItem(clip);
1740         m_listView->scrollToItem(clip);
1741         m_editButton->defaultAction()->setEnabled(true);
1742         m_deleteButton->defaultAction()->setEnabled(true);
1743         m_reloadAction->setEnabled(true);
1744         m_transcodeAction->setEnabled(true);
1745         m_proxyAction->setEnabled(true);
1746         if (clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) {
1747             m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
1748             m_openAction->setEnabled(true);
1749         } else if (clip->clipType() == AUDIO && !KdenliveSettings::defaultaudioapp().isEmpty()) {
1750             m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
1751             m_openAction->setEnabled(true);
1752         } else {
1753             m_openAction->setEnabled(false);
1754         }
1755     }
1756 }
1757
1758 QString ProjectList::currentClipUrl() const
1759 {
1760     ProjectItem *item;
1761     if (!m_listView->currentItem() || m_listView->currentItem()->type() == PROJECTFOLDERTYPE) return QString();
1762     if (m_listView->currentItem()->type() == PROJECTSUBCLIPTYPE) {
1763         // subitem
1764         item = static_cast <ProjectItem*>(m_listView->currentItem()->parent());
1765     } else {
1766         item = static_cast <ProjectItem*>(m_listView->currentItem());
1767     }
1768     if (item == NULL)
1769         return QString();
1770     return item->clipUrl().path();
1771 }
1772
1773 KUrl::List ProjectList::getConditionalUrls(const QString &condition) const
1774 {
1775     KUrl::List result;
1776     ProjectItem *item;
1777     QList<QTreeWidgetItem *> list = m_listView->selectedItems();
1778     for (int i = 0; i < list.count(); i++) {
1779         if (list.at(i)->type() == PROJECTFOLDERTYPE)
1780             continue;
1781         if (list.at(i)->type() == PROJECTSUBCLIPTYPE) {
1782             // subitem
1783             item = static_cast <ProjectItem*>(list.at(i)->parent());
1784         } else {
1785             item = static_cast <ProjectItem*>(list.at(i));
1786         }
1787         if (item == NULL || item->type() == COLOR || item->type() == SLIDESHOW || item->type() == TEXT)
1788             continue;
1789         DocClipBase *clip = item->referencedClip();
1790         if (!condition.isEmpty()) {
1791             if (condition.startsWith("vcodec") && !clip->hasVideoCodec(condition.section('=', 1, 1)))
1792                 continue;
1793             else if (condition.startsWith("acodec") && !clip->hasAudioCodec(condition.section('=', 1, 1)))
1794                 continue;
1795         }
1796         result.append(item->clipUrl());
1797     }
1798     return result;
1799 }
1800
1801 void ProjectList::regenerateTemplate(const QString &id)
1802 {
1803     ProjectItem *clip = getItemById(id);
1804     if (clip)
1805         regenerateTemplate(clip);
1806 }
1807
1808 void ProjectList::regenerateTemplate(ProjectItem *clip)
1809 {
1810     //TODO: remove this unused method, only force_reload is necessary
1811     clip->referencedClip()->producer()->set("force_reload", 1);
1812 }
1813
1814 QDomDocument ProjectList::generateTemplateXml(QString path, const QString &replaceString)
1815 {
1816     QDomDocument doc;
1817     QFile file(path);
1818     if (!file.open(QIODevice::ReadOnly)) {
1819         kWarning() << "ERROR, CANNOT READ: " << path;
1820         return doc;
1821     }
1822     if (!doc.setContent(&file)) {
1823         kWarning() << "ERROR, CANNOT READ: " << path;
1824         file.close();
1825         return doc;
1826     }
1827     file.close();
1828     QDomNodeList texts = doc.elementsByTagName("content");
1829     for (int i = 0; i < texts.count(); i++) {
1830         QString data = texts.item(i).firstChild().nodeValue();
1831         data.replace("%s", replaceString);
1832         texts.item(i).firstChild().setNodeValue(data);
1833     }
1834     return doc;
1835 }
1836
1837
1838 void ProjectList::slotAddClipCut(const QString &id, int in, int out)
1839 {
1840     ProjectItem *clip = getItemById(id);
1841     if (clip == NULL || clip->referencedClip()->hasCutZone(QPoint(in, out)))
1842         return;
1843     AddClipCutCommand *command = new AddClipCutCommand(this, id, in, out, QString(), true, false);
1844     m_commandStack->push(command);
1845 }
1846
1847 void ProjectList::addClipCut(const QString &id, int in, int out, const QString desc, bool newItem)
1848 {
1849     ProjectItem *clip = getItemById(id);
1850     if (clip) {
1851         DocClipBase *base = clip->referencedClip();
1852         base->addCutZone(in, out);
1853         m_listView->blockSignals(true);
1854         SubProjectItem *sub = new SubProjectItem(clip, in, out, desc);
1855         if (newItem && desc.isEmpty() && !m_listView->isColumnHidden(1)) {
1856             if (!clip->isExpanded())
1857                 clip->setExpanded(true);
1858             m_listView->scrollToItem(sub);
1859             m_listView->editItem(sub, 1);
1860         }
1861         QPixmap p = clip->referencedClip()->thumbProducer()->extractImage(in, (int)(sub->sizeHint(0).height()  * m_render->dar()), sub->sizeHint(0).height() - 2);
1862         sub->setData(0, Qt::DecorationRole, p);
1863         m_doc->cachePixmap(clip->getClipHash() + '#' + QString::number(in), p);
1864         m_listView->blockSignals(false);
1865     }
1866     emit projectModified();
1867 }
1868
1869 void ProjectList::removeClipCut(const QString &id, int in, int out)
1870 {
1871     ProjectItem *clip = getItemById(id);
1872     if (clip) {
1873         DocClipBase *base = clip->referencedClip();
1874         base->removeCutZone(in, out);
1875         SubProjectItem *sub = getSubItem(clip, QPoint(in, out));
1876         if (sub) {
1877             m_listView->blockSignals(true);
1878             delete sub;
1879             m_listView->blockSignals(false);
1880         }
1881     }
1882     emit projectModified();
1883 }
1884
1885 SubProjectItem *ProjectList::getSubItem(ProjectItem *clip, QPoint zone)
1886 {
1887     SubProjectItem *sub = NULL;
1888     if (clip) {
1889         for (int i = 0; i < clip->childCount(); i++) {
1890             QTreeWidgetItem *it = clip->child(i);
1891             if (it->type() == PROJECTSUBCLIPTYPE) {
1892                 sub = static_cast <SubProjectItem*>(it);
1893                 if (sub->zone() == zone)
1894                     break;
1895                 else
1896                     sub = NULL;
1897             }
1898         }
1899     }
1900     return sub;
1901 }
1902
1903 void ProjectList::slotUpdateClipCut(QPoint p)
1904 {
1905     if (!m_listView->currentItem() || m_listView->currentItem()->type() != PROJECTSUBCLIPTYPE)
1906         return;
1907     SubProjectItem *sub = static_cast <SubProjectItem*>(m_listView->currentItem());
1908     ProjectItem *item = static_cast <ProjectItem *>(sub->parent());
1909     EditClipCutCommand *command = new EditClipCutCommand(this, item->clipId(), sub->zone(), p, sub->text(1), sub->text(1), true);
1910     m_commandStack->push(command);
1911 }
1912
1913 void ProjectList::doUpdateClipCut(const QString &id, const QPoint oldzone, const QPoint zone, const QString &comment)
1914 {
1915     ProjectItem *clip = getItemById(id);
1916     SubProjectItem *sub = getSubItem(clip, oldzone);
1917     if (sub == NULL || clip == NULL)
1918         return;
1919     DocClipBase *base = clip->referencedClip();
1920     base->updateCutZone(oldzone.x(), oldzone.y(), zone.x(), zone.y(), comment);
1921     m_listView->blockSignals(true);
1922     sub->setZone(zone);
1923     sub->setDescription(comment);
1924     m_listView->blockSignals(false);
1925     emit projectModified();
1926 }
1927
1928 void ProjectList::slotForceProcessing(const QString &id)
1929 {
1930     while (m_infoQueue.contains(id)) {
1931         slotProcessNextClipInQueue();
1932     }
1933 }
1934
1935 void ProjectList::slotAddOrUpdateSequence(const QString frameName)
1936 {
1937     QString fileName = KUrl(frameName).fileName().section('_', 0, -2);
1938     QStringList list;
1939     QString pattern = SlideshowClip::selectedPath(frameName, false, QString(), &list);
1940     int count = list.count();
1941     if (count > 1) {
1942         const QList <DocClipBase *> existing = m_doc->clipManager()->getClipByResource(pattern);
1943         if (!existing.isEmpty()) {
1944             // Sequence already exists, update
1945             QString id = existing.at(0)->getId();
1946             //ProjectItem *item = getItemById(id);
1947             QMap <QString, QString> oldprops;
1948             QMap <QString, QString> newprops;
1949             int ttl = existing.at(0)->getProperty("ttl").toInt();
1950             oldprops["out"] = existing.at(0)->getProperty("out");
1951             newprops["out"] = QString::number(ttl * count - 1);
1952             slotUpdateClipProperties(id, newprops);
1953             EditClipCommand *command = new EditClipCommand(this, id, oldprops, newprops, false);
1954             m_commandStack->push(command);
1955         } else {
1956             // Create sequence
1957             QStringList groupInfo = getGroup();
1958             m_doc->slotCreateSlideshowClipFile(fileName, pattern, count, m_timecode.reformatSeparators(KdenliveSettings::sequence_duration()),
1959                                                false, false, false,
1960                                                m_timecode.getTimecodeFromFrames(int(ceil(m_timecode.fps()))), QString(), 0,
1961                                                QString(), groupInfo.at(0), groupInfo.at(1));
1962         }
1963     } else emit displayMessage(i18n("Sequence not found"), -2);
1964 }
1965
1966 QMap <QString, QString> ProjectList::getProxies()
1967 {
1968     QMap <QString, QString> list;
1969     ProjectItem *item;
1970     QTreeWidgetItemIterator it(m_listView);
1971     while (*it) {
1972         if ((*it)->type() != PROJECTCLIPTYPE) {
1973             ++it;
1974             continue;
1975         }
1976         item = static_cast<ProjectItem *>(*it);
1977         if (item && item->referencedClip() != NULL) {
1978             QString proxy = item->referencedClip()->getProperty("proxy");
1979             if (!proxy.isEmpty()) list.insert(proxy, item->clipUrl().path());
1980         }
1981         ++it;
1982     }
1983     return list;
1984 }
1985
1986 void ProjectList::updateProxyConfig()
1987 {
1988     ProjectItem *item;
1989     QTreeWidgetItemIterator it(m_listView);
1990     while (*it) {
1991         if ((*it)->type() != PROJECTCLIPTYPE) {
1992             ++it;
1993             continue;
1994         }
1995         item = static_cast<ProjectItem *>(*it);
1996         if (item && item->referencedClip() != NULL) {
1997             if  (KdenliveSettings::enableproxy()) {
1998                 DocClipBase *clip = item->referencedClip();
1999                 connect(clip, SIGNAL(proxyReady(const QString, bool)), this, SLOT(slotGotProxy(const QString, bool)));
2000                 item->setProxyStatus(1);
2001                 clip->generateProxy(m_doc->projectFolder());
2002             }
2003             else if (!item->referencedClip()->getProperty("proxy").isEmpty()) {
2004                 // remove proxy
2005                 item->referencedClip()->clearProperty("proxy");
2006                 QDomElement e = item->toXml().cloneNode().toElement();
2007                 e.removeAttribute("file_hash");
2008                 e.setAttribute("replace", 1);
2009                 m_infoQueue.insert(item->clipId(), e);
2010             }
2011         }
2012         ++it;
2013     }
2014     if (!m_infoQueue.isEmpty() && !m_queueTimer.isActive()) m_queueTimer.start();
2015
2016 }
2017
2018 void ProjectList::slotProxyCurrentItem(bool doProxy)
2019 {
2020     if (m_listView->currentItem()) {
2021         if (m_listView->currentItem()->type() == PROJECTCLIPTYPE) {
2022             ProjectItem *item = static_cast <ProjectItem*>(m_listView->currentItem());
2023             if (item->referencedClip()) {
2024                 if (doProxy) {
2025                     DocClipBase *clip = item->referencedClip();
2026                     connect(clip, SIGNAL(proxyReady(const QString, bool)), this, SLOT(slotGotProxy(const QString, bool)));
2027                     item->setProxyStatus(1);
2028                     clip->generateProxy(m_doc->projectFolder());
2029                 }
2030                 else if (!item->referencedClip()->getProperty("proxy").isEmpty()) {
2031                     // remove proxy
2032                     item->referencedClip()->clearProperty("proxy");
2033                     QDomElement e = item->toXml().cloneNode().toElement();
2034                     e.removeAttribute("file_hash");
2035                     e.setAttribute("replace", 1);
2036                     m_infoQueue.insert(item->clipId(), e);
2037                 }
2038             }
2039             if (!m_infoQueue.isEmpty() && !m_queueTimer.isActive()) m_queueTimer.start();
2040         }
2041     }
2042 }
2043
2044 #include "projectlist.moc"