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