]> git.sesse.net Git - kdenlive/blob - src/projectlist.cpp
Fix crash when enabling a proxy clip
[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 #include <KStandardDirs>
53
54 #ifdef NEPOMUK
55 #include <nepomuk/global.h>
56 #include <nepomuk/resourcemanager.h>
57 //#include <nepomuk/tag.h>
58 #endif
59
60 #include <QMouseEvent>
61 #include <QStylePainter>
62 #include <QPixmap>
63 #include <QIcon>
64 #include <QMenu>
65 #include <QProcess>
66 #include <QHeaderView>
67 #include <QInputDialog>
68 #include <QtConcurrentRun>
69 #include <QVBoxLayout>
70
71 InvalidDialog::InvalidDialog(const QString &caption, const QString &message, bool infoOnly, QWidget *parent) : KDialog(parent)
72 {
73     setCaption(caption);
74     if (infoOnly) setButtons(KDialog::Ok);
75     else setButtons(KDialog::Yes | KDialog::No);
76     QWidget *w = new QWidget(this);
77     QVBoxLayout *l = new QVBoxLayout;
78     l->addWidget(new QLabel(message));
79     m_clipList = new QListWidget;
80     l->addWidget(m_clipList);
81     w->setLayout(l);
82     setMainWidget(w);
83 }
84
85 InvalidDialog::~InvalidDialog()
86 {
87     delete m_clipList;
88 }
89
90
91 void InvalidDialog::addClip(const QString &id, const QString &path)
92 {
93     QListWidgetItem *item = new QListWidgetItem(path);
94     item->setData(Qt::UserRole, id);
95     m_clipList->addItem(item);
96 }
97
98 QStringList InvalidDialog::getIds() const
99 {
100     QStringList ids;
101     for (int i = 0; i < m_clipList->count(); i++) {
102         ids << m_clipList->item(i)->data(Qt::UserRole).toString();
103     }
104     return ids;
105 }
106
107
108 ProjectList::ProjectList(QWidget *parent) :
109     QWidget(parent),
110     m_render(NULL),
111     m_fps(-1),
112     m_commandStack(NULL),
113     m_openAction(NULL),
114     m_reloadAction(NULL),
115     m_transcodeAction(NULL),
116     m_doc(NULL),
117     m_refreshed(false),
118     m_thumbnailQueue(),
119     m_abortAllProxies(false),
120     m_invalidClipDialog(NULL)
121 {
122     QVBoxLayout *layout = new QVBoxLayout;
123     layout->setContentsMargins(0, 0, 0, 0);
124     layout->setSpacing(0);
125     qRegisterMetaType<QDomElement>("QDomElement");
126     // setup toolbar
127     QFrame *frame = new QFrame;
128     frame->setFrameStyle(QFrame::NoFrame);
129     QHBoxLayout *box = new QHBoxLayout;
130     KTreeWidgetSearchLine *searchView = new KTreeWidgetSearchLine;
131
132     box->addWidget(searchView);
133     //int s = style()->pixelMetric(QStyle::PM_SmallIconSize);
134     //m_toolbar->setIconSize(QSize(s, s));
135
136     m_addButton = new QToolButton;
137     m_addButton->setPopupMode(QToolButton::MenuButtonPopup);
138     m_addButton->setAutoRaise(true);
139     box->addWidget(m_addButton);
140
141     m_editButton = new QToolButton;
142     m_editButton->setAutoRaise(true);
143     box->addWidget(m_editButton);
144
145     m_deleteButton = new QToolButton;
146     m_deleteButton->setAutoRaise(true);
147     box->addWidget(m_deleteButton);
148     frame->setLayout(box);
149     layout->addWidget(frame);
150
151     m_listView = new ProjectListView;
152     layout->addWidget(m_listView);
153     setLayout(layout);
154     searchView->setTreeWidget(m_listView);
155
156     connect(this, SIGNAL(processNextThumbnail()), this, SLOT(slotProcessNextThumbnail()));
157     connect(m_listView, SIGNAL(projectModified()), this, SIGNAL(projectModified()));
158     connect(m_listView, SIGNAL(itemSelectionChanged()), this, SLOT(slotClipSelected()));
159     connect(m_listView, SIGNAL(focusMonitor()), this, SIGNAL(raiseClipMonitor()));
160     connect(m_listView, SIGNAL(pauseMonitor()), this, SLOT(slotPauseMonitor()));
161     connect(m_listView, SIGNAL(requestMenu(const QPoint &, QTreeWidgetItem *)), this, SLOT(slotContextMenu(const QPoint &, QTreeWidgetItem *)));
162     connect(m_listView, SIGNAL(addClip()), this, SLOT(slotAddClip()));
163     connect(m_listView, SIGNAL(addClip(const QList <QUrl>, const QString &, const QString &)), this, SLOT(slotAddClip(const QList <QUrl>, const QString &, const QString &)));
164     connect(m_listView, SIGNAL(addClipCut(const QString &, int, int)), this, SLOT(slotAddClipCut(const QString &, int, int)));
165     connect(m_listView, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this, SLOT(slotItemEdited(QTreeWidgetItem *, int)));
166     connect(m_listView, SIGNAL(showProperties(DocClipBase *)), this, SIGNAL(showClipProperties(DocClipBase *)));
167
168     m_listViewDelegate = new ItemDelegate(m_listView);
169     m_listView->setItemDelegate(m_listViewDelegate);
170 #ifdef NEPOMUK
171     if (KdenliveSettings::activate_nepomuk()) {
172         Nepomuk::ResourceManager::instance()->init();
173         if (!Nepomuk::ResourceManager::instance()->initialized()) {
174             kDebug() << "Cannot communicate with Nepomuk, DISABLING it";
175             KdenliveSettings::setActivate_nepomuk(false);
176         }
177     }
178 #endif
179 }
180
181 ProjectList::~ProjectList()
182 {
183     m_abortAllProxies = true;
184     m_thumbnailQueue.clear();
185     delete m_menu;
186     m_listView->blockSignals(true);
187     m_listView->clear();
188     delete m_listViewDelegate;
189 }
190
191 void ProjectList::focusTree() const
192 {
193     m_listView->setFocus();
194 }
195
196 void ProjectList::setupMenu(QMenu *addMenu, QAction *defaultAction)
197 {
198     QList <QAction *> actions = addMenu->actions();
199     for (int i = 0; i < actions.count(); i++) {
200         if (actions.at(i)->data().toString() == "clip_properties") {
201             m_editButton->setDefaultAction(actions.at(i));
202             actions.removeAt(i);
203             i--;
204         } else if (actions.at(i)->data().toString() == "delete_clip") {
205             m_deleteButton->setDefaultAction(actions.at(i));
206             actions.removeAt(i);
207             i--;
208         } else if (actions.at(i)->data().toString() == "edit_clip") {
209             m_openAction = actions.at(i);
210             actions.removeAt(i);
211             i--;
212         } else if (actions.at(i)->data().toString() == "reload_clip") {
213             m_reloadAction = actions.at(i);
214             actions.removeAt(i);
215             i--;
216         } else if (actions.at(i)->data().toString() == "proxy_clip") {
217             m_proxyAction = actions.at(i);
218             actions.removeAt(i);
219             i--;
220         }
221     }
222
223     QMenu *m = new QMenu();
224     m->addActions(actions);
225     m_addButton->setMenu(m);
226     m_addButton->setDefaultAction(defaultAction);
227     m_menu = new QMenu();
228     m_menu->addActions(addMenu->actions());
229 }
230
231 void ProjectList::setupGeneratorMenu(QMenu *addMenu, QMenu *transcodeMenu, QMenu *inTimelineMenu)
232 {
233     if (!addMenu)
234         return;
235     QMenu *menu = m_addButton->menu();
236     menu->addMenu(addMenu);
237     m_addButton->setMenu(menu);
238
239     m_menu->addMenu(addMenu);
240     if (addMenu->isEmpty())
241         addMenu->setEnabled(false);
242     m_menu->addMenu(transcodeMenu);
243     if (transcodeMenu->isEmpty())
244         transcodeMenu->setEnabled(false);
245     m_transcodeAction = transcodeMenu;
246     m_menu->addAction(m_reloadAction);
247     m_menu->addAction(m_proxyAction);
248     m_menu->addMenu(inTimelineMenu);
249     inTimelineMenu->setEnabled(false);
250     m_menu->addAction(m_editButton->defaultAction());
251     m_menu->addAction(m_openAction);
252     m_menu->addAction(m_deleteButton->defaultAction());
253     m_menu->insertSeparator(m_deleteButton->defaultAction());
254 }
255
256
257 QByteArray ProjectList::headerInfo() const
258 {
259     return m_listView->header()->saveState();
260 }
261
262 void ProjectList::setHeaderInfo(const QByteArray &state)
263 {
264     m_listView->header()->restoreState(state);
265 }
266
267 void ProjectList::updateProjectFormat(Timecode t)
268 {
269     m_timecode = t;
270 }
271
272 void ProjectList::slotEditClip()
273 {
274     QList<QTreeWidgetItem *> list = m_listView->selectedItems();
275     if (list.isEmpty()) return;
276     if (list.count() > 1 || list.at(0)->type() == PROJECTFOLDERTYPE) {
277         editClipSelection(list);
278         return;
279     }
280     ProjectItem *item;
281     if (!m_listView->currentItem() || m_listView->currentItem()->type() == PROJECTFOLDERTYPE)
282         return;
283     if (m_listView->currentItem()->type() == PROJECTSUBCLIPTYPE)
284         item = static_cast <ProjectItem*>(m_listView->currentItem()->parent());
285     else
286         item = static_cast <ProjectItem*>(m_listView->currentItem());
287     if (item && (item->flags() & Qt::ItemIsDragEnabled)) {
288         emit clipSelected(item->referencedClip());
289         emit showClipProperties(item->referencedClip());
290     }
291 }
292
293 void ProjectList::editClipSelection(QList<QTreeWidgetItem *> list)
294 {
295     // Gather all common properties
296     QMap <QString, QString> commonproperties;
297     QList <DocClipBase *> clipList;
298     commonproperties.insert("force_aspect_num", "-");
299     commonproperties.insert("force_aspect_den", "-");
300     commonproperties.insert("force_fps", "-");
301     commonproperties.insert("force_progressive", "-");
302     commonproperties.insert("force_tff", "-");
303     commonproperties.insert("threads", "-");
304     commonproperties.insert("video_index", "-");
305     commonproperties.insert("audio_index", "-");
306     commonproperties.insert("force_colorspace", "-");
307     commonproperties.insert("full_luma", "-");
308     QString transparency = "-";
309
310     bool allowDurationChange = true;
311     int commonDuration = -1;
312     bool hasImages = false;;
313     ProjectItem *item;
314     for (int i = 0; i < list.count(); i++) {
315         item = NULL;
316         if (list.at(i)->type() == PROJECTFOLDERTYPE) {
317             // Add folder items to the list
318             int ct = list.at(i)->childCount();
319             for (int j = 0; j < ct; j++) {
320                 list.append(list.at(i)->child(j));
321             }
322             continue;
323         }
324         else if (list.at(i)->type() == PROJECTSUBCLIPTYPE)
325             item = static_cast <ProjectItem*>(list.at(i)->parent());
326         else
327             item = static_cast <ProjectItem*>(list.at(i));
328         if (!(item->flags() & Qt::ItemIsDragEnabled))
329             continue;
330         if (item) {
331             // check properties
332             DocClipBase *clip = item->referencedClip();
333             if (clipList.contains(clip)) continue;
334             if (clip->clipType() == IMAGE) {
335                 hasImages = true;
336                 if (clip->getProperty("transparency").isEmpty() || clip->getProperty("transparency").toInt() == 0) {
337                     if (transparency == "-") {
338                         // first non transparent image
339                         transparency = "0";
340                     }
341                     else if (transparency == "1") {
342                         // we have transparent and non transparent clips
343                         transparency = "-1";
344                     }
345                 }
346                 else {
347                     if (transparency == "-") {
348                         // first transparent image
349                         transparency = "1";
350                     }
351                     else if (transparency == "0") {
352                         // we have transparent and non transparent clips
353                         transparency = "-1";
354                     }
355                 }
356             }
357             if (clip->clipType() != COLOR && clip->clipType() != IMAGE && clip->clipType() != TEXT)
358                 allowDurationChange = false;
359             if (allowDurationChange && commonDuration != 0) {
360                 if (commonDuration == -1)
361                     commonDuration = clip->duration().frames(m_fps);
362                 else if (commonDuration != clip->duration().frames(m_fps))
363                     commonDuration = 0;
364             }
365             clipList.append(clip);
366             QMap <QString, QString> clipprops = clip->properties();
367             QMapIterator<QString, QString> p(commonproperties);
368             while (p.hasNext()) {
369                 p.next();
370                 if (p.value().isEmpty()) continue;
371                 if (clipprops.contains(p.key())) {
372                     if (p.value() == "-")
373                         commonproperties.insert(p.key(), clipprops.value(p.key()));
374                     else if (p.value() != clipprops.value(p.key()))
375                         commonproperties.insert(p.key(), QString());
376                 } else {
377                     commonproperties.insert(p.key(), QString());
378                 }
379             }
380         }
381     }
382     if (allowDurationChange)
383         commonproperties.insert("out", QString::number(commonDuration));
384     if (hasImages)
385         commonproperties.insert("transparency", transparency);
386     /*QMapIterator<QString, QString> p(commonproperties);
387     while (p.hasNext()) {
388         p.next();
389         kDebug() << "Result: " << p.key() << " = " << p.value();
390     }*/
391     emit showClipProperties(clipList, commonproperties);
392 }
393
394 void ProjectList::slotOpenClip()
395 {
396     ProjectItem *item;
397     if (!m_listView->currentItem() || m_listView->currentItem()->type() == PROJECTFOLDERTYPE)
398         return;
399     if (m_listView->currentItem()->type() == QTreeWidgetItem::UserType + 1)
400         item = static_cast <ProjectItem*>(m_listView->currentItem()->parent());
401     else
402         item = static_cast <ProjectItem*>(m_listView->currentItem());
403     if (item) {
404         if (item->clipType() == IMAGE) {
405             if (KdenliveSettings::defaultimageapp().isEmpty())
406                 KMessageBox::sorry(kapp->activeWindow(), i18n("Please set a default application to open images in the Settings dialog"));
407             else
408                 QProcess::startDetached(KdenliveSettings::defaultimageapp(), QStringList() << item->clipUrl().path());
409         }
410         if (item->clipType() == AUDIO) {
411             if (KdenliveSettings::defaultaudioapp().isEmpty())
412                 KMessageBox::sorry(kapp->activeWindow(), i18n("Please set a default application to open audio files in the Settings dialog"));
413             else
414                 QProcess::startDetached(KdenliveSettings::defaultaudioapp(), QStringList() << item->clipUrl().path());
415         }
416     }
417 }
418
419 void ProjectList::cleanup()
420 {
421     m_listView->clearSelection();
422     QTreeWidgetItemIterator it(m_listView);
423     ProjectItem *item;
424     while (*it) {
425         if ((*it)->type() != PROJECTCLIPTYPE) {
426             it++;
427             continue;
428         }
429         item = static_cast <ProjectItem *>(*it);
430         if (item->numReferences() == 0)
431             item->setSelected(true);
432         it++;
433     }
434     slotRemoveClip();
435 }
436
437 void ProjectList::trashUnusedClips()
438 {
439     QTreeWidgetItemIterator it(m_listView);
440     ProjectItem *item;
441     QStringList ids;
442     QStringList urls;
443     while (*it) {
444         if ((*it)->type() != PROJECTCLIPTYPE) {
445             it++;
446             continue;
447         }
448         item = static_cast <ProjectItem *>(*it);
449         if (item->numReferences() == 0) {
450             ids << item->clipId();
451             KUrl url = item->clipUrl();
452             if (!url.isEmpty() && !urls.contains(url.path()))
453                 urls << url.path();
454         }
455         it++;
456     }
457
458     // Check that we don't use the URL in another clip
459     QTreeWidgetItemIterator it2(m_listView);
460     while (*it2) {
461         if ((*it2)->type() != PROJECTCLIPTYPE) {
462             it2++;
463             continue;
464         }
465         item = static_cast <ProjectItem *>(*it2);
466         if (item->numReferences() > 0) {
467             KUrl url = item->clipUrl();
468             if (!url.isEmpty() && urls.contains(url.path())) urls.removeAll(url.path());
469         }
470         it2++;
471     }
472
473     emit deleteProjectClips(ids, QMap <QString, QString>());
474     for (int i = 0; i < urls.count(); i++)
475         KIO::NetAccess::del(KUrl(urls.at(i)), this);
476 }
477
478 void ProjectList::slotReloadClip(const QString &id)
479 {
480     QList<QTreeWidgetItem *> selected;
481     if (id.isEmpty())
482         selected = m_listView->selectedItems();
483     else {
484         ProjectItem *itemToReLoad = getItemById(id);
485         if (itemToReLoad) selected.append(itemToReLoad);
486     }
487     ProjectItem *item;
488     for (int i = 0; i < selected.count(); i++) {
489         if (selected.at(i)->type() != PROJECTCLIPTYPE) {
490             if (selected.at(i)->type() == PROJECTFOLDERTYPE) {
491                 for (int j = 0; j < selected.at(i)->childCount(); j++)
492                     selected.append(selected.at(i)->child(j));
493             }
494             continue;
495         }
496         item = static_cast <ProjectItem *>(selected.at(i));
497         if (item && !item->isProxyRunning()) {
498             DocClipBase *clip = item->referencedClip();
499             if (!clip || !clip->isClean() || m_render->isProcessing(item->clipId())) {
500                 kDebug()<<"//// TRYING TO RELOAD: "<<item->clipId()<<", but it is busy";
501                 continue;
502             }
503             CLIPTYPE t = item->clipType();
504             if (t == TEXT) {
505                 if (clip && !clip->getProperty("xmltemplate").isEmpty())
506                     regenerateTemplate(item);
507             } else if (t != COLOR && t != SLIDESHOW && clip && clip->checkHash() == false) {
508                 item->referencedClip()->setPlaceHolder(true);
509                 item->setProperty("file_hash", QString());
510             } else if (t == IMAGE) {
511                 clip->getProducer()->set("force_reload", 1);
512             }
513
514             QDomElement e = item->toXml();
515             // Make sure we get the correct producer length if it was adjusted in timeline
516             if (t == COLOR || t == IMAGE || t == SLIDESHOW || t == TEXT) {
517                 int length = QString(clip->producerProperty("length")).toInt();
518                 if (length > 0 && !e.hasAttribute("length")) {
519                     e.setAttribute("length", length);
520                 }
521             }
522             resetThumbsProducer(clip);
523             m_render->getFileProperties(e, item->clipId(), m_listView->iconSize().height(), true);
524         }
525     }
526 }
527
528 void ProjectList::slotModifiedClip(const QString &id)
529 {
530     ProjectItem *item = getItemById(id);
531     if (item) {
532         QPixmap pixmap = qVariantValue<QPixmap>(item->data(0, Qt::DecorationRole));
533         if (!pixmap.isNull()) {
534             QPainter p(&pixmap);
535             p.fillRect(0, 0, pixmap.width(), pixmap.height(), QColor(255, 255, 255, 200));
536             p.drawPixmap(0, 0, KIcon("view-refresh").pixmap(m_listView->iconSize()));
537             p.end();
538         } else {
539             pixmap = KIcon("view-refresh").pixmap(m_listView->iconSize());
540         }
541         item->setData(0, Qt::DecorationRole, pixmap);
542     }
543 }
544
545 void ProjectList::slotMissingClip(const QString &id)
546 {
547     ProjectItem *item = getItemById(id);
548     if (item) {
549         item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsDropEnabled);
550         int height = m_listView->iconSize().height();
551         int width = (int)(height  * m_render->dar());
552         QPixmap pixmap = qVariantValue<QPixmap>(item->data(0, Qt::DecorationRole));
553         if (pixmap.isNull()) {
554             pixmap = QPixmap(width, height);
555             pixmap.fill(Qt::transparent);
556         }
557         KIcon icon("dialog-close");
558         QPainter p(&pixmap);
559         p.drawPixmap(3, 3, icon.pixmap(width - 6, height - 6));
560         p.end();
561         item->setData(0, Qt::DecorationRole, pixmap);
562         if (item->referencedClip()) {
563             item->referencedClip()->setPlaceHolder(true);
564             if (m_render == NULL) {
565                 kDebug() << "*********  ERROR, NULL RENDR";
566                 return;
567             }
568             Mlt::Producer *newProd = m_render->invalidProducer(id);
569             if (item->referencedClip()->getProducer()) {
570                 Mlt::Properties props(newProd->get_properties());
571                 Mlt::Properties src_props(item->referencedClip()->getProducer()->get_properties());
572                 props.inherit(src_props);
573             }
574             item->referencedClip()->setProducer(newProd, true);
575             item->slotSetToolTip();
576             emit clipNeedsReload(id);
577         }
578     }
579     update();
580     emit displayMessage(i18n("Check missing clips"), -2);
581     emit updateRenderStatus();
582 }
583
584 void ProjectList::slotAvailableClip(const QString &id)
585 {
586     ProjectItem *item = getItemById(id);
587     if (item == NULL)
588         return;
589     item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsDropEnabled);
590     if (item->referencedClip()) { // && item->referencedClip()->checkHash() == false) {
591         item->setProperty("file_hash", QString());
592         slotReloadClip(id);
593     }
594     /*else {
595     item->referencedClip()->setValid();
596     item->slotSetToolTip();
597     }
598     update();*/
599     emit updateRenderStatus();
600 }
601
602 bool ProjectList::hasMissingClips()
603 {
604     bool missing = false;
605     QTreeWidgetItemIterator it(m_listView);
606     while (*it) {
607         if ((*it)->type() == PROJECTCLIPTYPE && !((*it)->flags() & Qt::ItemIsDragEnabled)) {
608             missing = true;
609             break;
610         }
611         it++;
612     }
613     return missing;
614 }
615
616 void ProjectList::setRenderer(Render *projectRender)
617 {
618     m_render = projectRender;
619     m_listView->setIconSize(QSize((ProjectItem::itemDefaultHeight() - 2) * m_render->dar(), ProjectItem::itemDefaultHeight() - 2));
620 }
621
622 void ProjectList::slotClipSelected()
623 {
624     QTreeWidgetItem *item = m_listView->currentItem();
625     ProjectItem *clip = NULL;
626     if (item) {
627         if (item->type() == PROJECTFOLDERTYPE) {
628             emit clipSelected(NULL);
629             m_editButton->defaultAction()->setEnabled(item->childCount() > 0);
630             m_deleteButton->defaultAction()->setEnabled(true);
631             m_openAction->setEnabled(false);
632             m_reloadAction->setEnabled(false);
633             m_transcodeAction->setEnabled(false);
634         } else {
635             if (item->type() == PROJECTSUBCLIPTYPE) {
636                 // this is a sub item, use base clip
637                 m_deleteButton->defaultAction()->setEnabled(true);
638                 clip = static_cast <ProjectItem*>(item->parent());
639                 if (clip == NULL) kDebug() << "-----------ERROR";
640                 SubProjectItem *sub = static_cast <SubProjectItem*>(item);
641                 emit clipSelected(clip->referencedClip(), sub->zone());
642                 m_transcodeAction->setEnabled(false);
643                 m_reloadAction->setEnabled(false);
644                 adjustProxyActions(clip);
645                 return;
646             }
647             clip = static_cast <ProjectItem*>(item);
648             if (clip && clip->referencedClip())
649                 emit clipSelected(clip->referencedClip());
650             m_editButton->defaultAction()->setEnabled(true);
651             m_deleteButton->defaultAction()->setEnabled(true);
652             m_reloadAction->setEnabled(true);
653             m_transcodeAction->setEnabled(true);
654             if (clip && clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) {
655                 m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
656                 m_openAction->setEnabled(true);
657             } else if (clip && clip->clipType() == AUDIO && !KdenliveSettings::defaultaudioapp().isEmpty()) {
658                 m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
659                 m_openAction->setEnabled(true);
660             } else {
661                 m_openAction->setEnabled(false);
662             }
663             // Display relevant transcoding actions only
664             adjustTranscodeActions(clip);
665             // Display uses in timeline
666             emit findInTimeline(clip->clipId());
667         }
668     } else {
669         emit clipSelected(NULL);
670         m_editButton->defaultAction()->setEnabled(false);
671         m_deleteButton->defaultAction()->setEnabled(false);
672         m_openAction->setEnabled(false);
673         m_reloadAction->setEnabled(false);
674         m_transcodeAction->setEnabled(false);
675     }
676     adjustProxyActions(clip);
677 }
678
679 void ProjectList::adjustProxyActions(ProjectItem *clip) const
680 {
681     if (clip == NULL || clip->type() != PROJECTCLIPTYPE || clip->clipType() == COLOR || clip->clipType() == TEXT || clip->clipType() == SLIDESHOW || clip->clipType() == AUDIO) {
682         m_proxyAction->setEnabled(false);
683         return;
684     }
685     m_proxyAction->setEnabled(useProxy());
686     m_proxyAction->blockSignals(true);
687     m_proxyAction->setChecked(clip->hasProxy());
688     m_proxyAction->blockSignals(false);
689 }
690
691 void ProjectList::adjustTranscodeActions(ProjectItem *clip) const
692 {
693     if (clip == NULL || clip->type() != PROJECTCLIPTYPE || clip->clipType() == COLOR || clip->clipType() == TEXT || clip->clipType() == PLAYLIST || clip->clipType() == SLIDESHOW) {
694         m_transcodeAction->setEnabled(false);
695         return;
696     }
697     m_transcodeAction->setEnabled(true);
698     QList<QAction *> transcodeActions = m_transcodeAction->actions();
699     QStringList data;
700     QString condition;
701     for (int i = 0; i < transcodeActions.count(); i++) {
702         data = transcodeActions.at(i)->data().toStringList();
703         if (data.count() > 2) {
704             condition = data.at(2);
705             if (condition.startsWith("vcodec"))
706                 transcodeActions.at(i)->setEnabled(clip->referencedClip()->hasVideoCodec(condition.section('=', 1, 1)));
707             else if (condition.startsWith("acodec"))
708                 transcodeActions.at(i)->setEnabled(clip->referencedClip()->hasVideoCodec(condition.section('=', 1, 1)));
709         }
710     }
711
712 }
713
714 void ProjectList::slotPauseMonitor()
715 {
716     if (m_render)
717         m_render->pause();
718 }
719
720 void ProjectList::slotUpdateClipProperties(const QString &id, QMap <QString, QString> properties)
721 {
722     ProjectItem *item = getItemById(id);
723     if (item) {
724         slotUpdateClipProperties(item, properties);
725         if (properties.contains("out") || properties.contains("force_fps") || properties.contains("resource")) {
726             slotReloadClip(id);
727         } else if (properties.contains("colour") ||
728                    properties.contains("xmldata") ||
729                    properties.contains("force_aspect_num") ||
730                    properties.contains("force_aspect_den") ||
731                    properties.contains("templatetext")) {
732             slotRefreshClipThumbnail(item);
733             emit refreshClip(id, true);
734         } else if (properties.contains("full_luma") || properties.contains("force_colorspace") || properties.contains("loop")) {
735             emit refreshClip(id, false);
736         }
737     }
738 }
739
740 void ProjectList::slotUpdateClipProperties(ProjectItem *clip, QMap <QString, QString> properties)
741 {
742     if (!clip)
743         return;
744     clip->setProperties(properties);
745     if (properties.contains("name")) {
746         monitorItemEditing(false);
747         clip->setText(0, properties.value("name"));
748         monitorItemEditing(true);
749         emit clipNameChanged(clip->clipId(), properties.value("name"));
750     }
751     if (properties.contains("description")) {
752         CLIPTYPE type = clip->clipType();
753         monitorItemEditing(false);
754         clip->setText(1, properties.value("description"));
755         monitorItemEditing(true);
756 #ifdef NEPOMUK
757         if (KdenliveSettings::activate_nepomuk() && (type == AUDIO || type == VIDEO || type == AV || type == IMAGE || type == PLAYLIST)) {
758             // Use Nepomuk system to store clip description
759             Nepomuk::Resource f(clip->clipUrl().path());
760             f.setDescription(properties.value("description"));
761         }
762 #endif
763         emit projectModified();
764     }
765 }
766
767 void ProjectList::slotItemEdited(QTreeWidgetItem *item, int column)
768 {
769     if (item->type() == PROJECTSUBCLIPTYPE) {
770         // this is a sub-item
771         if (column == 1) {
772             // user edited description
773             SubProjectItem *sub = static_cast <SubProjectItem*>(item);
774             ProjectItem *item = static_cast <ProjectItem *>(sub->parent());
775             EditClipCutCommand *command = new EditClipCutCommand(this, item->clipId(), sub->zone(), sub->zone(), sub->description(), sub->text(1), true);
776             m_commandStack->push(command);
777             //slotUpdateCutClipProperties(sub->clipId(), sub->zone(), sub->text(1), sub->text(1));
778         }
779         return;
780     }
781     if (item->type() == PROJECTFOLDERTYPE) {
782         if (column == 0) {
783             FolderProjectItem *folder = static_cast <FolderProjectItem*>(item);
784             editFolder(item->text(0), folder->groupName(), folder->clipId());
785             folder->setGroupName(item->text(0));
786             m_doc->clipManager()->addFolder(folder->clipId(), item->text(0));
787             const int children = item->childCount();
788             for (int i = 0; i < children; i++) {
789                 ProjectItem *child = static_cast <ProjectItem *>(item->child(i));
790                 child->setProperty("groupname", item->text(0));
791             }
792         }
793         return;
794     }
795
796     ProjectItem *clip = static_cast <ProjectItem*>(item);
797     if (column == 1) {
798         if (clip->referencedClip()) {
799             QMap <QString, QString> oldprops;
800             QMap <QString, QString> newprops;
801             oldprops["description"] = clip->referencedClip()->getProperty("description");
802             newprops["description"] = item->text(1);
803
804             if (clip->clipType() == TEXT) {
805                 // This is a text template clip, update the image
806                 /*oldprops.insert("xmldata", clip->referencedClip()->getProperty("xmldata"));
807                 newprops.insert("xmldata", generateTemplateXml(clip->referencedClip()->getProperty("xmltemplate"), item->text(2)).toString());*/
808                 oldprops.insert("templatetext", clip->referencedClip()->getProperty("templatetext"));
809                 newprops.insert("templatetext", item->text(1));
810             }
811             slotUpdateClipProperties(clip->clipId(), newprops);
812             EditClipCommand *command = new EditClipCommand(this, clip->clipId(), oldprops, newprops, false);
813             m_commandStack->push(command);
814         }
815     } else if (column == 0) {
816         if (clip->referencedClip()) {
817             QMap <QString, QString> oldprops;
818             QMap <QString, QString> newprops;
819             oldprops["name"] = clip->referencedClip()->getProperty("name");
820             if (oldprops.value("name") != item->text(0)) {
821                 newprops["name"] = item->text(0);
822                 slotUpdateClipProperties(clip, newprops);
823                 emit projectModified();
824                 EditClipCommand *command = new EditClipCommand(this, clip->clipId(), oldprops, newprops, false);
825                 m_commandStack->push(command);
826             }
827         }
828     }
829 }
830
831 void ProjectList::slotContextMenu(const QPoint &pos, QTreeWidgetItem *item)
832 {
833     bool enable = item ? true : false;
834     m_editButton->defaultAction()->setEnabled(enable);
835     m_deleteButton->defaultAction()->setEnabled(enable);
836     m_reloadAction->setEnabled(enable);
837     m_transcodeAction->setEnabled(enable);
838     if (enable) {
839         ProjectItem *clip = NULL;
840         if (m_listView->currentItem()->type() == PROJECTSUBCLIPTYPE) {
841             clip = static_cast <ProjectItem*>(item->parent());
842             m_transcodeAction->setEnabled(false);
843             adjustProxyActions(clip);
844         } else if (m_listView->currentItem()->type() == PROJECTCLIPTYPE) {
845             clip = static_cast <ProjectItem*>(item);
846             // Display relevant transcoding actions only
847             adjustTranscodeActions(clip);
848             adjustProxyActions(clip);
849             // Display uses in timeline
850             emit findInTimeline(clip->clipId());
851         } else {
852             m_transcodeAction->setEnabled(false);
853         }
854         if (clip && clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) {
855             m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
856             m_openAction->setEnabled(true);
857         } else if (clip && clip->clipType() == AUDIO && !KdenliveSettings::defaultaudioapp().isEmpty()) {
858             m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
859             m_openAction->setEnabled(true);
860         } else {
861             m_openAction->setEnabled(false);
862         }
863
864     } else {
865         m_openAction->setEnabled(false);
866     }
867     m_menu->popup(pos);
868 }
869
870 void ProjectList::slotRemoveClip()
871 {
872     if (!m_listView->currentItem())
873         return;
874     QStringList ids;
875     QMap <QString, QString> folderids;
876     QList<QTreeWidgetItem *> selected = m_listView->selectedItems();
877
878     QUndoCommand *delCommand = new QUndoCommand();
879     delCommand->setText(i18n("Delete Clip Zone"));
880     for (int i = 0; i < selected.count(); i++) {
881         if (selected.at(i)->type() == PROJECTSUBCLIPTYPE) {
882             // subitem
883             SubProjectItem *sub = static_cast <SubProjectItem *>(selected.at(i));
884             ProjectItem *item = static_cast <ProjectItem *>(sub->parent());
885             new AddClipCutCommand(this, item->clipId(), sub->zone().x(), sub->zone().y(), sub->description(), false, true, delCommand);
886         } else if (selected.at(i)->type() == PROJECTFOLDERTYPE) {
887             // folder
888             FolderProjectItem *folder = static_cast <FolderProjectItem *>(selected.at(i));
889             folderids[folder->groupName()] = folder->clipId();
890             int children = folder->childCount();
891
892             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)
893                 return;
894             for (int i = 0; i < children; ++i) {
895                 ProjectItem *child = static_cast <ProjectItem *>(folder->child(i));
896                 ids << child->clipId();
897             }
898         } else {
899             ProjectItem *item = static_cast <ProjectItem *>(selected.at(i));
900             ids << item->clipId();
901             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) {
902                 KMessageBox::enableMessage("DeleteAll");
903                 return;
904             }
905         }
906     }
907     KMessageBox::enableMessage("DeleteAll");
908     if (delCommand->childCount() == 0)
909         delete delCommand;
910     else
911         m_commandStack->push(delCommand);
912     emit deleteProjectClips(ids, folderids);
913 }
914
915 void ProjectList::updateButtons() const
916 {
917     if (m_listView->topLevelItemCount() == 0) {
918         m_deleteButton->defaultAction()->setEnabled(false);
919         m_editButton->defaultAction()->setEnabled(false);
920     } else {
921         m_deleteButton->defaultAction()->setEnabled(true);
922         if (!m_listView->currentItem())
923             m_listView->setCurrentItem(m_listView->topLevelItem(0));
924         QTreeWidgetItem *item = m_listView->currentItem();
925         if (item && item->type() == PROJECTCLIPTYPE) {
926             m_editButton->defaultAction()->setEnabled(true);
927             m_openAction->setEnabled(true);
928             m_reloadAction->setEnabled(true);
929             m_transcodeAction->setEnabled(true);
930             return;
931         }
932         else if (item && item->type() == PROJECTFOLDERTYPE && item->childCount() > 0) {
933             m_editButton->defaultAction()->setEnabled(true);
934         }
935         else m_editButton->defaultAction()->setEnabled(false);
936     }
937     m_openAction->setEnabled(false);
938     m_reloadAction->setEnabled(false);
939     m_transcodeAction->setEnabled(false);
940     m_proxyAction->setEnabled(false);
941 }
942
943 void ProjectList::selectItemById(const QString &clipId)
944 {
945     ProjectItem *item = getItemById(clipId);
946     if (item)
947         m_listView->setCurrentItem(item);
948 }
949
950
951 void ProjectList::slotDeleteClip(const QString &clipId)
952 {
953     ProjectItem *item = getItemById(clipId);
954     if (!item) {
955         kDebug() << "/// Cannot find clip to delete";
956         return;
957     }
958     if (item->isProxyRunning()) m_abortProxy.append(item->referencedClip()->getProperty("proxy"));
959     m_listView->blockSignals(true);
960     QTreeWidgetItem *newSelectedItem = m_listView->itemAbove(item);
961     if (!newSelectedItem)
962         newSelectedItem = m_listView->itemBelow(item);
963     delete item;
964     // Pause playing to prevent crash while deleting clip
965     slotPauseMonitor();
966     m_doc->clipManager()->deleteClip(clipId);
967     m_listView->blockSignals(false);
968     if (newSelectedItem) {
969         m_listView->setCurrentItem(newSelectedItem);
970     } else {
971         updateButtons();
972         emit clipSelected(NULL);
973     }
974 }
975
976
977 void ProjectList::editFolder(const QString folderName, const QString oldfolderName, const QString &clipId)
978 {
979     EditFolderCommand *command = new EditFolderCommand(this, folderName, oldfolderName, clipId, false);
980     m_commandStack->push(command);
981     m_doc->setModified(true);
982 }
983
984 void ProjectList::slotAddFolder()
985 {
986     AddFolderCommand *command = new AddFolderCommand(this, i18n("Folder"), QString::number(m_doc->clipManager()->getFreeFolderId()), true);
987     m_commandStack->push(command);
988 }
989
990 void ProjectList::slotAddFolder(const QString foldername, const QString &clipId, bool remove, bool edit)
991 {
992     if (remove) {
993         FolderProjectItem *item = getFolderItemById(clipId);
994         if (item) {
995             m_doc->clipManager()->deleteFolder(clipId);
996             QTreeWidgetItem *newSelectedItem = m_listView->itemAbove(item);
997             if (!newSelectedItem)
998                 newSelectedItem = m_listView->itemBelow(item);
999             delete item;
1000             if (newSelectedItem)
1001                 m_listView->setCurrentItem(newSelectedItem);
1002             else
1003                 updateButtons();
1004         }
1005     } else {
1006         if (edit) {
1007             FolderProjectItem *item = getFolderItemById(clipId);
1008             if (item) {
1009                 m_listView->blockSignals(true);
1010                 item->setGroupName(foldername);
1011                 m_listView->blockSignals(false);
1012                 m_doc->clipManager()->addFolder(clipId, foldername);
1013                 const int children = item->childCount();
1014                 for (int i = 0; i < children; i++) {
1015                     ProjectItem *child = static_cast <ProjectItem *>(item->child(i));
1016                     child->setProperty("groupname", foldername);
1017                 }
1018             }
1019         } else {
1020             m_listView->blockSignals(true);
1021             m_listView->setCurrentItem(new FolderProjectItem(m_listView, QStringList() << foldername, clipId));
1022             m_doc->clipManager()->addFolder(clipId, foldername);
1023             m_listView->blockSignals(false);
1024             m_listView->editItem(m_listView->currentItem(), 0);
1025         }
1026         updateButtons();
1027     }
1028     m_doc->setModified(true);
1029 }
1030
1031
1032
1033 void ProjectList::deleteProjectFolder(QMap <QString, QString> map)
1034 {
1035     QMapIterator<QString, QString> i(map);
1036     QUndoCommand *delCommand = new QUndoCommand();
1037     delCommand->setText(i18n("Delete Folder"));
1038     while (i.hasNext()) {
1039         i.next();
1040         new AddFolderCommand(this, i.key(), i.value(), false, delCommand);
1041     }
1042     if (delCommand->childCount() > 0) m_commandStack->push(delCommand);
1043     else delete delCommand;
1044 }
1045
1046 void ProjectList::slotAddClip(DocClipBase *clip, bool getProperties)
1047 {
1048     //m_listView->setEnabled(false);
1049     const QString parent = clip->getProperty("groupid");
1050     ProjectItem *item = NULL;
1051     monitorItemEditing(false);
1052     if (!parent.isEmpty()) {
1053         FolderProjectItem *parentitem = getFolderItemById(parent);
1054         if (!parentitem) {
1055             QStringList text;
1056             QString groupName = clip->getProperty("groupname");
1057             //kDebug() << "Adding clip to new group: " << groupName;
1058             if (groupName.isEmpty()) groupName = i18n("Folder");
1059             text << groupName;
1060             parentitem = new FolderProjectItem(m_listView, text, parent);
1061         }
1062
1063         if (parentitem)
1064             item = new ProjectItem(parentitem, clip);
1065     }
1066     if (item == NULL) {
1067         item = new ProjectItem(m_listView, clip);
1068     }
1069     if (item->data(0, DurationRole).isNull()) item->setData(0, DurationRole, i18n("Loading"));
1070     QString proxy = clip->getProperty("proxy");
1071     if (!proxy.isEmpty() && proxy != "-") slotCreateProxy(clip->getId());
1072     connect(clip, SIGNAL(createProxy(const QString &)), this, SLOT(slotCreateProxy(const QString &)));
1073     connect(clip, SIGNAL(abortProxy(const QString &, const QString &)), this, SLOT(slotAbortProxy(const QString, const QString)));
1074     if (getProperties) {
1075         int height = m_listView->iconSize().height();
1076         int width = (int)(height  * m_render->dar());
1077         QPixmap pix =  KIcon("video-x-generic").pixmap(QSize(width, height));
1078         item->setData(0, Qt::DecorationRole, pix);
1079         //item->setFlags(Qt::ItemIsSelectable);
1080         m_listView->processLayout();
1081         QDomElement e = clip->toXML().cloneNode().toElement();
1082         e.removeAttribute("file_hash");
1083         resetThumbsProducer(clip);
1084         m_render->getFileProperties(e, clip->getId(), m_listView->iconSize().height(), true);
1085     }
1086     else if (item->hasProxy() && !item->isProxyRunning()) {
1087         slotCreateProxy(clip->getId());
1088     }
1089     clip->askForAudioThumbs();
1090     
1091     KUrl url = clip->fileURL();
1092 #ifdef NEPOMUK
1093     if (!url.isEmpty() && KdenliveSettings::activate_nepomuk()) {
1094         // if file has Nepomuk comment, use it
1095         Nepomuk::Resource f(url.path());
1096         QString annotation = f.description();
1097         if (!annotation.isEmpty()) item->setText(1, annotation);
1098         item->setText(2, QString::number(f.rating()));
1099     }
1100 #endif
1101     // Add cut zones
1102     QList <CutZoneInfo> cuts = clip->cutZones();
1103     if (!cuts.isEmpty()) {
1104         for (int i = 0; i < cuts.count(); i++) {
1105             SubProjectItem *sub = new SubProjectItem(item, cuts.at(i).zone.x(), cuts.at(i).zone.y(), cuts.at(i).description);
1106             if (!clip->getClipHash().isEmpty()) {
1107                 QString cachedPixmap = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "thumbs/" + clip->getClipHash() + '#' + QString::number(cuts.at(i).zone.x()) + ".png";
1108                 if (QFile::exists(cachedPixmap)) {
1109                     QPixmap pix(cachedPixmap);
1110                     if (pix.isNull())
1111                         KIO::NetAccess::del(KUrl(cachedPixmap), this);
1112                     sub->setData(0, Qt::DecorationRole, pix);
1113                 }
1114             }
1115         }
1116     }
1117     monitorItemEditing(true);
1118     updateButtons();
1119 }
1120
1121 void ProjectList::slotGotProxy(const QString &proxyPath)
1122 {
1123     if (proxyPath.isEmpty() || !m_refreshed || m_abortAllProxies) return;
1124     QTreeWidgetItemIterator it(m_listView);
1125     ProjectItem *item;
1126
1127     while (*it) {
1128         if ((*it)->type() == PROJECTCLIPTYPE) {
1129             item = static_cast <ProjectItem *>(*it);
1130             if (item->referencedClip()->getProperty("proxy") == proxyPath)
1131                 slotGotProxy(item);
1132         }
1133         ++it;
1134     }
1135 }
1136
1137 void ProjectList::slotGotProxy(ProjectItem *item)
1138 {
1139     if (item == NULL || !m_refreshed) return;
1140     DocClipBase *clip = item->referencedClip();
1141     if (!clip || !clip->isClean() || m_render->isProcessing(item->clipId())) {
1142         // Clip is being reprocessed, abort
1143         kDebug()<<"//// TRYING TO PROXY: "<<item->clipId()<<", but it is busy";
1144         return;
1145     }
1146     
1147     // Proxy clip successfully created
1148     QDomElement e = clip->toXML().cloneNode().toElement();
1149
1150     // Make sure we get the correct producer length if it was adjusted in timeline
1151     CLIPTYPE t = item->clipType();
1152     if (t == COLOR || t == IMAGE || t == SLIDESHOW || t == TEXT) {
1153         int length = QString(clip->producerProperty("length")).toInt();
1154         if (length > 0 && !e.hasAttribute("length")) {
1155             e.setAttribute("length", length);
1156         }
1157     }
1158     resetThumbsProducer(clip);
1159     m_render->getFileProperties(e, clip->getId(), m_listView->iconSize().height(), true);
1160 }
1161
1162 void ProjectList::slotResetProjectList()
1163 {
1164     m_abortAllProxies = true;
1165     m_proxyThreads.waitForFinished();
1166     m_proxyThreads.clearFutures();
1167     m_thumbnailQueue.clear();
1168     m_listView->clear();
1169     emit clipSelected(NULL);
1170     m_refreshed = false;
1171     m_abortAllProxies = false;
1172 }
1173
1174 void ProjectList::slotUpdateClip(const QString &id)
1175 {
1176     ProjectItem *item = getItemById(id);
1177     monitorItemEditing(false);
1178     if (item) item->setData(0, UsageRole, QString::number(item->numReferences()));
1179     monitorItemEditing(true);
1180 }
1181
1182 void ProjectList::getCachedThumbnail(ProjectItem *item)
1183 {
1184     if (!item) return;
1185     DocClipBase *clip = item->referencedClip();
1186     if (!clip) return;
1187     QString cachedPixmap = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "thumbs/" + clip->getClipHash() + ".png";
1188     if (QFile::exists(cachedPixmap)) {
1189         QPixmap pix(cachedPixmap);
1190         if (pix.isNull()) {
1191             KIO::NetAccess::del(KUrl(cachedPixmap), this);
1192             requestClipThumbnail(item->clipId());
1193         }
1194         else item->setData(0, Qt::DecorationRole, pix);
1195     }
1196     else requestClipThumbnail(item->clipId());
1197 }
1198
1199 void ProjectList::updateAllClips(bool displayRatioChanged, bool fpsChanged)
1200 {
1201     m_listView->setSortingEnabled(false);
1202
1203     QTreeWidgetItemIterator it(m_listView);
1204     DocClipBase *clip;
1205     ProjectItem *item;
1206     monitorItemEditing(false);
1207     int height = m_listView->iconSize().height();
1208     int width = (int)(height  * m_render->dar());
1209     QPixmap missingPixmap = QPixmap(width, height);
1210     missingPixmap.fill(Qt::transparent);
1211     KIcon icon("dialog-close");
1212     QPainter p(&missingPixmap);
1213     p.drawPixmap(3, 3, icon.pixmap(width - 6, height - 6));
1214     p.end();
1215     kDebug()<<"//////////////7  UPDATE ALL CLPS";
1216     while (*it) {
1217         if ((*it)->type() == PROJECTSUBCLIPTYPE) {
1218             // subitem
1219             SubProjectItem *sub = static_cast <SubProjectItem *>(*it);
1220             if (displayRatioChanged || sub->data(0, Qt::DecorationRole).isNull()) {
1221                 item = static_cast <ProjectItem *>((*it)->parent());
1222                 requestClipThumbnail(item->clipId() + '#' + QString::number(sub->zone().x()));
1223             }
1224             ++it;
1225             continue;
1226         } else if ((*it)->type() == PROJECTFOLDERTYPE) {
1227             // folder
1228             ++it;
1229             continue;
1230         } else {
1231             item = static_cast <ProjectItem *>(*it);
1232             clip = item->referencedClip();
1233             if (item->referencedClip()->getProducer() == NULL) {
1234                 if (clip->isPlaceHolder() == false) {
1235                     QDomElement xml = clip->toXML();
1236                     if (fpsChanged) {
1237                         xml.removeAttribute("out");
1238                         xml.removeAttribute("file_hash");
1239                         xml.removeAttribute("proxy_out");
1240                     }
1241                     bool replace = xml.attribute("replace") == "1";
1242                     if (replace) resetThumbsProducer(clip);
1243                     m_render->getFileProperties(xml, clip->getId(), m_listView->iconSize().height(), replace);
1244                 }
1245                 else {
1246                     item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsDropEnabled);
1247                     if (item->data(0, Qt::DecorationRole).isNull()) {
1248                         item->setData(0, Qt::DecorationRole, missingPixmap);
1249                     }
1250                     else {
1251                         QPixmap pixmap = qVariantValue<QPixmap>(item->data(0, Qt::DecorationRole));
1252                         QPainter p(&pixmap);
1253                         p.drawPixmap(3, 3, KIcon("dialog-close").pixmap(pixmap.width() - 6, pixmap.height() - 6));
1254                         p.end();
1255                         item->setData(0, Qt::DecorationRole, pixmap);
1256                     }
1257                 }
1258             } else {              
1259                 if (displayRatioChanged)
1260                     requestClipThumbnail(clip->getId());
1261                 else if (item->data(0, Qt::DecorationRole).isNull()) {
1262                     getCachedThumbnail(item);
1263                 }
1264                 if (item->data(0, DurationRole).toString().isEmpty()) {
1265                     item->changeDuration(item->referencedClip()->getProducer()->get_playtime());
1266                 }
1267                 if (clip->isPlaceHolder()) {
1268                     QPixmap pixmap = qVariantValue<QPixmap>(item->data(0, Qt::DecorationRole));
1269                     if (pixmap.isNull()) {
1270                         pixmap = QPixmap(width, height);
1271                         pixmap.fill(Qt::transparent);
1272                     }
1273                     QPainter p(&pixmap);
1274                     p.drawPixmap(3, 3, KIcon("dialog-close").pixmap(pixmap.width() - 6, pixmap.height() - 6));
1275                     p.end();
1276                     item->setData(0, Qt::DecorationRole, pixmap);
1277                 }
1278             }
1279             item->setData(0, UsageRole, QString::number(item->numReferences()));
1280         }
1281         ++it;
1282     }
1283
1284     m_listView->setSortingEnabled(true);
1285     if (m_render->processingItems() == 0) {
1286        monitorItemEditing(true);
1287        slotProcessNextThumbnail();
1288     }
1289 }
1290
1291 // static
1292 QString ProjectList::getExtensions()
1293 {
1294     // Build list of mime types
1295     QStringList mimeTypes = QStringList() << "application/x-kdenlive" << "application/x-kdenlivetitle" << "video/mlt-playlist" << "text/plain"
1296                             << "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"
1297                             << "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"
1298                             << "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";
1299
1300     QString allExtensions;
1301     foreach(const QString & mimeType, mimeTypes) {
1302         KMimeType::Ptr mime(KMimeType::mimeType(mimeType));
1303         if (mime) {
1304             allExtensions.append(mime->patterns().join(" "));
1305             allExtensions.append(' ');
1306         }
1307     }
1308     return allExtensions.simplified();
1309 }
1310
1311 void ProjectList::slotAddClip(const QList <QUrl> givenList, const QString &groupName, const QString &groupId)
1312 {
1313     if (!m_commandStack)
1314         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1315
1316     KUrl::List list;
1317     if (givenList.isEmpty()) {
1318         QString allExtensions = getExtensions();
1319         const QString dialogFilter = allExtensions + ' ' + QLatin1Char('|') + i18n("All Supported Files") + "\n* " + QLatin1Char('|') + i18n("All Files");
1320         QCheckBox *b = new QCheckBox(i18n("Import image sequence"));
1321         b->setChecked(KdenliveSettings::autoimagesequence());
1322         QCheckBox *c = new QCheckBox(i18n("Transparent background for images"));
1323         c->setChecked(KdenliveSettings::autoimagetransparency());
1324         QFrame *f = new QFrame;
1325         f->setFrameShape(QFrame::NoFrame);
1326         QHBoxLayout *l = new QHBoxLayout;
1327         l->addWidget(b);
1328         l->addWidget(c);
1329         l->addStretch(5);
1330         f->setLayout(l);
1331         KFileDialog *d = new KFileDialog(KUrl("kfiledialog:///clipfolder"), dialogFilter, kapp->activeWindow(), f);
1332         d->setOperationMode(KFileDialog::Opening);
1333         d->setMode(KFile::Files);
1334         if (d->exec() == QDialog::Accepted) {
1335             KdenliveSettings::setAutoimagetransparency(c->isChecked());
1336         }
1337         list = d->selectedUrls();
1338         if (b->isChecked() && list.count() == 1) {
1339             // Check for image sequence
1340             KUrl url = list.at(0);
1341             QString fileName = url.fileName().section('.', 0, -2);
1342             if (fileName.at(fileName.size() - 1).isDigit()) {
1343                 KFileItem item(KFileItem::Unknown, KFileItem::Unknown, url);
1344                 if (item.mimetype().startsWith("image")) {
1345                     // import as sequence if we found more than one image in the sequence
1346                     QStringList list;
1347                     QString pattern = SlideshowClip::selectedPath(url.path(), false, QString(), &list);
1348                     int count = list.count();
1349                     if (count > 1) {
1350                         delete d;
1351                         QStringList groupInfo = getGroup();
1352
1353                         // get image sequence base name
1354                         while (fileName.at(fileName.size() - 1).isDigit()) {
1355                             fileName.chop(1);
1356                         }
1357
1358                         m_doc->slotCreateSlideshowClipFile(fileName, pattern, count, m_timecode.reformatSeparators(KdenliveSettings::sequence_duration()),
1359                                                            false, false, false,
1360                                                            m_timecode.getTimecodeFromFrames(int(ceil(m_timecode.fps()))), QString(), 0,
1361                                                            QString(), groupInfo.at(0), groupInfo.at(1));
1362                         return;
1363                     }
1364                 }
1365             }
1366         }
1367         delete d;
1368     } else {
1369         for (int i = 0; i < givenList.count(); i++)
1370             list << givenList.at(i);
1371     }
1372
1373     foreach(const KUrl & file, list) {
1374         // Check there is no folder here
1375         KMimeType::Ptr type = KMimeType::findByUrl(file);
1376         if (type->is("inode/directory")) {
1377             // user dropped a folder
1378             list.removeAll(file);
1379         }
1380     }
1381
1382     if (list.isEmpty())
1383         return;
1384
1385     if (givenList.isEmpty()) {
1386         QStringList groupInfo = getGroup();
1387         m_doc->slotAddClipList(list, groupInfo.at(0), groupInfo.at(1));
1388     } else {
1389         m_doc->slotAddClipList(list, groupName, groupId);
1390     }
1391 }
1392
1393 void ProjectList::slotRemoveInvalidClip(const QString &id, bool replace)
1394 {
1395     ProjectItem *item = getItemById(id);
1396     m_processingClips.removeAll(id);
1397     m_thumbnailQueue.removeAll(id);
1398     if (item) {
1399         item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsDropEnabled);
1400         const QString path = item->referencedClip()->fileURL().path();
1401         if (item->referencedClip()->isPlaceHolder()) replace = false;
1402         if (!path.isEmpty()) {
1403             if (m_invalidClipDialog) {
1404                 m_invalidClipDialog->addClip(id, path);
1405                 return;
1406             }
1407             else {
1408                 if (replace)
1409                     m_invalidClipDialog = new InvalidDialog(i18n("Invalid clip"),  i18n("Clip <b>%1</b><br />is invalid, will be removed from project.", QString()), replace, kapp->activeWindow());
1410                 else {
1411                     m_invalidClipDialog = new InvalidDialog(i18n("Invalid clip"),  i18n("Clip <b>%1</b><br />is missing or invalid. Remove it from project?", QString()), replace, kapp->activeWindow());
1412                 }
1413                 m_invalidClipDialog->addClip(id, path);
1414                 int result = m_invalidClipDialog->exec();
1415                 if (result == KDialog::Yes) replace = true;
1416             }
1417         }
1418         if (m_invalidClipDialog) {
1419             if (replace)
1420                 emit deleteProjectClips(m_invalidClipDialog->getIds(), QMap <QString, QString>());
1421             delete m_invalidClipDialog;
1422             m_invalidClipDialog = NULL;
1423         }
1424         
1425     }
1426 }
1427
1428 void ProjectList::slotRemoveInvalidProxy(const QString &id, bool durationError)
1429 {
1430     ProjectItem *item = getItemById(id);
1431     if (item) {
1432         item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsDropEnabled);
1433         if (durationError) {
1434             kDebug() << "Proxy duration is wrong, try changing transcoding parameters.";
1435             emit displayMessage(i18n("Proxy clip unusable (duration is different from original)."), -2);
1436         }
1437         item->setProxyStatus(PROXYCRASHED);
1438         QString path = item->referencedClip()->getProperty("proxy");
1439         KUrl proxyFolder(m_doc->projectFolder().path( KUrl::AddTrailingSlash) + "proxy/");
1440
1441         //Security check: make sure the invalid proxy file is in the proxy folder
1442         if (proxyFolder.isParentOf(KUrl(path))) {
1443             QFile::remove(path);
1444         }
1445     }
1446     m_processingClips.removeAll(id);
1447     m_thumbnailQueue.removeAll(id);
1448 }
1449
1450 void ProjectList::slotAddColorClip()
1451 {
1452     if (!m_commandStack)
1453         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1454
1455     QDialog *dia = new QDialog(this);
1456     Ui::ColorClip_UI dia_ui;
1457     dia_ui.setupUi(dia);
1458     dia->setWindowTitle(i18n("Color Clip"));
1459     dia_ui.clip_name->setText(i18n("Color Clip"));
1460
1461     TimecodeDisplay *t = new TimecodeDisplay(m_timecode);
1462     t->setValue(KdenliveSettings::color_duration());
1463     t->setTimeCodeFormat(false);
1464     dia_ui.clip_durationBox->addWidget(t);
1465     dia_ui.clip_color->setColor(KdenliveSettings::colorclipcolor());
1466
1467     if (dia->exec() == QDialog::Accepted) {
1468         QString color = dia_ui.clip_color->color().name();
1469         KdenliveSettings::setColorclipcolor(color);
1470         color = color.replace(0, 1, "0x") + "ff";
1471         QStringList groupInfo = getGroup();
1472         m_doc->slotCreateColorClip(dia_ui.clip_name->text(), color, m_timecode.getTimecode(t->gentime()), groupInfo.at(0), groupInfo.at(1));
1473     }
1474     delete t;
1475     delete dia;
1476 }
1477
1478
1479 void ProjectList::slotAddSlideshowClip()
1480 {
1481     if (!m_commandStack)
1482         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1483
1484     SlideshowClip *dia = new SlideshowClip(m_timecode, this);
1485
1486     if (dia->exec() == QDialog::Accepted) {
1487         QStringList groupInfo = getGroup();
1488         m_doc->slotCreateSlideshowClipFile(dia->clipName(), dia->selectedPath(), dia->imageCount(), dia->clipDuration(),
1489                                            dia->loop(), dia->crop(), dia->fade(),
1490                                            dia->lumaDuration(), dia->lumaFile(), dia->softness(),
1491                                            dia->animation(), groupInfo.at(0), groupInfo.at(1));
1492     }
1493     delete dia;
1494 }
1495
1496 void ProjectList::slotAddTitleClip()
1497 {
1498     QStringList groupInfo = getGroup();
1499     m_doc->slotCreateTextClip(groupInfo.at(0), groupInfo.at(1));
1500 }
1501
1502 void ProjectList::slotAddTitleTemplateClip()
1503 {
1504     if (!m_commandStack)
1505         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1506
1507     QStringList groupInfo = getGroup();
1508
1509     // Get the list of existing templates
1510     QStringList filter;
1511     filter << "*.kdenlivetitle";
1512     const QString path = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1513     QStringList templateFiles = QDir(path).entryList(filter, QDir::Files);
1514
1515     QDialog *dia = new QDialog(this);
1516     Ui::TemplateClip_UI dia_ui;
1517     dia_ui.setupUi(dia);
1518     for (int i = 0; i < templateFiles.size(); ++i)
1519         dia_ui.template_list->comboBox()->addItem(templateFiles.at(i), path + templateFiles.at(i));
1520
1521     if (!templateFiles.isEmpty())
1522         dia_ui.buttonBox->button(QDialogButtonBox::Ok)->setFocus();
1523     dia_ui.template_list->fileDialog()->setFilter("application/x-kdenlivetitle");
1524     //warning: setting base directory doesn't work??
1525     KUrl startDir(path);
1526     dia_ui.template_list->fileDialog()->setUrl(startDir);
1527     dia_ui.text_box->setHidden(true);
1528     if (dia->exec() == QDialog::Accepted) {
1529         QString textTemplate = dia_ui.template_list->comboBox()->itemData(dia_ui.template_list->comboBox()->currentIndex()).toString();
1530         if (textTemplate.isEmpty()) textTemplate = dia_ui.template_list->comboBox()->currentText();
1531         // Create a cloned template clip
1532         m_doc->slotCreateTextTemplateClip(groupInfo.at(0), groupInfo.at(1), KUrl(textTemplate));
1533     }
1534     delete dia;
1535 }
1536
1537 QStringList ProjectList::getGroup() const
1538 {
1539     QStringList result;
1540     QTreeWidgetItem *item = m_listView->currentItem();
1541     while (item && item->type() != PROJECTFOLDERTYPE)
1542         item = item->parent();
1543
1544     if (item) {
1545         FolderProjectItem *folder = static_cast <FolderProjectItem *>(item);
1546         result << folder->groupName() << folder->clipId();
1547     } else {
1548         result << QString() << QString();
1549     }
1550     return result;
1551 }
1552
1553 void ProjectList::setDocument(KdenliveDoc *doc)
1554 {
1555     m_listView->blockSignals(true);
1556     m_abortAllProxies = true;
1557     m_proxyThreads.waitForFinished();
1558     m_proxyThreads.clearFutures();
1559     m_thumbnailQueue.clear();
1560     m_listView->clear();
1561     m_processingClips.clear();
1562     
1563     m_listView->setSortingEnabled(false);
1564     emit clipSelected(NULL);
1565     m_refreshed = false;
1566     m_fps = doc->fps();
1567     m_timecode = doc->timecode();
1568     m_commandStack = doc->commandStack();
1569     m_doc = doc;
1570     m_abortAllProxies = false;
1571
1572     QMap <QString, QString> flist = doc->clipManager()->documentFolderList();
1573     QStringList openedFolders = doc->getExpandedFolders();
1574     QMapIterator<QString, QString> f(flist);
1575     while (f.hasNext()) {
1576         f.next();
1577         FolderProjectItem *folder = new FolderProjectItem(m_listView, QStringList() << f.value(), f.key());
1578         folder->setExpanded(openedFolders.contains(f.key()));
1579     }
1580
1581     QList <DocClipBase*> list = doc->clipManager()->documentClipList();
1582     if (list.isEmpty()) m_refreshed = true;
1583     for (int i = 0; i < list.count(); i++)
1584         slotAddClip(list.at(i), false);
1585
1586     m_listView->blockSignals(false);
1587     connect(m_doc->clipManager(), SIGNAL(reloadClip(const QString &)), this, SLOT(slotReloadClip(const QString &)));
1588     connect(m_doc->clipManager(), SIGNAL(modifiedClip(const QString &)), this, SLOT(slotModifiedClip(const QString &)));
1589     connect(m_doc->clipManager(), SIGNAL(missingClip(const QString &)), this, SLOT(slotMissingClip(const QString &)));
1590     connect(m_doc->clipManager(), SIGNAL(availableClip(const QString &)), this, SLOT(slotAvailableClip(const QString &)));
1591     connect(m_doc->clipManager(), SIGNAL(checkAllClips(bool, bool)), this, SLOT(updateAllClips(bool, bool)));
1592 }
1593
1594 QList <DocClipBase*> ProjectList::documentClipList() const
1595 {
1596     if (m_doc == NULL)
1597         return QList <DocClipBase*> ();
1598
1599     return m_doc->clipManager()->documentClipList();
1600 }
1601
1602 QDomElement ProjectList::producersList()
1603 {
1604     QDomDocument doc;
1605     QDomElement prods = doc.createElement("producerlist");
1606     doc.appendChild(prods);
1607     kDebug() << "////////////  PRO LIST BUILD PRDSLIST ";
1608     QTreeWidgetItemIterator it(m_listView);
1609     while (*it) {
1610         if ((*it)->type() != PROJECTCLIPTYPE) {
1611             // subitem
1612             ++it;
1613             continue;
1614         }
1615         prods.appendChild(doc.importNode(((ProjectItem *)(*it))->toXml(), true));
1616         ++it;
1617     }
1618     return prods;
1619 }
1620
1621 void ProjectList::slotCheckForEmptyQueue()
1622 {
1623     if (m_render->processingItems() == 0 && m_thumbnailQueue.isEmpty()) {
1624         if (!m_refreshed) {
1625             emit loadingIsOver();
1626             emit displayMessage(QString(), -1);
1627             m_refreshed = true;
1628         }
1629         updateButtons();
1630     } else if (!m_refreshed) {
1631         QTimer::singleShot(300, this, SLOT(slotCheckForEmptyQueue()));
1632     }
1633 }
1634
1635
1636 void ProjectList::requestClipThumbnail(const QString id)
1637 {
1638     if (!m_thumbnailQueue.contains(id)) m_thumbnailQueue.append(id);
1639     slotProcessNextThumbnail();
1640 }
1641
1642 void ProjectList::resetThumbsProducer(DocClipBase *clip)
1643 {
1644     if (!clip) return;
1645     clip->clearThumbProducer();
1646     QString id = clip->getId();
1647     m_thumbnailQueue.removeAll(id);
1648 }
1649
1650 void ProjectList::slotProcessNextThumbnail()
1651 {
1652     if (m_render->processingItems() > 0) {
1653         return;
1654     }
1655     if (m_thumbnailQueue.isEmpty()) {
1656         slotCheckForEmptyQueue();
1657         return;
1658     }
1659     int max = m_doc->clipManager()->clipsCount();
1660     emit displayMessage(i18n("Loading thumbnails"), (int)(100 *(max - m_thumbnailQueue.count()) / max));
1661     slotRefreshClipThumbnail(m_thumbnailQueue.takeFirst(), false);
1662 }
1663
1664 void ProjectList::slotRefreshClipThumbnail(const QString &clipId, bool update)
1665 {
1666     QTreeWidgetItem *item = getAnyItemById(clipId);
1667     if (item)
1668         slotRefreshClipThumbnail(item, update);
1669     else {
1670         slotProcessNextThumbnail();
1671     }
1672 }
1673
1674 void ProjectList::slotRefreshClipThumbnail(QTreeWidgetItem *it, bool update)
1675 {
1676     if (it == NULL) return;
1677     ProjectItem *item = NULL;
1678     bool isSubItem = false;
1679     int frame;
1680     if (it->type() == PROJECTFOLDERTYPE) return;
1681     if (it->type() == PROJECTSUBCLIPTYPE) {
1682         item = static_cast <ProjectItem *>(it->parent());
1683         frame = static_cast <SubProjectItem *>(it)->zone().x();
1684         isSubItem = true;
1685     } else {
1686         item = static_cast <ProjectItem *>(it);
1687         frame = item->referencedClip()->getClipThumbFrame();
1688     }
1689
1690     if (item) {
1691         DocClipBase *clip = item->referencedClip();
1692         if (!clip) {
1693             slotProcessNextThumbnail();
1694             return;
1695         }
1696         QPixmap pix;
1697         int height = m_listView->iconSize().height();
1698         int swidth = (int)(height  * m_render->frameRenderWidth() / m_render->renderHeight()+ 0.5);
1699         int dwidth = (int)(height  * m_render->dar() + 0.5);
1700         if (clip->clipType() == AUDIO)
1701             pix = KIcon("audio-x-generic").pixmap(QSize(dwidth, height));
1702         else if (clip->clipType() == IMAGE)
1703             pix = QPixmap::fromImage(KThumb::getFrame(item->referencedClip()->getProducer(), 0, swidth, dwidth, height));
1704         else {
1705             pix = item->referencedClip()->extractImage(frame, dwidth, height);
1706         }
1707
1708         if (!pix.isNull()) {
1709             monitorItemEditing(false);
1710             it->setData(0, Qt::DecorationRole, pix);
1711             monitorItemEditing(true);
1712                 
1713             if (!isSubItem)
1714                 m_doc->cachePixmap(item->getClipHash(), pix);
1715             else
1716                 m_doc->cachePixmap(item->getClipHash() + '#' + QString::number(frame), pix);
1717         }
1718         if (update)
1719             emit projectModified();
1720         slotProcessNextThumbnail();
1721     }
1722 }
1723
1724
1725 void ProjectList::slotReplyGetFileProperties(const QString &clipId, Mlt::Producer *producer, const stringMap &properties, const stringMap &metadata, bool replace)
1726 {
1727     QString toReload;
1728     ProjectItem *item = getItemById(clipId);
1729
1730     int queue = m_render->processingItems();
1731     if (queue == 0) {
1732         m_listView->setEnabled(true);
1733     }
1734     if (item && producer) {
1735         monitorItemEditing(false);
1736         DocClipBase *clip = item->referencedClip();
1737         if (producer->is_valid()) {
1738             if (clip->isPlaceHolder()) {
1739                 clip->setValid();
1740                 toReload = clipId;
1741             }
1742             item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsDropEnabled);
1743         }
1744         item->setProperties(properties, metadata);
1745         clip->setProducer(producer, replace);
1746         clip->askForAudioThumbs();
1747
1748         // Proxy stuff
1749         QString size = properties.value("frame_size");
1750         if (!useProxy() && clip->getProperty("proxy").isEmpty()) setProxyStatus(item, NOPROXY);
1751         if (useProxy() && generateProxy() && clip->getProperty("proxy") == "-") setProxyStatus(item, NOPROXY);
1752         else if (useProxy() && !item->hasProxy() && !item->isProxyRunning()) {
1753             // proxy video and image clips
1754             int maxSize;
1755             CLIPTYPE t = item->clipType();
1756             if (t == IMAGE) maxSize = m_doc->getDocumentProperty("proxyimageminsize").toInt();
1757             else maxSize = m_doc->getDocumentProperty("proxyminsize").toInt();
1758             if ((((t == AV || t == VIDEO || t == PLAYLIST) && generateProxy()) || (t == IMAGE && generateImageProxy())) && (size.section('x', 0, 0).toInt() > maxSize || size.section('x', 1, 1).toInt() > maxSize)) {
1759                 if (clip->getProperty("proxy").isEmpty()) {
1760                     KUrl proxyPath = m_doc->projectFolder();
1761                     proxyPath.addPath("proxy/");
1762                     proxyPath.addPath(clip->getClipHash() + "." + (t == IMAGE ? "png" : m_doc->getDocumentProperty("proxyextension")));
1763                     QMap <QString, QString> newProps;
1764                     // insert required duration for proxy
1765                     if (t != IMAGE) newProps.insert("proxy_out", clip->producerProperty("out"));
1766                     newProps.insert("proxy", proxyPath.path());
1767                     QMap <QString, QString> oldProps = clip->properties();
1768                     oldProps.insert("proxy", QString());
1769                     EditClipCommand *command = new EditClipCommand(this, clipId, oldProps, newProps, true);
1770                     m_doc->commandStack()->push(command);
1771                 }
1772             }
1773         }
1774
1775         if (!replace && item->data(0, Qt::DecorationRole).isNull()) {
1776             requestClipThumbnail(clipId);
1777         }
1778         if (!toReload.isEmpty())
1779             item->slotSetToolTip();
1780     } else kDebug() << "////////  COULD NOT FIND CLIP TO UPDATE PRPS...";
1781     if (queue == 0) {
1782         monitorItemEditing(true);
1783         if (item && m_thumbnailQueue.isEmpty()) {
1784             m_listView->setCurrentItem(item);
1785             bool updatedProfile = false;
1786             if (item->parent()) {
1787                 if (item->parent()->type() == PROJECTFOLDERTYPE)
1788                     static_cast <FolderProjectItem *>(item->parent())->switchIcon();
1789             } else if (KdenliveSettings::checkfirstprojectclip() &&  m_listView->topLevelItemCount() == 1) {
1790                 // this is the first clip loaded in project, check if we want to adjust project settings to the clip
1791                 updatedProfile = adjustProjectProfileToItem(item);
1792             }
1793             if (updatedProfile == false) {
1794                 //emit clipSelected(item->referencedClip());
1795             }
1796         } else {
1797             int max = m_doc->clipManager()->clipsCount();
1798             emit displayMessage(i18n("Loading clips"), (int)(100 *(max - queue) / max));
1799         }
1800         processNextThumbnail();
1801     }
1802     if (replace && item) {
1803         toReload = clipId;
1804     }
1805     if (!item) {
1806         // no item for producer, delete it
1807         delete producer;
1808     }
1809     if (!toReload.isEmpty())
1810         emit clipNeedsReload(toReload);
1811 }
1812
1813 bool ProjectList::adjustProjectProfileToItem(ProjectItem *item)
1814 {
1815     if (item == NULL) {
1816         if (m_listView->currentItem() && m_listView->currentItem()->type() != PROJECTFOLDERTYPE)
1817             item = static_cast <ProjectItem*>(m_listView->currentItem());
1818     }
1819     if (item == NULL || item->referencedClip() == NULL) {
1820         KMessageBox::information(kapp->activeWindow(), i18n("Cannot find profile from current clip"));
1821         return false;
1822     }
1823     bool profileUpdated = false;
1824     QString size = item->referencedClip()->getProperty("frame_size");
1825     int width = size.section('x', 0, 0).toInt();
1826     int height = size.section('x', -1).toInt();
1827     double fps = item->referencedClip()->getProperty("fps").toDouble();
1828     double par = item->referencedClip()->getProperty("aspect_ratio").toDouble();
1829     if (item->clipType() == IMAGE || item->clipType() == AV || item->clipType() == VIDEO) {
1830         if (ProfilesDialog::matchProfile(width, height, fps, par, item->clipType() == IMAGE, m_doc->mltProfile()) == false) {
1831             // get a list of compatible profiles
1832             QMap <QString, QString> suggestedProfiles = ProfilesDialog::getProfilesFromProperties(width, height, fps, par, item->clipType() == IMAGE);
1833             if (!suggestedProfiles.isEmpty()) {
1834                 KDialog *dialog = new KDialog(this);
1835                 dialog->setCaption(i18n("Change project profile"));
1836                 dialog->setButtons(KDialog::Ok | KDialog::Cancel);
1837
1838                 QWidget container;
1839                 QVBoxLayout *l = new QVBoxLayout;
1840                 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));
1841                 l->addWidget(label);
1842                 QListWidget *list = new QListWidget;
1843                 list->setAlternatingRowColors(true);
1844                 QMapIterator<QString, QString> i(suggestedProfiles);
1845                 while (i.hasNext()) {
1846                     i.next();
1847                     QListWidgetItem *item = new QListWidgetItem(i.value(), list);
1848                     item->setData(Qt::UserRole, i.key());
1849                     item->setToolTip(i.key());
1850                 }
1851                 list->setCurrentRow(0);
1852                 l->addWidget(list);
1853                 container.setLayout(l);
1854                 dialog->setButtonText(KDialog::Ok, i18n("Update profile"));
1855                 dialog->setMainWidget(&container);
1856                 if (dialog->exec() == QDialog::Accepted) {
1857                     //Change project profile
1858                     profileUpdated = true;
1859                     if (list->currentItem())
1860                         emit updateProfile(list->currentItem()->data(Qt::UserRole).toString());
1861                 }
1862                 delete list;
1863                 delete label;
1864             } else if (fps > 0) {
1865                 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));
1866             }
1867         }
1868     }
1869     return profileUpdated;
1870 }
1871
1872 QString ProjectList::getDocumentProperty(const QString &key) const
1873 {
1874     return m_doc->getDocumentProperty(key);
1875 }
1876
1877 bool ProjectList::useProxy() const
1878 {
1879     return m_doc->getDocumentProperty("enableproxy").toInt();
1880 }
1881
1882 bool ProjectList::generateProxy() const
1883 {
1884     return m_doc->getDocumentProperty("generateproxy").toInt();
1885 }
1886
1887 bool ProjectList::generateImageProxy() const
1888 {
1889     return m_doc->getDocumentProperty("generateimageproxy").toInt();
1890 }
1891
1892 void ProjectList::slotReplyGetImage(const QString &clipId, const QImage &img)
1893 {
1894     QPixmap pix = QPixmap::fromImage(img);
1895     setThumbnail(clipId, pix);
1896 }
1897
1898 void ProjectList::slotReplyGetImage(const QString &clipId, const QString &name, int width, int height)
1899 {
1900     QPixmap pix =  KIcon(name).pixmap(QSize(width, height));
1901     setThumbnail(clipId, pix);
1902 }
1903
1904 void ProjectList::setThumbnail(const QString &clipId, const QPixmap &pix)
1905 {
1906     ProjectItem *item = getItemById(clipId);
1907     if (item && !pix.isNull()) {
1908         monitorItemEditing(false);
1909         item->setData(0, Qt::DecorationRole, pix);
1910         monitorItemEditing(true);
1911         //update();
1912         m_doc->cachePixmap(item->getClipHash(), pix);
1913     }
1914 }
1915
1916 QTreeWidgetItem *ProjectList::getAnyItemById(const QString &id)
1917 {
1918     QTreeWidgetItemIterator it(m_listView);
1919     QString lookId = id;
1920     if (id.contains('#'))
1921         lookId = id.section('#', 0, 0);
1922
1923     ProjectItem *result = NULL;
1924     while (*it) {
1925         if ((*it)->type() != PROJECTCLIPTYPE) {
1926             // subitem
1927             ++it;
1928             continue;
1929         }
1930         ProjectItem *item = static_cast<ProjectItem *>(*it);
1931         if (item->clipId() == lookId) {
1932             result = item;
1933             break;
1934         }
1935         ++it;
1936     }
1937     if (result == NULL || !id.contains('#')) {
1938         return result;
1939     } else {
1940         for (int i = 0; i < result->childCount(); i++) {
1941             SubProjectItem *sub = static_cast <SubProjectItem *>(result->child(i));
1942             if (sub && sub->zone().x() == id.section('#', 1, 1).toInt())
1943                 return sub;
1944         }
1945     }
1946
1947     return NULL;
1948 }
1949
1950
1951 ProjectItem *ProjectList::getItemById(const QString &id)
1952 {
1953     ProjectItem *item;
1954     QTreeWidgetItemIterator it(m_listView);
1955     while (*it) {
1956         if ((*it)->type() != PROJECTCLIPTYPE) {
1957             // subitem or folder
1958             ++it;
1959             continue;
1960         }
1961         item = static_cast<ProjectItem *>(*it);
1962         if (item->clipId() == id)
1963             return item;
1964         ++it;
1965     }
1966     return NULL;
1967 }
1968
1969 FolderProjectItem *ProjectList::getFolderItemById(const QString &id)
1970 {
1971     FolderProjectItem *item;
1972     QTreeWidgetItemIterator it(m_listView);
1973     while (*it) {
1974         if ((*it)->type() == PROJECTFOLDERTYPE) {
1975             item = static_cast<FolderProjectItem *>(*it);
1976             if (item->clipId() == id)
1977                 return item;
1978         }
1979         ++it;
1980     }
1981     return NULL;
1982 }
1983
1984 void ProjectList::slotSelectClip(const QString &ix)
1985 {
1986     ProjectItem *clip = getItemById(ix);
1987     if (clip) {
1988         m_listView->setCurrentItem(clip);
1989         m_listView->scrollToItem(clip);
1990         m_editButton->defaultAction()->setEnabled(true);
1991         m_deleteButton->defaultAction()->setEnabled(true);
1992         m_reloadAction->setEnabled(true);
1993         m_transcodeAction->setEnabled(true);
1994         if (clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) {
1995             m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
1996             m_openAction->setEnabled(true);
1997         } else if (clip->clipType() == AUDIO && !KdenliveSettings::defaultaudioapp().isEmpty()) {
1998             m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
1999             m_openAction->setEnabled(true);
2000         } else {
2001             m_openAction->setEnabled(false);
2002         }
2003     }
2004 }
2005
2006 QString ProjectList::currentClipUrl() const
2007 {
2008     ProjectItem *item;
2009     if (!m_listView->currentItem() || m_listView->currentItem()->type() == PROJECTFOLDERTYPE) return QString();
2010     if (m_listView->currentItem()->type() == PROJECTSUBCLIPTYPE) {
2011         // subitem
2012         item = static_cast <ProjectItem*>(m_listView->currentItem()->parent());
2013     } else {
2014         item = static_cast <ProjectItem*>(m_listView->currentItem());
2015     }
2016     if (item == NULL)
2017         return QString();
2018     return item->clipUrl().path();
2019 }
2020
2021 KUrl::List ProjectList::getConditionalUrls(const QString &condition) const
2022 {
2023     KUrl::List result;
2024     ProjectItem *item;
2025     QList<QTreeWidgetItem *> list = m_listView->selectedItems();
2026     for (int i = 0; i < list.count(); i++) {
2027         if (list.at(i)->type() == PROJECTFOLDERTYPE)
2028             continue;
2029         if (list.at(i)->type() == PROJECTSUBCLIPTYPE) {
2030             // subitem
2031             item = static_cast <ProjectItem*>(list.at(i)->parent());
2032         } else {
2033             item = static_cast <ProjectItem*>(list.at(i));
2034         }
2035         if (item == NULL || item->type() == COLOR || item->type() == SLIDESHOW || item->type() == TEXT)
2036             continue;
2037         DocClipBase *clip = item->referencedClip();
2038         if (!condition.isEmpty()) {
2039             if (condition.startsWith("vcodec") && !clip->hasVideoCodec(condition.section('=', 1, 1)))
2040                 continue;
2041             else if (condition.startsWith("acodec") && !clip->hasAudioCodec(condition.section('=', 1, 1)))
2042                 continue;
2043         }
2044         result.append(item->clipUrl());
2045     }
2046     return result;
2047 }
2048
2049 void ProjectList::regenerateTemplate(const QString &id)
2050 {
2051     ProjectItem *clip = getItemById(id);
2052     if (clip)
2053         regenerateTemplate(clip);
2054 }
2055
2056 void ProjectList::regenerateTemplate(ProjectItem *clip)
2057 {
2058     //TODO: remove this unused method, only force_reload is necessary
2059     clip->referencedClip()->getProducer()->set("force_reload", 1);
2060 }
2061
2062 QDomDocument ProjectList::generateTemplateXml(QString path, const QString &replaceString)
2063 {
2064     QDomDocument doc;
2065     QFile file(path);
2066     if (!file.open(QIODevice::ReadOnly)) {
2067         kWarning() << "ERROR, CANNOT READ: " << path;
2068         return doc;
2069     }
2070     if (!doc.setContent(&file)) {
2071         kWarning() << "ERROR, CANNOT READ: " << path;
2072         file.close();
2073         return doc;
2074     }
2075     file.close();
2076     QDomNodeList texts = doc.elementsByTagName("content");
2077     for (int i = 0; i < texts.count(); i++) {
2078         QString data = texts.item(i).firstChild().nodeValue();
2079         data.replace("%s", replaceString);
2080         texts.item(i).firstChild().setNodeValue(data);
2081     }
2082     return doc;
2083 }
2084
2085
2086 void ProjectList::slotAddClipCut(const QString &id, int in, int out)
2087 {
2088     ProjectItem *clip = getItemById(id);
2089     if (clip == NULL || clip->referencedClip()->hasCutZone(QPoint(in, out)))
2090         return;
2091     AddClipCutCommand *command = new AddClipCutCommand(this, id, in, out, QString(), true, false);
2092     m_commandStack->push(command);
2093 }
2094
2095 void ProjectList::addClipCut(const QString &id, int in, int out, const QString desc, bool newItem)
2096 {
2097     ProjectItem *clip = getItemById(id);
2098     if (clip) {
2099         DocClipBase *base = clip->referencedClip();
2100         base->addCutZone(in, out);
2101         monitorItemEditing(false);
2102         SubProjectItem *sub = new SubProjectItem(clip, in, out, desc);
2103         if (newItem && desc.isEmpty() && !m_listView->isColumnHidden(1)) {
2104             if (!clip->isExpanded())
2105                 clip->setExpanded(true);
2106             m_listView->scrollToItem(sub);
2107             m_listView->editItem(sub, 1);
2108         }
2109         QPixmap p = clip->referencedClip()->extractImage(in, (int)(sub->sizeHint(0).height()  * m_render->dar()), sub->sizeHint(0).height() - 2);
2110         sub->setData(0, Qt::DecorationRole, p);
2111         m_doc->cachePixmap(clip->getClipHash() + '#' + QString::number(in), p);
2112         monitorItemEditing(true);
2113     }
2114     emit projectModified();
2115 }
2116
2117 void ProjectList::removeClipCut(const QString &id, int in, int out)
2118 {
2119     ProjectItem *clip = getItemById(id);
2120     if (clip) {
2121         DocClipBase *base = clip->referencedClip();
2122         base->removeCutZone(in, out);
2123         SubProjectItem *sub = getSubItem(clip, QPoint(in, out));
2124         if (sub) {
2125             monitorItemEditing(false);
2126             delete sub;
2127             monitorItemEditing(true);
2128         }
2129     }
2130     emit projectModified();
2131 }
2132
2133 SubProjectItem *ProjectList::getSubItem(ProjectItem *clip, QPoint zone)
2134 {
2135     SubProjectItem *sub = NULL;
2136     if (clip) {
2137         for (int i = 0; i < clip->childCount(); i++) {
2138             QTreeWidgetItem *it = clip->child(i);
2139             if (it->type() == PROJECTSUBCLIPTYPE) {
2140                 sub = static_cast <SubProjectItem*>(it);
2141                 if (sub->zone() == zone)
2142                     break;
2143                 else
2144                     sub = NULL;
2145             }
2146         }
2147     }
2148     return sub;
2149 }
2150
2151 void ProjectList::slotUpdateClipCut(QPoint p)
2152 {
2153     if (!m_listView->currentItem() || m_listView->currentItem()->type() != PROJECTSUBCLIPTYPE)
2154         return;
2155     SubProjectItem *sub = static_cast <SubProjectItem*>(m_listView->currentItem());
2156     ProjectItem *item = static_cast <ProjectItem *>(sub->parent());
2157     EditClipCutCommand *command = new EditClipCutCommand(this, item->clipId(), sub->zone(), p, sub->text(1), sub->text(1), true);
2158     m_commandStack->push(command);
2159 }
2160
2161 void ProjectList::doUpdateClipCut(const QString &id, const QPoint oldzone, const QPoint zone, const QString &comment)
2162 {
2163     ProjectItem *clip = getItemById(id);
2164     SubProjectItem *sub = getSubItem(clip, oldzone);
2165     if (sub == NULL || clip == NULL)
2166         return;
2167     DocClipBase *base = clip->referencedClip();
2168     base->updateCutZone(oldzone.x(), oldzone.y(), zone.x(), zone.y(), comment);
2169     monitorItemEditing(false);
2170     sub->setZone(zone);
2171     sub->setDescription(comment);
2172     monitorItemEditing(true);
2173     emit projectModified();
2174 }
2175
2176 void ProjectList::slotForceProcessing(const QString &id)
2177 {
2178     m_render->forceProcessing(id);
2179 }
2180
2181 void ProjectList::slotAddOrUpdateSequence(const QString frameName)
2182 {
2183     QString fileName = KUrl(frameName).fileName().section('_', 0, -2);
2184     QStringList list;
2185     QString pattern = SlideshowClip::selectedPath(frameName, false, QString(), &list);
2186     int count = list.count();
2187     if (count > 1) {
2188         const QList <DocClipBase *> existing = m_doc->clipManager()->getClipByResource(pattern);
2189         if (!existing.isEmpty()) {
2190             // Sequence already exists, update
2191             QString id = existing.at(0)->getId();
2192             //ProjectItem *item = getItemById(id);
2193             QMap <QString, QString> oldprops;
2194             QMap <QString, QString> newprops;
2195             int ttl = existing.at(0)->getProperty("ttl").toInt();
2196             oldprops["out"] = existing.at(0)->getProperty("out");
2197             newprops["out"] = QString::number(ttl * count - 1);
2198             slotUpdateClipProperties(id, newprops);
2199             EditClipCommand *command = new EditClipCommand(this, id, oldprops, newprops, false);
2200             m_commandStack->push(command);
2201         } else {
2202             // Create sequence
2203             QStringList groupInfo = getGroup();
2204             m_doc->slotCreateSlideshowClipFile(fileName, pattern, count, m_timecode.reformatSeparators(KdenliveSettings::sequence_duration()),
2205                                                false, false, false,
2206                                                m_timecode.getTimecodeFromFrames(int(ceil(m_timecode.fps()))), QString(), 0,
2207                                                QString(), groupInfo.at(0), groupInfo.at(1));
2208         }
2209     } else emit displayMessage(i18n("Sequence not found"), -2);
2210 }
2211
2212 QMap <QString, QString> ProjectList::getProxies()
2213 {
2214     QMap <QString, QString> list;
2215     ProjectItem *item;
2216     QTreeWidgetItemIterator it(m_listView);
2217     while (*it) {
2218         if ((*it)->type() != PROJECTCLIPTYPE) {
2219             ++it;
2220             continue;
2221         }
2222         item = static_cast<ProjectItem *>(*it);
2223         if (item && item->referencedClip() != NULL) {
2224             if (item->hasProxy()) {
2225                 QString proxy = item->referencedClip()->getProperty("proxy");
2226                 list.insert(proxy, item->clipUrl().path());
2227             }
2228         }
2229         ++it;
2230     }
2231     return list;
2232 }
2233
2234 void ProjectList::slotCreateProxy(const QString id)
2235 {
2236     ProjectItem *item = getItemById(id);
2237     if (!item || item->isProxyRunning() || item->referencedClip()->isPlaceHolder()) return;
2238     QString path = item->referencedClip()->getProperty("proxy");
2239     if (path.isEmpty()) {
2240         setProxyStatus(path, PROXYCRASHED);
2241         return;
2242     }
2243     setProxyStatus(path, PROXYWAITING);
2244     if (m_abortProxy.contains(path)) m_abortProxy.removeAll(path);
2245     if (m_processingProxy.contains(path)) {
2246         // Proxy is already being generated
2247         return;
2248     }
2249     if (QFile::exists(path)) {
2250         // Proxy already created
2251         setProxyStatus(path, PROXYDONE);
2252         slotGotProxy(path);
2253         return;
2254     }
2255     m_processingProxy.append(path);
2256
2257     PROXYINFO info;
2258     info.dest = path;
2259     info.src = item->clipUrl().path();
2260     info.type = item->clipType();
2261     info.exif = QString(item->referencedClip()->producerProperty("_exif_orientation")).toInt();
2262     m_proxyList.append(info);
2263     m_proxyThreads.addFuture(QtConcurrent::run(this, &ProjectList::slotGenerateProxy));
2264 }
2265
2266 void ProjectList::slotAbortProxy(const QString id, const QString path)
2267 {
2268     QTreeWidgetItemIterator it(m_listView);
2269     ProjectItem *item = getItemById(id);
2270     setProxyStatus(item, NOPROXY);
2271     slotGotProxy(item);
2272     if (!path.isEmpty() && m_processingProxy.contains(path)) {
2273         m_abortProxy << path;
2274         setProxyStatus(path, NOPROXY);
2275     }
2276 }
2277
2278 void ProjectList::slotGenerateProxy()
2279 {
2280     if (m_proxyList.isEmpty() || m_abortAllProxies) return;
2281     emit projectModified();
2282     PROXYINFO info = m_proxyList.takeFirst();
2283     if (m_abortProxy.contains(info.dest)) {
2284         m_abortProxy.removeAll(info.dest);
2285         return;
2286     }
2287
2288     // Make sure proxy path is writable
2289     QFile file(info.dest);
2290     if (!file.open(QIODevice::WriteOnly)) {
2291         setProxyStatus(info.dest, PROXYCRASHED);
2292         m_processingProxy.removeAll(info.dest);
2293         return;
2294     }
2295     file.close();
2296     QFile::remove(info.dest);
2297     
2298     setProxyStatus(info.dest, CREATINGPROXY);
2299
2300     // Special case: playlist clips (.mlt or .kdenlive project files)
2301     if (info.type == PLAYLIST) {
2302         // change FFmpeg params to MLT format
2303         QStringList parameters;
2304         parameters << info.src;
2305         parameters << "-consumer" << "avformat:" + info.dest;
2306         QStringList params = m_doc->getDocumentProperty("proxyparams").simplified().split('-', QString::SkipEmptyParts);
2307         
2308         foreach(QString s, params) {
2309             s = s.simplified();
2310             if (s.count(' ') == 0) {
2311                 s.append("=1");
2312             }
2313             else s.replace(' ', '=');
2314             parameters << s;
2315         }
2316         
2317         parameters.append(QString("real_time=-%1").arg(KdenliveSettings::mltthreads()));
2318
2319         //TODO: currently, when rendering an xml file through melt, the display ration is lost, so we enforce it manualy
2320         double display_ratio = KdenliveDoc::getDisplayRatio(info.src);
2321         parameters << "aspect=" + QString::number(display_ratio);
2322
2323         //kDebug()<<"TRANSCOD: "<<parameters;
2324         QProcess myProcess;
2325         myProcess.setProcessChannelMode(QProcess::MergedChannels);
2326         myProcess.start(KdenliveSettings::rendererpath(), parameters);
2327         myProcess.waitForStarted();
2328         int result = -1;
2329         int duration = 0;
2330         while (myProcess.state() != QProcess::NotRunning) {
2331             // building proxy file
2332             if (m_abortProxy.contains(info.dest) || m_abortAllProxies) {
2333                 myProcess.close();
2334                 myProcess.waitForFinished();
2335                 QFile::remove(info.dest);
2336                 m_abortProxy.removeAll(info.dest);
2337                 m_processingProxy.removeAll(info.dest);
2338                 setProxyStatus(info.dest, NOPROXY);
2339                 result = -2;
2340             }
2341             else {
2342                 QString log = QString(myProcess.readAll());
2343                 processLogInfo(info.dest, &duration, log);
2344             }
2345             myProcess.waitForFinished(500);
2346         }
2347         myProcess.waitForFinished();
2348         m_processingProxy.removeAll(info.dest);
2349         if (result == -1) result = myProcess.exitStatus();
2350         if (result == 0) {
2351             // proxy successfully created
2352             setProxyStatus(info.dest, PROXYDONE);
2353             slotGotProxy(info.dest);
2354         }
2355         else if (result == 1) {
2356             // Proxy process crashed
2357             QFile::remove(info.dest);
2358             setProxyStatus(info.dest, PROXYCRASHED);
2359         }   
2360
2361     }
2362     
2363     if (info.type == IMAGE) {
2364         // Image proxy
2365         QImage i(info.src);
2366         if (i.isNull()) {
2367             // Cannot load image
2368             setProxyStatus(info.dest, PROXYCRASHED);
2369             return;
2370         }
2371         QImage proxy;
2372         // Images are scaled to profile size. 
2373         //TODO: Make it be configurable?
2374         if (i.width() > i.height()) proxy = i.scaledToWidth(m_render->frameRenderWidth());
2375         else proxy = i.scaledToHeight(m_render->renderHeight());
2376         if (info.exif > 1) {
2377             // Rotate image according to exif data
2378             QImage processed;
2379             QMatrix matrix;
2380
2381             switch ( info.exif ) {
2382                 case 2:
2383                   matrix.scale( -1, 1 );
2384                   break;
2385                 case 3:
2386                   matrix.rotate( 180 );
2387                   break;
2388                 case 4:
2389                   matrix.scale( 1, -1 );
2390                   break;
2391                 case 5:
2392                   matrix.rotate( 270 );
2393                   matrix.scale( -1, 1 );
2394                   break;
2395                 case 6:
2396                   matrix.rotate( 90 );
2397                   break;
2398                 case 7:
2399                   matrix.rotate( 90 );
2400                   matrix.scale( -1, 1 );
2401                   break;
2402                 case 8:
2403                   matrix.rotate( 270 );
2404                   break;
2405               }
2406               processed = proxy.transformed( matrix );
2407               processed.save(info.dest);
2408         }
2409         else proxy.save(info.dest);
2410         setProxyStatus(info.dest, PROXYDONE);
2411         slotGotProxy(info.dest);
2412         m_abortProxy.removeAll(info.dest);
2413         m_processingProxy.removeAll(info.dest);
2414         return;
2415     }
2416
2417     QStringList parameters;
2418     parameters << "-i" << info.src;
2419     QString params = m_doc->getDocumentProperty("proxyparams").simplified();
2420     foreach(QString s, params.split(' '))
2421     parameters << s;
2422
2423     // Make sure we don't block when proxy file already exists
2424     parameters << "-y";
2425     parameters << info.dest;
2426     kDebug()<<"// STARTING PROXY GEN: "<<parameters;
2427     QProcess myProcess;
2428     myProcess.setProcessChannelMode(QProcess::MergedChannels);
2429     myProcess.start("ffmpeg", parameters);
2430     myProcess.waitForStarted();
2431     int result = -1;
2432     int duration = 0;
2433     while (myProcess.state() != QProcess::NotRunning) {
2434         // building proxy file
2435         if (m_abortProxy.contains(info.dest) || m_abortAllProxies) {
2436             myProcess.close();
2437             myProcess.waitForFinished();
2438             m_abortProxy.removeAll(info.dest);
2439             m_processingProxy.removeAll(info.dest);
2440             QFile::remove(info.dest);
2441             setProxyStatus(info.dest, NOPROXY);
2442             result = -2;
2443             
2444         }
2445         else {
2446             QString log = QString(myProcess.readAll());
2447             processLogInfo(info.dest, &duration, log);
2448         }
2449         myProcess.waitForFinished(500);
2450     }
2451     myProcess.waitForFinished();
2452     if (result == -1) result = myProcess.exitStatus();
2453     if (result == 0) {
2454         // proxy successfully created
2455         setProxyStatus(info.dest, PROXYDONE);
2456         slotGotProxy(info.dest);
2457     }
2458     else if (result == 1) {
2459         // Proxy process crashed
2460         QFile::remove(info.dest);
2461         setProxyStatus(info.dest, PROXYCRASHED);
2462     }
2463     m_abortProxy.removeAll(info.dest);
2464     m_processingProxy.removeAll(info.dest);
2465 }
2466
2467
2468 void ProjectList::processLogInfo(const QString &path, int *duration, const QString &log)
2469 {
2470     int progress;
2471     if (*duration == 0) {
2472         if (log.contains("Duration:")) {
2473             QString data = log.section("Duration:", 1, 1).section(',', 0, 0).simplified();
2474             QStringList numbers = data.split(':');
2475             *duration = (int) (numbers.at(0).toInt() * 3600 + numbers.at(1).toInt() * 60 + numbers.at(2).toDouble());
2476         }
2477     }
2478     else if (log.contains("time=")) {
2479         QString time = log.section("time=", 1, 1).simplified().section(' ', 0, 0);
2480         if (time.contains(':')) {
2481             QStringList numbers = time.split(':');
2482             progress = numbers.at(0).toInt() * 3600 + numbers.at(1).toInt() * 60 + numbers.at(2).toDouble();
2483         }
2484         else progress = (int) time.toDouble();
2485         setProxyStatus(path, CREATINGPROXY, (int) (100.0 * progress / (*duration)));
2486     }
2487 }
2488
2489 void ProjectList::updateProxyConfig()
2490 {
2491     ProjectItem *item;
2492     QTreeWidgetItemIterator it(m_listView);
2493     QUndoCommand *command = new QUndoCommand();
2494     command->setText(i18n("Update proxy settings"));
2495     QString proxydir = m_doc->projectFolder().path( KUrl::AddTrailingSlash) + "proxy/";
2496     while (*it) {
2497         if ((*it)->type() != PROJECTCLIPTYPE) {
2498             ++it;
2499             continue;
2500         }
2501         item = static_cast<ProjectItem *>(*it);
2502         if (item == NULL) {
2503             ++it;
2504             continue;
2505         }
2506         CLIPTYPE t = item->clipType();
2507         if ((t == VIDEO || t == AV || t == UNKNOWN) && item->referencedClip() != NULL) {
2508             if  (generateProxy() && useProxy() && !item->isProxyRunning()) {
2509                 DocClipBase *clip = item->referencedClip();
2510                 if (clip->getProperty("frame_size").section('x', 0, 0).toInt() > m_doc->getDocumentProperty("proxyminsize").toInt()) {
2511                     if (clip->getProperty("proxy").isEmpty()) {
2512                         // We need to insert empty proxy in old properties so that undo will work
2513                         QMap <QString, QString> oldProps;// = clip->properties();
2514                         oldProps.insert("proxy", QString());
2515                         QMap <QString, QString> newProps;
2516                         newProps.insert("proxy", proxydir + item->referencedClip()->getClipHash() + "." + m_doc->getDocumentProperty("proxyextension"));
2517                         new EditClipCommand(this, clip->getId(), oldProps, newProps, true, command);
2518                     }
2519                 }
2520             }
2521             else if (item->hasProxy()) {
2522                 // remove proxy
2523                 QMap <QString, QString> newProps;
2524                 newProps.insert("proxy", QString());
2525                 newProps.insert("replace", "1");
2526                 // insert required duration for proxy
2527                 newProps.insert("proxy_out", item->referencedClip()->producerProperty("out"));
2528                 new EditClipCommand(this, item->clipId(), item->referencedClip()->properties(), newProps, true, command);
2529             }
2530         }
2531         else if (t == IMAGE && item->referencedClip() != NULL) {
2532             if  (generateImageProxy() && useProxy()) {
2533                 DocClipBase *clip = item->referencedClip();
2534                 int maxImageSize = m_doc->getDocumentProperty("proxyimageminsize").toInt();
2535                 if (clip->getProperty("frame_size").section('x', 0, 0).toInt() > maxImageSize || clip->getProperty("frame_size").section('x', 1, 1).toInt() > maxImageSize) {
2536                     if (clip->getProperty("proxy").isEmpty()) {
2537                         // We need to insert empty proxy in old properties so that undo will work
2538                         QMap <QString, QString> oldProps = clip->properties();
2539                         oldProps.insert("proxy", QString());
2540                         QMap <QString, QString> newProps;
2541                         newProps.insert("proxy", proxydir + item->referencedClip()->getClipHash() + ".png");
2542                         new EditClipCommand(this, clip->getId(), oldProps, newProps, true, command);
2543                     }
2544                 }
2545             }
2546             else if (item->hasProxy()) {
2547                 // remove proxy
2548                 QMap <QString, QString> newProps;
2549                 newProps.insert("proxy", QString());
2550                 newProps.insert("replace", "1");
2551                 new EditClipCommand(this, item->clipId(), item->referencedClip()->properties(), newProps, true, command);
2552             }
2553         }
2554         ++it;
2555     }
2556     if (command->childCount() > 0) m_doc->commandStack()->push(command);
2557     else delete command;
2558 }
2559
2560 void ProjectList::slotProxyCurrentItem(bool doProxy)
2561 {
2562     QList<QTreeWidgetItem *> list = m_listView->selectedItems();
2563     QTreeWidgetItem *listItem;
2564     QUndoCommand *command = new QUndoCommand();
2565     if (doProxy) command->setText(i18np("Add proxy clip", "Add proxy clips", list.count()));
2566     else command->setText(i18np("Remove proxy clip", "Remove proxy clips", list.count()));
2567     
2568     // Make sure the proxy folder exists
2569     QString proxydir = m_doc->projectFolder().path( KUrl::AddTrailingSlash) + "proxy/";
2570     KStandardDirs::makeDir(proxydir);
2571                 
2572     QMap <QString, QString> newProps;
2573     QMap <QString, QString> oldProps;
2574     if (!doProxy) newProps.insert("proxy", "-");
2575     for (int i = 0; i < list.count(); i++) {
2576         listItem = list.at(i);
2577         if (listItem->type() == PROJECTFOLDERTYPE) {
2578             for (int j = 0; j < listItem->childCount(); j++) {
2579                 QTreeWidgetItem *sub = listItem->child(j);
2580                 if (!list.contains(sub)) list.append(sub);
2581             }
2582         }
2583         else if (listItem->type() == PROJECTSUBCLIPTYPE) {
2584             QTreeWidgetItem *sub = listItem->parent();
2585             if (!list.contains(sub)) list.append(sub);
2586         }
2587         else if (listItem->type() == PROJECTCLIPTYPE) {
2588             ProjectItem *item = static_cast <ProjectItem*>(listItem);
2589             CLIPTYPE t = item->clipType();
2590             if ((t == VIDEO || t == AV || t == UNKNOWN || t == IMAGE || t == PLAYLIST) && item->referencedClip()) {
2591                 if ((doProxy && item->hasProxy()) || (!doProxy && !item->hasProxy())) continue;
2592                 DocClipBase *clip = item->referencedClip();
2593                 if (!clip || !clip->isClean() || m_render->isProcessing(item->clipId())) {
2594                     kDebug()<<"//// TRYING TO PROXY: "<<item->clipId()<<", but it is busy";
2595                     continue;
2596                 }
2597                 
2598                 resetThumbsProducer(clip);
2599                 oldProps = clip->properties();
2600                 if (doProxy) {
2601                     newProps.clear();
2602                     QString path = proxydir + clip->getClipHash() + "." + (t == IMAGE ? "png" : m_doc->getDocumentProperty("proxyextension"));
2603                     // insert required duration for proxy
2604                     newProps.insert("proxy_out", clip->producerProperty("out"));
2605                     newProps.insert("proxy", path);
2606                     // We need to insert empty proxy so that undo will work
2607                     oldProps.insert("proxy", QString());
2608                 }
2609                 new EditClipCommand(this, item->clipId(), oldProps, newProps, true, command);
2610             }
2611         }
2612     }
2613     if (command->childCount() > 0) {
2614         m_doc->commandStack()->push(command);
2615     }
2616     else delete command;
2617 }
2618
2619
2620 void ProjectList::slotDeleteProxy(const QString proxyPath)
2621 {
2622     if (proxyPath.isEmpty()) return;
2623     QUndoCommand *proxyCommand = new QUndoCommand();
2624     proxyCommand->setText(i18n("Remove Proxy"));
2625     QTreeWidgetItemIterator it(m_listView);
2626     ProjectItem *item;
2627     while (*it) {
2628         if ((*it)->type() == PROJECTCLIPTYPE) {
2629             item = static_cast <ProjectItem *>(*it);
2630             if (item->referencedClip()->getProperty("proxy") == proxyPath) {
2631                 QMap <QString, QString> props;
2632                 props.insert("proxy", QString());
2633                 new EditClipCommand(this, item->clipId(), item->referencedClip()->properties(), props, true, proxyCommand);
2634             
2635             }
2636         }
2637         ++it;
2638     }
2639     if (proxyCommand->childCount() == 0)
2640         delete proxyCommand;
2641     else
2642         m_commandStack->push(proxyCommand);
2643     QFile::remove(proxyPath);
2644 }
2645
2646 void ProjectList::setProxyStatus(const QString proxyPath, PROXYSTATUS status, int progress)
2647 {
2648     if (proxyPath.isEmpty() || m_abortAllProxies) return;
2649     QTreeWidgetItemIterator it(m_listView);
2650     ProjectItem *item;
2651     while (*it) {
2652         if ((*it)->type() == PROJECTCLIPTYPE) {
2653             item = static_cast <ProjectItem *>(*it);
2654             if (item->referencedClip()->getProperty("proxy") == proxyPath) {
2655                 setProxyStatus(item, status, progress);
2656             }
2657         }
2658         ++it;
2659     }
2660 }
2661
2662 void ProjectList::setProxyStatus(ProjectItem *item, PROXYSTATUS status, int progress)
2663 {
2664     if (item == NULL) return;
2665     monitorItemEditing(false);
2666     item->setProxyStatus(status, progress);
2667     monitorItemEditing(true);
2668 }
2669
2670 void ProjectList::monitorItemEditing(bool enable)
2671 {
2672     if (enable) connect(m_listView, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this, SLOT(slotItemEdited(QTreeWidgetItem *, int)));     
2673     else disconnect(m_listView, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this, SLOT(slotItemEdited(QTreeWidgetItem *, int)));     
2674 }
2675
2676 QStringList ProjectList::expandedFolders() const
2677 {
2678     QStringList result;
2679     FolderProjectItem *item;
2680     QTreeWidgetItemIterator it(m_listView);
2681     while (*it) {
2682         if ((*it)->type() != PROJECTFOLDERTYPE) {
2683             ++it;
2684             continue;
2685         }
2686         if ((*it)->isExpanded()) {
2687             item = static_cast<FolderProjectItem *>(*it);
2688             result.append(item->clipId());
2689         }
2690         ++it;
2691     }
2692     return result;
2693 }
2694
2695 #include "projectlist.moc"