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