]> git.sesse.net Git - kdenlive/blob - src/projectlist.cpp
Fix white thumbnails in timeline when audio only copy of clip was in timeline
[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, const QString)), this, SLOT(slotAbortProxy(const QString, 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());
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 &proxyPath)
1076 {
1077     if (proxyPath.isEmpty()) return;
1078     QTreeWidgetItemIterator it(m_listView);
1079     ProjectItem *item;
1080
1081     while (*it) {
1082         if ((*it)->type() == PROJECTCLIPTYPE) {
1083             item = static_cast <ProjectItem *>(*it);
1084             if (item->referencedClip()->getProperty("proxy") == proxyPath)
1085                 slotGotProxy(item);
1086         }
1087         ++it;
1088     }
1089 }
1090
1091 void ProjectList::slotGotProxy(ProjectItem *item)
1092 {
1093     if (item == NULL) return;
1094     DocClipBase *clip = item->referencedClip();
1095     // Proxy clip successfully created
1096     QDomElement e = clip->toXML().cloneNode().toElement();
1097
1098     // Make sure we get the correct producer length if it was adjusted in timeline
1099     CLIPTYPE t = item->clipType();
1100     if (t == COLOR || t == IMAGE || t == SLIDESHOW || t == TEXT) {
1101         int length = QString(clip->producerProperty("length")).toInt();
1102         if (length > 0 && !e.hasAttribute("length")) {
1103             e.setAttribute("length", length);
1104         }
1105     }
1106     e.setAttribute("replace", 1);
1107     m_infoQueue.insert(clip->getId(), e);
1108     if (!m_queueRunner.isRunning() && m_processingClips.isEmpty()) m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);   
1109 }
1110
1111 void ProjectList::slotResetProjectList()
1112 {
1113     m_listView->clear();
1114     emit clipSelected(NULL);
1115     m_thumbnailQueue.clear();
1116     m_infoQueue.clear();
1117     m_refreshed = false;
1118 }
1119
1120 void ProjectList::requestClipInfo(const QDomElement xml, const QString id)
1121 {
1122     m_infoQueue.insert(id, xml);
1123     //if (m_infoQueue.count() == 1 || ) QTimer::singleShot(300, this, SLOT(slotProcessNextClipInQueue()));
1124 }
1125
1126 void ProjectList::slotProcessNextClipInQueue()
1127 {
1128     if (m_infoQueue.isEmpty()) {
1129         emit processNextThumbnail();
1130         return;
1131     }
1132
1133     QMap<QString, QDomElement>::const_iterator j = m_infoQueue.constBegin();
1134     if (j != m_infoQueue.constEnd()) {
1135         QDomElement dom = j.value();
1136         const QString id = j.key();
1137         m_infoQueue.remove(id);
1138         m_processingClips.append(id);
1139         bool replace;
1140         if (dom.hasAttribute("replace")) {
1141             // Proxy action was enabled / disabled and we want to replace current producer
1142             dom.removeAttribute("replace");
1143             replace = true;
1144         }
1145         else replace = false;
1146         bool selectClip = !replace;
1147         if (m_infoQueue.count() > 1) selectClip = false;
1148         emit getFileProperties(dom, id, m_listView->iconSize().height(), replace, selectClip);
1149     }
1150 }
1151
1152 void ProjectList::slotUpdateClip(const QString &id)
1153 {
1154     ProjectItem *item = getItemById(id);
1155     monitorItemEditing(false);
1156     if (item) item->setData(0, UsageRole, QString::number(item->numReferences()));
1157     monitorItemEditing(true);
1158 }
1159
1160 void ProjectList::updateAllClips(bool displayRatioChanged, bool fpsChanged)
1161 {
1162     m_listView->setSortingEnabled(false);
1163
1164     QTreeWidgetItemIterator it(m_listView);
1165     DocClipBase *clip;
1166     ProjectItem *item;
1167     monitorItemEditing(false);
1168     int height = m_listView->iconSize().height();
1169     int width = (int)(height  * m_render->dar());
1170     QPixmap missingPixmap = QPixmap(width, height);
1171     missingPixmap.fill(Qt::transparent);
1172     KIcon icon("dialog-close");
1173     QPainter p(&missingPixmap);
1174     p.drawPixmap(3, 3, icon.pixmap(width - 6, height - 6));
1175     p.end();
1176                         
1177     while (*it) {
1178         if ((*it)->type() == PROJECTSUBCLIPTYPE) {
1179             // subitem
1180             SubProjectItem *sub = static_cast <SubProjectItem *>(*it);
1181             if (displayRatioChanged || sub->data(0, Qt::DecorationRole).isNull()) {
1182                 item = static_cast <ProjectItem *>((*it)->parent());
1183                 requestClipThumbnail(item->clipId() + '#' + QString::number(sub->zone().x()));
1184             }
1185             ++it;
1186             continue;
1187         } else if ((*it)->type() == PROJECTFOLDERTYPE) {
1188             // folder
1189             ++it;
1190             continue;
1191         } else {
1192             item = static_cast <ProjectItem *>(*it);
1193             clip = item->referencedClip();
1194             if (item->referencedClip()->producer() == NULL) {
1195                 if (clip->isPlaceHolder() == false) {
1196                     QDomElement xml = clip->toXML();
1197                     if (fpsChanged) {
1198                         xml.removeAttribute("out");
1199                         xml.removeAttribute("file_hash");
1200                         xml.removeAttribute("proxy_out");
1201                     }
1202                     requestClipInfo(xml, clip->getId());
1203                 }
1204                 else {
1205                     item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsDropEnabled);
1206                     if (item->data(0, Qt::DecorationRole).isNull()) {
1207                         item->setData(0, Qt::DecorationRole, missingPixmap);
1208                     }
1209                     else {
1210                         QPixmap pixmap = qVariantValue<QPixmap>(item->data(0, Qt::DecorationRole));
1211                         QPainter p(&pixmap);
1212                         p.drawPixmap(3, 3, KIcon("dialog-close").pixmap(pixmap.width() - 6, pixmap.height() - 6));
1213                         p.end();
1214                         item->setData(0, Qt::DecorationRole, pixmap);
1215                     }
1216                 }
1217             } else {
1218                 if (displayRatioChanged || item->data(0, Qt::DecorationRole).isNull())
1219                     requestClipThumbnail(clip->getId());
1220                 if (item->data(0, DurationRole).toString().isEmpty()) {
1221                     item->changeDuration(item->referencedClip()->producer()->get_playtime());
1222                 }
1223                 if (clip->isPlaceHolder()) {
1224                     QPixmap pixmap = qVariantValue<QPixmap>(item->data(0, Qt::DecorationRole));
1225                     if (pixmap.isNull()) {
1226                         pixmap = QPixmap(width, height);
1227                         pixmap.fill(Qt::transparent);
1228                     }
1229                     QPainter p(&pixmap);
1230                     p.drawPixmap(3, 3, KIcon("dialog-close").pixmap(pixmap.width() - 6, pixmap.height() - 6));
1231                     p.end();
1232                     item->setData(0, Qt::DecorationRole, pixmap);
1233                 }
1234             }
1235             item->setData(0, UsageRole, QString::number(item->numReferences()));
1236         }
1237         ++it;
1238     }
1239
1240     if (!m_queueRunner.isRunning() && m_processingClips.isEmpty()) m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
1241     if (m_listView->isEnabled())
1242         monitorItemEditing(true);
1243     m_listView->setSortingEnabled(true);
1244     if (m_infoQueue.isEmpty()) {
1245        slotProcessNextThumbnail();
1246     }
1247 }
1248
1249 // static
1250 QString ProjectList::getExtensions()
1251 {
1252     // Build list of mime types
1253     QStringList mimeTypes = QStringList() << "application/x-kdenlive" << "application/x-kdenlivetitle" << "video/mlt-playlist" << "text/plain"
1254                             << "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"
1255                             << "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"
1256                             << "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";
1257
1258     QString allExtensions;
1259     foreach(const QString & mimeType, mimeTypes) {
1260         KMimeType::Ptr mime(KMimeType::mimeType(mimeType));
1261         if (mime) {
1262             allExtensions.append(mime->patterns().join(" "));
1263             allExtensions.append(' ');
1264         }
1265     }
1266     return allExtensions.simplified();
1267 }
1268
1269 void ProjectList::slotAddClip(const QList <QUrl> givenList, const QString &groupName, const QString &groupId)
1270 {
1271     if (!m_commandStack)
1272         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1273
1274     KUrl::List list;
1275     if (givenList.isEmpty()) {
1276         QString allExtensions = getExtensions();
1277         const QString dialogFilter = allExtensions + ' ' + QLatin1Char('|') + i18n("All Supported Files") + "\n* " + QLatin1Char('|') + i18n("All Files");
1278         QCheckBox *b = new QCheckBox(i18n("Import image sequence"));
1279         b->setChecked(KdenliveSettings::autoimagesequence());
1280         QCheckBox *c = new QCheckBox(i18n("Transparent background for images"));
1281         c->setChecked(KdenliveSettings::autoimagetransparency());
1282         QFrame *f = new QFrame;
1283         f->setFrameShape(QFrame::NoFrame);
1284         QHBoxLayout *l = new QHBoxLayout;
1285         l->addWidget(b);
1286         l->addWidget(c);
1287         l->addStretch(5);
1288         f->setLayout(l);
1289         KFileDialog *d = new KFileDialog(KUrl("kfiledialog:///clipfolder"), dialogFilter, kapp->activeWindow(), f);
1290         d->setOperationMode(KFileDialog::Opening);
1291         d->setMode(KFile::Files);
1292         if (d->exec() == QDialog::Accepted) {
1293             KdenliveSettings::setAutoimagetransparency(c->isChecked());
1294         }
1295         list = d->selectedUrls();
1296         if (b->isChecked() && list.count() == 1) {
1297             // Check for image sequence
1298             KUrl url = list.at(0);
1299             QString fileName = url.fileName().section('.', 0, -2);
1300             if (fileName.at(fileName.size() - 1).isDigit()) {
1301                 KFileItem item(KFileItem::Unknown, KFileItem::Unknown, url);
1302                 if (item.mimetype().startsWith("image")) {
1303                     // import as sequence if we found more than one image in the sequence
1304                     QStringList list;
1305                     QString pattern = SlideshowClip::selectedPath(url.path(), false, QString(), &list);
1306                     int count = list.count();
1307                     if (count > 1) {
1308                         delete d;
1309                         QStringList groupInfo = getGroup();
1310
1311                         // get image sequence base name
1312                         while (fileName.at(fileName.size() - 1).isDigit()) {
1313                             fileName.chop(1);
1314                         }
1315
1316                         m_doc->slotCreateSlideshowClipFile(fileName, pattern, count, m_timecode.reformatSeparators(KdenliveSettings::sequence_duration()),
1317                                                            false, false, false,
1318                                                            m_timecode.getTimecodeFromFrames(int(ceil(m_timecode.fps()))), QString(), 0,
1319                                                            QString(), groupInfo.at(0), groupInfo.at(1));
1320                         return;
1321                     }
1322                 }
1323             }
1324         }
1325         delete d;
1326     } else {
1327         for (int i = 0; i < givenList.count(); i++)
1328             list << givenList.at(i);
1329     }
1330
1331     foreach(const KUrl & file, list) {
1332         // Check there is no folder here
1333         KMimeType::Ptr type = KMimeType::findByUrl(file);
1334         if (type->is("inode/directory")) {
1335             // user dropped a folder
1336             list.removeAll(file);
1337         }
1338     }
1339
1340     if (list.isEmpty())
1341         return;
1342
1343     if (givenList.isEmpty()) {
1344         QStringList groupInfo = getGroup();
1345         m_doc->slotAddClipList(list, groupInfo.at(0), groupInfo.at(1));
1346     } else {
1347         m_doc->slotAddClipList(list, groupName, groupId);
1348     }
1349 }
1350
1351 void ProjectList::slotRemoveInvalidClip(const QString &id, bool replace)
1352 {
1353     ProjectItem *item = getItemById(id);
1354     m_processingClips.removeAll(id);
1355     m_thumbnailQueue.removeAll(id);
1356     if (!m_queueRunner.isRunning() && m_processingClips.isEmpty()) m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
1357     if (item) {
1358         const QString path = item->referencedClip()->fileURL().path();
1359         if (item->referencedClip()->isPlaceHolder()) replace = false;
1360         if (!path.isEmpty()) {
1361             if (replace)
1362                 KMessageBox::sorry(kapp->activeWindow(), i18n("Clip <b>%1</b><br />is invalid, will be removed from project.", path));
1363             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)
1364                 replace = true;
1365         }
1366         if (replace)
1367             emit deleteProjectClips(QStringList() << id, QMap <QString, QString>());
1368     }
1369 }
1370
1371 void ProjectList::slotRemoveInvalidProxy(const QString &id, bool durationError)
1372 {
1373     ProjectItem *item = getItemById(id);
1374     if (item) {
1375         if (durationError) {
1376             kDebug() << "Proxy duration is wrong, try changing transcoding parameters.";
1377             emit displayMessage(i18n("Proxy clip unusable (duration is different from original)."), -2);
1378         }
1379         item->setProxyStatus(PROXYCRASHED);
1380         QString path = item->referencedClip()->getProperty("proxy");
1381         KUrl proxyFolder(m_doc->projectFolder().path( KUrl::AddTrailingSlash) + "proxy/");
1382
1383         //Security check: make sure the invalid proxy file is in the proxy folder
1384         if (proxyFolder.isParentOf(KUrl(path))) {
1385             QFile::remove(path);
1386         }
1387     }
1388     m_processingClips.removeAll(id);
1389     m_thumbnailQueue.removeAll(id);
1390     if (!m_queueRunner.isRunning() && m_processingClips.isEmpty()) m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
1391 }
1392
1393 void ProjectList::slotAddColorClip()
1394 {
1395     if (!m_commandStack)
1396         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1397
1398     QDialog *dia = new QDialog(this);
1399     Ui::ColorClip_UI dia_ui;
1400     dia_ui.setupUi(dia);
1401     dia->setWindowTitle(i18n("Color Clip"));
1402     dia_ui.clip_name->setText(i18n("Color Clip"));
1403
1404     TimecodeDisplay *t = new TimecodeDisplay(m_timecode);
1405     t->setValue(KdenliveSettings::color_duration());
1406     t->setTimeCodeFormat(false);
1407     dia_ui.clip_durationBox->addWidget(t);
1408     dia_ui.clip_color->setColor(KdenliveSettings::colorclipcolor());
1409
1410     if (dia->exec() == QDialog::Accepted) {
1411         QString color = dia_ui.clip_color->color().name();
1412         KdenliveSettings::setColorclipcolor(color);
1413         color = color.replace(0, 1, "0x") + "ff";
1414         QStringList groupInfo = getGroup();
1415         m_doc->slotCreateColorClip(dia_ui.clip_name->text(), color, m_timecode.getTimecode(t->gentime()), groupInfo.at(0), groupInfo.at(1));
1416     }
1417     delete t;
1418     delete dia;
1419 }
1420
1421
1422 void ProjectList::slotAddSlideshowClip()
1423 {
1424     if (!m_commandStack)
1425         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1426
1427     SlideshowClip *dia = new SlideshowClip(m_timecode, this);
1428
1429     if (dia->exec() == QDialog::Accepted) {
1430         QStringList groupInfo = getGroup();
1431         m_doc->slotCreateSlideshowClipFile(dia->clipName(), dia->selectedPath(), dia->imageCount(), dia->clipDuration(),
1432                                            dia->loop(), dia->crop(), dia->fade(),
1433                                            dia->lumaDuration(), dia->lumaFile(), dia->softness(),
1434                                            dia->animation(), groupInfo.at(0), groupInfo.at(1));
1435     }
1436     delete dia;
1437 }
1438
1439 void ProjectList::slotAddTitleClip()
1440 {
1441     QStringList groupInfo = getGroup();
1442     m_doc->slotCreateTextClip(groupInfo.at(0), groupInfo.at(1));
1443 }
1444
1445 void ProjectList::slotAddTitleTemplateClip()
1446 {
1447     if (!m_commandStack)
1448         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1449
1450     QStringList groupInfo = getGroup();
1451
1452     // Get the list of existing templates
1453     QStringList filter;
1454     filter << "*.kdenlivetitle";
1455     const QString path = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1456     QStringList templateFiles = QDir(path).entryList(filter, QDir::Files);
1457
1458     QDialog *dia = new QDialog(this);
1459     Ui::TemplateClip_UI dia_ui;
1460     dia_ui.setupUi(dia);
1461     for (int i = 0; i < templateFiles.size(); ++i)
1462         dia_ui.template_list->comboBox()->addItem(templateFiles.at(i), path + templateFiles.at(i));
1463
1464     if (!templateFiles.isEmpty())
1465         dia_ui.buttonBox->button(QDialogButtonBox::Ok)->setFocus();
1466     dia_ui.template_list->fileDialog()->setFilter("application/x-kdenlivetitle");
1467     //warning: setting base directory doesn't work??
1468     KUrl startDir(path);
1469     dia_ui.template_list->fileDialog()->setUrl(startDir);
1470     dia_ui.text_box->setHidden(true);
1471     if (dia->exec() == QDialog::Accepted) {
1472         QString textTemplate = dia_ui.template_list->comboBox()->itemData(dia_ui.template_list->comboBox()->currentIndex()).toString();
1473         if (textTemplate.isEmpty()) textTemplate = dia_ui.template_list->comboBox()->currentText();
1474         // Create a cloned template clip
1475         m_doc->slotCreateTextTemplateClip(groupInfo.at(0), groupInfo.at(1), KUrl(textTemplate));
1476     }
1477     delete dia;
1478 }
1479
1480 QStringList ProjectList::getGroup() const
1481 {
1482     QStringList result;
1483     QTreeWidgetItem *item = m_listView->currentItem();
1484     while (item && item->type() != PROJECTFOLDERTYPE)
1485         item = item->parent();
1486
1487     if (item) {
1488         FolderProjectItem *folder = static_cast <FolderProjectItem *>(item);
1489         result << folder->groupName() << folder->clipId();
1490     } else {
1491         result << QString() << QString();
1492     }
1493     return result;
1494 }
1495
1496 void ProjectList::setDocument(KdenliveDoc *doc)
1497 {
1498     m_listView->blockSignals(true);
1499     m_listView->clear();
1500     m_processingClips.clear();
1501     m_listView->setSortingEnabled(false);
1502     emit clipSelected(NULL);
1503     m_thumbnailQueue.clear();
1504     m_infoQueue.clear();
1505     m_refreshed = false;
1506     m_fps = doc->fps();
1507     m_timecode = doc->timecode();
1508     m_commandStack = doc->commandStack();
1509     m_doc = doc;
1510
1511     QMap <QString, QString> flist = doc->clipManager()->documentFolderList();
1512     QStringList openedFolders = doc->getExpandedFolders();
1513     QMapIterator<QString, QString> f(flist);
1514     while (f.hasNext()) {
1515         f.next();
1516         FolderProjectItem *folder = new FolderProjectItem(m_listView, QStringList() << f.value(), f.key());
1517         folder->setExpanded(openedFolders.contains(f.key()));
1518     }
1519
1520     QList <DocClipBase*> list = doc->clipManager()->documentClipList();
1521     for (int i = 0; i < list.count(); i++)
1522         slotAddClip(list.at(i), false);
1523
1524     m_listView->blockSignals(false);
1525     connect(m_doc->clipManager(), SIGNAL(reloadClip(const QString &)), this, SLOT(slotReloadClip(const QString &)));
1526     connect(m_doc->clipManager(), SIGNAL(modifiedClip(const QString &)), this, SLOT(slotModifiedClip(const QString &)));
1527     connect(m_doc->clipManager(), SIGNAL(missingClip(const QString &)), this, SLOT(slotMissingClip(const QString &)));
1528     connect(m_doc->clipManager(), SIGNAL(availableClip(const QString &)), this, SLOT(slotAvailableClip(const QString &)));
1529     connect(m_doc->clipManager(), SIGNAL(checkAllClips(bool, bool)), this, SLOT(updateAllClips(bool, bool)));
1530 }
1531
1532 QList <DocClipBase*> ProjectList::documentClipList() const
1533 {
1534     if (m_doc == NULL)
1535         return QList <DocClipBase*> ();
1536
1537     return m_doc->clipManager()->documentClipList();
1538 }
1539
1540 QDomElement ProjectList::producersList()
1541 {
1542     QDomDocument doc;
1543     QDomElement prods = doc.createElement("producerlist");
1544     doc.appendChild(prods);
1545     kDebug() << "////////////  PRO LIST BUILD PRDSLIST ";
1546     QTreeWidgetItemIterator it(m_listView);
1547     while (*it) {
1548         if ((*it)->type() != PROJECTCLIPTYPE) {
1549             // subitem
1550             ++it;
1551             continue;
1552         }
1553         prods.appendChild(doc.importNode(((ProjectItem *)(*it))->toXml(), true));
1554         ++it;
1555     }
1556     return prods;
1557 }
1558
1559 void ProjectList::slotCheckForEmptyQueue()
1560 {
1561     if (!m_refreshed && m_processingClips.isEmpty() && m_thumbnailQueue.isEmpty() && m_infoQueue.isEmpty()) {
1562         m_refreshed = true;
1563         emit loadingIsOver();
1564         emit displayMessage(QString(), -1);
1565         m_listView->blockSignals(false);
1566         m_listView->setEnabled(true);
1567         updateButtons();
1568     } else if (!m_refreshed) {
1569         QTimer::singleShot(300, this, SLOT(slotCheckForEmptyQueue()));
1570     }
1571 }
1572
1573
1574 void ProjectList::requestClipThumbnail(const QString id)
1575 {
1576     if (!m_thumbnailQueue.contains(id)) m_thumbnailQueue.append(id);
1577 }
1578
1579 void ProjectList::slotProcessNextThumbnail()
1580 {
1581     if (m_thumbnailQueue.isEmpty() && m_infoQueue.isEmpty()) {
1582         slotCheckForEmptyQueue();
1583         return;
1584     }
1585     if (!m_infoQueue.isEmpty()) {
1586         //QTimer::singleShot(300, this, SLOT(slotProcessNextThumbnail()));
1587         return;
1588     }
1589     if (m_thumbnailQueue.count() > 1) {
1590         int max = m_doc->clipManager()->clipsCount();
1591         emit displayMessage(i18n("Loading thumbnails"), (int)(100 *(max - m_thumbnailQueue.count()) / max));
1592     }
1593     slotRefreshClipThumbnail(m_thumbnailQueue.takeFirst(), false);
1594 }
1595
1596 void ProjectList::slotRefreshClipThumbnail(const QString &clipId, bool update)
1597 {
1598     QTreeWidgetItem *item = getAnyItemById(clipId);
1599     if (item)
1600         slotRefreshClipThumbnail(item, update);
1601     else {
1602         slotProcessNextThumbnail();
1603     }
1604 }
1605
1606 void ProjectList::slotRefreshClipThumbnail(QTreeWidgetItem *it, bool update)
1607 {
1608     if (it == NULL) return;
1609     ProjectItem *item = NULL;
1610     bool isSubItem = false;
1611     int frame;
1612     if (it->type() == PROJECTFOLDERTYPE) return;
1613     if (it->type() == PROJECTSUBCLIPTYPE) {
1614         item = static_cast <ProjectItem *>(it->parent());
1615         frame = static_cast <SubProjectItem *>(it)->zone().x();
1616         isSubItem = true;
1617     } else {
1618         item = static_cast <ProjectItem *>(it);
1619         frame = item->referencedClip()->getClipThumbFrame();
1620     }
1621
1622     if (item) {
1623         DocClipBase *clip = item->referencedClip();
1624         if (!clip) {
1625             slotProcessNextThumbnail();
1626             return;
1627         }
1628         QPixmap pix;
1629         int height = m_listView->iconSize().height();
1630         int width = (int)(height  * m_render->dar());
1631         if (clip->clipType() == AUDIO)
1632             pix = KIcon("audio-x-generic").pixmap(QSize(width, height));
1633         else if (clip->clipType() == IMAGE)
1634             pix = QPixmap::fromImage(KThumb::getFrame(item->referencedClip()->producer(), 0, width, height));
1635         else
1636             pix = item->referencedClip()->extractImage(frame, width, height);
1637
1638         if (!pix.isNull()) {
1639             monitorItemEditing(false);
1640             it->setData(0, Qt::DecorationRole, pix);
1641             monitorItemEditing(true);
1642                 
1643             if (!isSubItem)
1644                 m_doc->cachePixmap(item->getClipHash(), pix);
1645             else
1646                 m_doc->cachePixmap(item->getClipHash() + '#' + QString::number(frame), pix);
1647         }
1648         if (update)
1649             emit projectModified();
1650         slotProcessNextThumbnail();
1651     }
1652 }
1653
1654 void ProjectList::slotReplyGetFileProperties(const QString &clipId, Mlt::Producer *producer, const QMap < QString, QString > &properties, const QMap < QString, QString > &metadata, bool replace, bool selectClip)
1655 {
1656     QString toReload;
1657     ProjectItem *item = getItemById(clipId);
1658     if (!m_refreshed) {
1659         // we are still finishing to load the document
1660         selectClip = false;
1661     }
1662     m_processingClips.removeAll(clipId);
1663     if (m_infoQueue.isEmpty() && m_processingClips.isEmpty()) m_listView->setEnabled(true);
1664
1665     if (item && producer) {
1666         //m_listView->blockSignals(true);
1667         monitorItemEditing(false);
1668         DocClipBase *clip = item->referencedClip();
1669         item->setProperties(properties, metadata);
1670         if (clip->isPlaceHolder() && producer->is_valid()) {
1671             clip->setValid();
1672             item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsDropEnabled);
1673             toReload = clipId;
1674         }
1675         // Proxy stuff
1676         QString size = properties.value("frame_size");
1677         if (!useProxy() && clip->getProperty("proxy").isEmpty()) setProxyStatus(item, NOPROXY);
1678         if (useProxy() && generateProxy() && clip->getProperty("proxy") == "-") setProxyStatus(item, NOPROXY);
1679         else if (useProxy() && !item->isProxyRunning()) {
1680             // proxy video and image clips
1681             int maxSize;
1682             CLIPTYPE t = item->clipType();
1683             if (t == IMAGE) maxSize = m_doc->getDocumentProperty("proxyimageminsize").toInt();
1684             else maxSize = m_doc->getDocumentProperty("proxyminsize").toInt();
1685             if ((((t == AV || t == VIDEO || t == PLAYLIST) && generateProxy()) || (t == IMAGE && generateImageProxy())) && (size.section('x', 0, 0).toInt() > maxSize || size.section('x', 1, 1).toInt() > maxSize)) {
1686                 if (clip->getProperty("proxy").isEmpty()) {
1687                     KUrl proxyPath = m_doc->projectFolder();
1688                     proxyPath.addPath("proxy/");
1689                     proxyPath.addPath(clip->getClipHash() + "." + (t == IMAGE ? "png" : m_doc->getDocumentProperty("proxyextension")));
1690                     QMap <QString, QString> newProps;
1691                     // insert required duration for proxy
1692                     if (t != IMAGE) newProps.insert("proxy_out", clip->producerProperty("out"));
1693                     newProps.insert("proxy", proxyPath.path());
1694                     QMap <QString, QString> oldProps = clip->properties();
1695                     oldProps.insert("proxy", QString());
1696                     EditClipCommand *command = new EditClipCommand(this, clipId, oldProps, newProps, true);
1697                     m_doc->commandStack()->push(command);
1698                 }
1699             }
1700         }
1701         clip->setProducer(producer, replace);
1702         clip->askForAudioThumbs();
1703
1704         if (!replace && item->data(0, Qt::DecorationRole).isNull())
1705             requestClipThumbnail(clipId);
1706         if (!toReload.isEmpty())
1707             item->slotSetToolTip();
1708
1709         if (m_listView->isEnabled())
1710             monitorItemEditing(true);
1711     } else kDebug() << "////////  COULD NOT FIND CLIP TO UPDATE PRPS...";
1712     if (selectClip && m_infoQueue.isEmpty()) {
1713         if (item && m_infoQueue.isEmpty() && m_thumbnailQueue.isEmpty()) {
1714             m_listView->setCurrentItem(item);
1715             bool updatedProfile = false;
1716             if (item->parent()) {
1717                 if (item->parent()->type() == PROJECTFOLDERTYPE)
1718                     static_cast <FolderProjectItem *>(item->parent())->switchIcon();
1719             } else if (KdenliveSettings::checkfirstprojectclip() &&  m_listView->topLevelItemCount() == 1) {
1720                 // this is the first clip loaded in project, check if we want to adjust project settings to the clip
1721                 updatedProfile = adjustProjectProfileToItem(item);
1722             }
1723             if (updatedProfile == false) emit clipSelected(item->referencedClip());
1724         } else {
1725             int max = m_doc->clipManager()->clipsCount();
1726             emit displayMessage(i18n("Loading clips"), (int)(100 *(max - m_infoQueue.count()) / max));
1727         }
1728     }
1729     if (item && m_listView->isEnabled() && replace) {
1730             // update clip in clip monitor
1731             if (item->isSelected() && m_listView->selectedItems().count() == 1)
1732                 emit clipSelected(item->referencedClip());
1733             //TODO: Make sure the line below has no side effect
1734             toReload = clipId;
1735         }
1736     if (!toReload.isEmpty())
1737         emit clipNeedsReload(toReload, true);
1738
1739     if (!m_queueRunner.isRunning() && m_processingClips.isEmpty()) m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
1740 }
1741
1742 bool ProjectList::adjustProjectProfileToItem(ProjectItem *item)
1743 {
1744     if (item == NULL) {
1745         if (m_listView->currentItem() && m_listView->currentItem()->type() != PROJECTFOLDERTYPE)
1746             item = static_cast <ProjectItem*>(m_listView->currentItem());
1747     }
1748     if (item == NULL || item->referencedClip() == NULL) {
1749         KMessageBox::information(kapp->activeWindow(), i18n("Cannot find profile from current clip"));
1750         return false;
1751     }
1752     bool profileUpdated = false;
1753     QString size = item->referencedClip()->getProperty("frame_size");
1754     int width = size.section('x', 0, 0).toInt();
1755     int height = size.section('x', -1).toInt();
1756     double fps = item->referencedClip()->getProperty("fps").toDouble();
1757     double par = item->referencedClip()->getProperty("aspect_ratio").toDouble();
1758     if (item->clipType() == IMAGE || item->clipType() == AV || item->clipType() == VIDEO) {
1759         if (ProfilesDialog::matchProfile(width, height, fps, par, item->clipType() == IMAGE, m_doc->mltProfile()) == false) {
1760             // get a list of compatible profiles
1761             QMap <QString, QString> suggestedProfiles = ProfilesDialog::getProfilesFromProperties(width, height, fps, par, item->clipType() == IMAGE);
1762             if (!suggestedProfiles.isEmpty()) {
1763                 KDialog *dialog = new KDialog(this);
1764                 dialog->setCaption(i18n("Change project profile"));
1765                 dialog->setButtons(KDialog::Ok | KDialog::Cancel);
1766
1767                 QWidget container;
1768                 QVBoxLayout *l = new QVBoxLayout;
1769                 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));
1770                 l->addWidget(label);
1771                 QListWidget *list = new QListWidget;
1772                 list->setAlternatingRowColors(true);
1773                 QMapIterator<QString, QString> i(suggestedProfiles);
1774                 while (i.hasNext()) {
1775                     i.next();
1776                     QListWidgetItem *item = new QListWidgetItem(i.value(), list);
1777                     item->setData(Qt::UserRole, i.key());
1778                     item->setToolTip(i.key());
1779                 }
1780                 list->setCurrentRow(0);
1781                 l->addWidget(list);
1782                 container.setLayout(l);
1783                 dialog->setButtonText(KDialog::Ok, i18n("Update profile"));
1784                 dialog->setMainWidget(&container);
1785                 if (dialog->exec() == QDialog::Accepted) {
1786                     //Change project profile
1787                     profileUpdated = true;
1788                     if (list->currentItem())
1789                         emit updateProfile(list->currentItem()->data(Qt::UserRole).toString());
1790                 }
1791                 delete list;
1792                 delete label;
1793             } else if (fps > 0) {
1794                 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));
1795             }
1796         }
1797     }
1798     return profileUpdated;
1799 }
1800
1801 QString ProjectList::getDocumentProperty(const QString &key) const
1802 {
1803     return m_doc->getDocumentProperty(key);
1804 }
1805
1806 bool ProjectList::useProxy() const
1807 {
1808     return m_doc->getDocumentProperty("enableproxy").toInt();
1809 }
1810
1811 bool ProjectList::generateProxy() const
1812 {
1813     return m_doc->getDocumentProperty("generateproxy").toInt();
1814 }
1815
1816 bool ProjectList::generateImageProxy() const
1817 {
1818     return m_doc->getDocumentProperty("generateimageproxy").toInt();
1819 }
1820
1821 void ProjectList::slotReplyGetImage(const QString &clipId, const QPixmap &pix)
1822 {
1823     ProjectItem *item = getItemById(clipId);
1824     if (item && !pix.isNull()) {
1825         monitorItemEditing(false);
1826         item->setData(0, Qt::DecorationRole, pix);
1827         monitorItemEditing(true);
1828         m_doc->cachePixmap(item->getClipHash(), pix);
1829         if (m_listView->isEnabled())
1830             m_listView->blockSignals(false);
1831     }
1832 }
1833
1834 QTreeWidgetItem *ProjectList::getAnyItemById(const QString &id)
1835 {
1836     QTreeWidgetItemIterator it(m_listView);
1837     QString lookId = id;
1838     if (id.contains('#'))
1839         lookId = id.section('#', 0, 0);
1840
1841     ProjectItem *result = NULL;
1842     while (*it) {
1843         if ((*it)->type() != PROJECTCLIPTYPE) {
1844             // subitem
1845             ++it;
1846             continue;
1847         }
1848         ProjectItem *item = static_cast<ProjectItem *>(*it);
1849         if (item->clipId() == lookId) {
1850             result = item;
1851             break;
1852         }
1853         ++it;
1854     }
1855     if (result == NULL || !id.contains('#')) {
1856         return result;
1857     } else {
1858         for (int i = 0; i < result->childCount(); i++) {
1859             SubProjectItem *sub = static_cast <SubProjectItem *>(result->child(i));
1860             if (sub && sub->zone().x() == id.section('#', 1, 1).toInt())
1861                 return sub;
1862         }
1863     }
1864
1865     return NULL;
1866 }
1867
1868
1869 ProjectItem *ProjectList::getItemById(const QString &id)
1870 {
1871     ProjectItem *item;
1872     QTreeWidgetItemIterator it(m_listView);
1873     while (*it) {
1874         if ((*it)->type() != PROJECTCLIPTYPE) {
1875             // subitem or folder
1876             ++it;
1877             continue;
1878         }
1879         item = static_cast<ProjectItem *>(*it);
1880         if (item->clipId() == id)
1881             return item;
1882         ++it;
1883     }
1884     return NULL;
1885 }
1886
1887 FolderProjectItem *ProjectList::getFolderItemById(const QString &id)
1888 {
1889     FolderProjectItem *item;
1890     QTreeWidgetItemIterator it(m_listView);
1891     while (*it) {
1892         if ((*it)->type() == PROJECTFOLDERTYPE) {
1893             item = static_cast<FolderProjectItem *>(*it);
1894             if (item->clipId() == id)
1895                 return item;
1896         }
1897         ++it;
1898     }
1899     return NULL;
1900 }
1901
1902 void ProjectList::slotSelectClip(const QString &ix)
1903 {
1904     ProjectItem *clip = getItemById(ix);
1905     if (clip) {
1906         m_listView->setCurrentItem(clip);
1907         m_listView->scrollToItem(clip);
1908         m_editButton->defaultAction()->setEnabled(true);
1909         m_deleteButton->defaultAction()->setEnabled(true);
1910         m_reloadAction->setEnabled(true);
1911         m_transcodeAction->setEnabled(true);
1912         m_proxyAction->setEnabled(useProxy());
1913         if (clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) {
1914             m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
1915             m_openAction->setEnabled(true);
1916         } else if (clip->clipType() == AUDIO && !KdenliveSettings::defaultaudioapp().isEmpty()) {
1917             m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
1918             m_openAction->setEnabled(true);
1919         } else {
1920             m_openAction->setEnabled(false);
1921         }
1922     }
1923 }
1924
1925 QString ProjectList::currentClipUrl() const
1926 {
1927     ProjectItem *item;
1928     if (!m_listView->currentItem() || m_listView->currentItem()->type() == PROJECTFOLDERTYPE) return QString();
1929     if (m_listView->currentItem()->type() == PROJECTSUBCLIPTYPE) {
1930         // subitem
1931         item = static_cast <ProjectItem*>(m_listView->currentItem()->parent());
1932     } else {
1933         item = static_cast <ProjectItem*>(m_listView->currentItem());
1934     }
1935     if (item == NULL)
1936         return QString();
1937     return item->clipUrl().path();
1938 }
1939
1940 KUrl::List ProjectList::getConditionalUrls(const QString &condition) const
1941 {
1942     KUrl::List result;
1943     ProjectItem *item;
1944     QList<QTreeWidgetItem *> list = m_listView->selectedItems();
1945     for (int i = 0; i < list.count(); i++) {
1946         if (list.at(i)->type() == PROJECTFOLDERTYPE)
1947             continue;
1948         if (list.at(i)->type() == PROJECTSUBCLIPTYPE) {
1949             // subitem
1950             item = static_cast <ProjectItem*>(list.at(i)->parent());
1951         } else {
1952             item = static_cast <ProjectItem*>(list.at(i));
1953         }
1954         if (item == NULL || item->type() == COLOR || item->type() == SLIDESHOW || item->type() == TEXT)
1955             continue;
1956         DocClipBase *clip = item->referencedClip();
1957         if (!condition.isEmpty()) {
1958             if (condition.startsWith("vcodec") && !clip->hasVideoCodec(condition.section('=', 1, 1)))
1959                 continue;
1960             else if (condition.startsWith("acodec") && !clip->hasAudioCodec(condition.section('=', 1, 1)))
1961                 continue;
1962         }
1963         result.append(item->clipUrl());
1964     }
1965     return result;
1966 }
1967
1968 void ProjectList::regenerateTemplate(const QString &id)
1969 {
1970     ProjectItem *clip = getItemById(id);
1971     if (clip)
1972         regenerateTemplate(clip);
1973 }
1974
1975 void ProjectList::regenerateTemplate(ProjectItem *clip)
1976 {
1977     //TODO: remove this unused method, only force_reload is necessary
1978     clip->referencedClip()->producer()->set("force_reload", 1);
1979 }
1980
1981 QDomDocument ProjectList::generateTemplateXml(QString path, const QString &replaceString)
1982 {
1983     QDomDocument doc;
1984     QFile file(path);
1985     if (!file.open(QIODevice::ReadOnly)) {
1986         kWarning() << "ERROR, CANNOT READ: " << path;
1987         return doc;
1988     }
1989     if (!doc.setContent(&file)) {
1990         kWarning() << "ERROR, CANNOT READ: " << path;
1991         file.close();
1992         return doc;
1993     }
1994     file.close();
1995     QDomNodeList texts = doc.elementsByTagName("content");
1996     for (int i = 0; i < texts.count(); i++) {
1997         QString data = texts.item(i).firstChild().nodeValue();
1998         data.replace("%s", replaceString);
1999         texts.item(i).firstChild().setNodeValue(data);
2000     }
2001     return doc;
2002 }
2003
2004
2005 void ProjectList::slotAddClipCut(const QString &id, int in, int out)
2006 {
2007     ProjectItem *clip = getItemById(id);
2008     if (clip == NULL || clip->referencedClip()->hasCutZone(QPoint(in, out)))
2009         return;
2010     AddClipCutCommand *command = new AddClipCutCommand(this, id, in, out, QString(), true, false);
2011     m_commandStack->push(command);
2012 }
2013
2014 void ProjectList::addClipCut(const QString &id, int in, int out, const QString desc, bool newItem)
2015 {
2016     ProjectItem *clip = getItemById(id);
2017     if (clip) {
2018         DocClipBase *base = clip->referencedClip();
2019         base->addCutZone(in, out);
2020         monitorItemEditing(false);
2021         SubProjectItem *sub = new SubProjectItem(clip, in, out, desc);
2022         if (newItem && desc.isEmpty() && !m_listView->isColumnHidden(1)) {
2023             if (!clip->isExpanded())
2024                 clip->setExpanded(true);
2025             m_listView->scrollToItem(sub);
2026             m_listView->editItem(sub, 1);
2027         }
2028         QPixmap p = clip->referencedClip()->extractImage(in, (int)(sub->sizeHint(0).height()  * m_render->dar()), sub->sizeHint(0).height() - 2);
2029         sub->setData(0, Qt::DecorationRole, p);
2030         m_doc->cachePixmap(clip->getClipHash() + '#' + QString::number(in), p);
2031         monitorItemEditing(true);
2032     }
2033     emit projectModified();
2034 }
2035
2036 void ProjectList::removeClipCut(const QString &id, int in, int out)
2037 {
2038     ProjectItem *clip = getItemById(id);
2039     if (clip) {
2040         DocClipBase *base = clip->referencedClip();
2041         base->removeCutZone(in, out);
2042         SubProjectItem *sub = getSubItem(clip, QPoint(in, out));
2043         if (sub) {
2044             monitorItemEditing(false);
2045             delete sub;
2046             monitorItemEditing(true);
2047         }
2048     }
2049     emit projectModified();
2050 }
2051
2052 SubProjectItem *ProjectList::getSubItem(ProjectItem *clip, QPoint zone)
2053 {
2054     SubProjectItem *sub = NULL;
2055     if (clip) {
2056         for (int i = 0; i < clip->childCount(); i++) {
2057             QTreeWidgetItem *it = clip->child(i);
2058             if (it->type() == PROJECTSUBCLIPTYPE) {
2059                 sub = static_cast <SubProjectItem*>(it);
2060                 if (sub->zone() == zone)
2061                     break;
2062                 else
2063                     sub = NULL;
2064             }
2065         }
2066     }
2067     return sub;
2068 }
2069
2070 void ProjectList::slotUpdateClipCut(QPoint p)
2071 {
2072     if (!m_listView->currentItem() || m_listView->currentItem()->type() != PROJECTSUBCLIPTYPE)
2073         return;
2074     SubProjectItem *sub = static_cast <SubProjectItem*>(m_listView->currentItem());
2075     ProjectItem *item = static_cast <ProjectItem *>(sub->parent());
2076     EditClipCutCommand *command = new EditClipCutCommand(this, item->clipId(), sub->zone(), p, sub->text(1), sub->text(1), true);
2077     m_commandStack->push(command);
2078 }
2079
2080 void ProjectList::doUpdateClipCut(const QString &id, const QPoint oldzone, const QPoint zone, const QString &comment)
2081 {
2082     ProjectItem *clip = getItemById(id);
2083     SubProjectItem *sub = getSubItem(clip, oldzone);
2084     if (sub == NULL || clip == NULL)
2085         return;
2086     DocClipBase *base = clip->referencedClip();
2087     base->updateCutZone(oldzone.x(), oldzone.y(), zone.x(), zone.y(), comment);
2088     monitorItemEditing(false);
2089     sub->setZone(zone);
2090     sub->setDescription(comment);
2091     monitorItemEditing(true);
2092     emit projectModified();
2093 }
2094
2095 void ProjectList::slotForceProcessing(const QString &id)
2096 {
2097     while (m_infoQueue.contains(id)) {
2098         slotProcessNextClipInQueue();
2099     }
2100 }
2101
2102 void ProjectList::slotAddOrUpdateSequence(const QString frameName)
2103 {
2104     QString fileName = KUrl(frameName).fileName().section('_', 0, -2);
2105     QStringList list;
2106     QString pattern = SlideshowClip::selectedPath(frameName, false, QString(), &list);
2107     int count = list.count();
2108     if (count > 1) {
2109         const QList <DocClipBase *> existing = m_doc->clipManager()->getClipByResource(pattern);
2110         if (!existing.isEmpty()) {
2111             // Sequence already exists, update
2112             QString id = existing.at(0)->getId();
2113             //ProjectItem *item = getItemById(id);
2114             QMap <QString, QString> oldprops;
2115             QMap <QString, QString> newprops;
2116             int ttl = existing.at(0)->getProperty("ttl").toInt();
2117             oldprops["out"] = existing.at(0)->getProperty("out");
2118             newprops["out"] = QString::number(ttl * count - 1);
2119             slotUpdateClipProperties(id, newprops);
2120             EditClipCommand *command = new EditClipCommand(this, id, oldprops, newprops, false);
2121             m_commandStack->push(command);
2122         } else {
2123             // Create sequence
2124             QStringList groupInfo = getGroup();
2125             m_doc->slotCreateSlideshowClipFile(fileName, pattern, count, m_timecode.reformatSeparators(KdenliveSettings::sequence_duration()),
2126                                                false, false, false,
2127                                                m_timecode.getTimecodeFromFrames(int(ceil(m_timecode.fps()))), QString(), 0,
2128                                                QString(), groupInfo.at(0), groupInfo.at(1));
2129         }
2130     } else emit displayMessage(i18n("Sequence not found"), -2);
2131 }
2132
2133 QMap <QString, QString> ProjectList::getProxies()
2134 {
2135     QMap <QString, QString> list;
2136     ProjectItem *item;
2137     QTreeWidgetItemIterator it(m_listView);
2138     while (*it) {
2139         if ((*it)->type() != PROJECTCLIPTYPE) {
2140             ++it;
2141             continue;
2142         }
2143         item = static_cast<ProjectItem *>(*it);
2144         if (item && item->referencedClip() != NULL) {
2145             if (item->hasProxy()) {
2146                 QString proxy = item->referencedClip()->getProperty("proxy");
2147                 list.insert(proxy, item->clipUrl().path());
2148             }
2149         }
2150         ++it;
2151     }
2152     return list;
2153 }
2154
2155 void ProjectList::slotCreateProxy(const QString id)
2156 {
2157     ProjectItem *item = getItemById(id);
2158     if (!item || item->isProxyRunning() || item->referencedClip()->isPlaceHolder()) return;
2159     QString path = item->referencedClip()->getProperty("proxy");
2160     if (path.isEmpty()) {
2161         setProxyStatus(path, PROXYCRASHED);
2162         return;
2163     }
2164     setProxyStatus(path, PROXYWAITING);
2165     if (m_abortProxy.contains(path)) m_abortProxy.removeAll(path);
2166     if (m_processingProxy.contains(path)) {
2167         // Proxy is already being generated
2168         return;
2169     }
2170     if (QFile::exists(path)) {
2171         // Proxy already created
2172         setProxyStatus(path, PROXYDONE);
2173         slotGotProxy(path);
2174         return;
2175     }
2176     m_processingProxy.append(path);
2177     QtConcurrent::run(this, &ProjectList::slotGenerateProxy, path, item->clipUrl().path(), item->clipType(), QString(item->referencedClip()->producerProperty("_exif_orientation")).toInt());
2178 }
2179
2180 void ProjectList::slotAbortProxy(const QString id, const QString path)
2181 {
2182     QTreeWidgetItemIterator it(m_listView);
2183     ProjectItem *item = getItemById(id);
2184     setProxyStatus(item, NOPROXY);
2185     slotGotProxy(item);
2186     if (!path.isEmpty() && m_processingProxy.contains(path)) {
2187         m_abortProxy << path;
2188         setProxyStatus(path, NOPROXY);
2189     }
2190 }
2191
2192 void ProjectList::slotGenerateProxy(const QString destPath, const QString sourcePath, int clipType, int exif_orientation)
2193 {
2194     emit projectModified();
2195     // Make sure proxy path is writable
2196     QFile file(destPath);
2197     if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
2198         setProxyStatus(destPath, PROXYCRASHED);
2199         return;
2200     }
2201     file.close();
2202     QFile::remove(destPath);
2203     
2204     setProxyStatus(destPath, CREATINGPROXY);
2205
2206     // Special case: playlist clips (.mlt or .kdenlive project files)
2207     if (clipType == PLAYLIST) {
2208         // change FFmpeg params to MLT format
2209         QStringList parameters;
2210         parameters << sourcePath;
2211         parameters << "-consumer" << "avformat:" + destPath;
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         //TODO: currently, when rendering an xml file through melt, the display ration is lost, so we enforce it manualy
2226         double display_ratio = KdenliveDoc::getDisplayRatio(sourcePath);
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_abortProxy.contains(destPath)) {
2237                 myProcess.close();
2238                 myProcess.waitForFinished();
2239                 m_abortProxy.removeAll(destPath);
2240                 m_processingProxy.removeAll(destPath);
2241                 QFile::remove(destPath);
2242                 setProxyStatus(destPath, NOPROXY);
2243                 result = -2;
2244
2245             }
2246             myProcess.waitForFinished(500);
2247         }
2248         myProcess.waitForFinished();
2249         m_processingProxy.removeAll(destPath);
2250         if (result == -1) result = myProcess.exitStatus();
2251         if (result == 0) {
2252             // proxy successfully created
2253             setProxyStatus(destPath, PROXYDONE);
2254             slotGotProxy(destPath);
2255         }
2256         else if (result == 1) {
2257             // Proxy process crashed
2258             QFile::remove(destPath);
2259             setProxyStatus(destPath, PROXYCRASHED);
2260         }   
2261
2262     }
2263     
2264     if (clipType == IMAGE) {
2265         // Image proxy
2266         QImage i(sourcePath);
2267         if (i.isNull()) {
2268             // Cannot load image
2269             setProxyStatus(destPath, PROXYCRASHED);
2270             return;
2271         }
2272         QImage proxy;
2273         // Images are scaled to profile size. 
2274         //TODO: Make it be configurable?
2275         if (i.width() > i.height()) proxy = i.scaledToWidth(m_render->frameRenderWidth());
2276         else proxy = i.scaledToHeight(m_render->renderHeight());
2277         if (exif_orientation > 1) {
2278             // Rotate image according to exif data
2279             QImage processed;
2280             QMatrix matrix;
2281
2282             switch ( exif_orientation ) {
2283                 case 2:
2284                   matrix.scale( -1, 1 );
2285                   break;
2286                 case 3:
2287                   matrix.rotate( 180 );
2288                   break;
2289                 case 4:
2290                   matrix.scale( 1, -1 );
2291                   break;
2292                 case 5:
2293                   matrix.rotate( 270 );
2294                   matrix.scale( -1, 1 );
2295                   break;
2296                 case 6:
2297                   matrix.rotate( 90 );
2298                   break;
2299                 case 7:
2300                   matrix.rotate( 90 );
2301                   matrix.scale( -1, 1 );
2302                   break;
2303                 case 8:
2304                   matrix.rotate( 270 );
2305                   break;
2306               }
2307               processed = proxy.transformed( matrix );
2308               processed.save(destPath);
2309         }
2310         else proxy.save(destPath);
2311         setProxyStatus(destPath, PROXYDONE);
2312         slotGotProxy(destPath);
2313         m_abortProxy.removeAll(destPath);
2314         m_processingProxy.removeAll(destPath);
2315         return;
2316     }
2317
2318     QStringList parameters;
2319     parameters << "-i" << sourcePath;
2320     QString params = m_doc->getDocumentProperty("proxyparams").simplified();
2321     foreach(QString s, params.split(' '))
2322     parameters << s;
2323
2324     // Make sure we don't block when proxy file already exists
2325     parameters << "-y";
2326     parameters << destPath;
2327     kDebug()<<"// STARTING PROXY GEN: "<<parameters;
2328     QProcess myProcess;
2329     myProcess.start("ffmpeg", parameters);
2330     myProcess.waitForStarted();
2331     int result = -1;
2332     while (myProcess.state() != QProcess::NotRunning) {
2333         // building proxy file
2334         if (m_abortProxy.contains(destPath)) {
2335             myProcess.close();
2336             myProcess.waitForFinished();
2337             m_abortProxy.removeAll(destPath);
2338             m_processingProxy.removeAll(destPath);
2339             QFile::remove(destPath);
2340             setProxyStatus(destPath, NOPROXY);
2341             result = -2;
2342             
2343         }
2344         myProcess.waitForFinished(500);
2345     }
2346     myProcess.waitForFinished();
2347     if (result == -1) result = myProcess.exitStatus();
2348     if (result == 0) {
2349         // proxy successfully created
2350         setProxyStatus(destPath, PROXYDONE);
2351         slotGotProxy(destPath);
2352     }
2353     else if (result == 1) {
2354         // Proxy process crashed
2355         QFile::remove(destPath);
2356         setProxyStatus(destPath, PROXYCRASHED);
2357     }
2358     m_abortProxy.removeAll(destPath);
2359     m_processingProxy.removeAll(destPath);
2360 }
2361
2362 void ProjectList::updateProxyConfig()
2363 {
2364     ProjectItem *item;
2365     QTreeWidgetItemIterator it(m_listView);
2366     QUndoCommand *command = new QUndoCommand();
2367     command->setText(i18n("Update proxy settings"));
2368     QString proxydir = m_doc->projectFolder().path( KUrl::AddTrailingSlash) + "proxy/";
2369     while (*it) {
2370         if ((*it)->type() != PROJECTCLIPTYPE) {
2371             ++it;
2372             continue;
2373         }
2374         item = static_cast<ProjectItem *>(*it);
2375         if (item == NULL) {
2376             ++it;
2377             continue;
2378         }
2379         CLIPTYPE t = item->clipType();
2380         if ((t == VIDEO || t == AV || t == UNKNOWN) && item->referencedClip() != NULL) {
2381             if  (generateProxy() && useProxy() && !item->isProxyRunning()) {
2382                 DocClipBase *clip = item->referencedClip();
2383                 if (clip->getProperty("frame_size").section('x', 0, 0).toInt() > m_doc->getDocumentProperty("proxyminsize").toInt()) {
2384                     if (clip->getProperty("proxy").isEmpty()) {
2385                         // We need to insert empty proxy in old properties so that undo will work
2386                         QMap <QString, QString> oldProps = clip->properties();
2387                         oldProps.insert("proxy", QString());
2388                         QMap <QString, QString> newProps;
2389                         newProps.insert("proxy", proxydir + item->referencedClip()->getClipHash() + "." + m_doc->getDocumentProperty("proxyextension"));
2390                         new EditClipCommand(this, clip->getId(), oldProps, newProps, true, command);
2391                     }
2392                 }
2393             }
2394             else if (item->hasProxy()) {
2395                 // remove proxy
2396                 QMap <QString, QString> newProps;
2397                 newProps.insert("proxy", QString());
2398                 newProps.insert("replace", "1");
2399                 // insert required duration for proxy
2400                 newProps.insert("proxy_out", item->referencedClip()->producerProperty("out"));
2401                 new EditClipCommand(this, item->clipId(), item->referencedClip()->properties(), newProps, true, command);
2402             }
2403         }
2404         else if (t == IMAGE && item->referencedClip() != NULL) {
2405             if  (generateImageProxy() && useProxy()) {
2406                 DocClipBase *clip = item->referencedClip();
2407                 int maxImageSize = m_doc->getDocumentProperty("proxyimageminsize").toInt();
2408                 if (clip->getProperty("frame_size").section('x', 0, 0).toInt() > maxImageSize || clip->getProperty("frame_size").section('x', 1, 1).toInt() > maxImageSize) {
2409                     if (clip->getProperty("proxy").isEmpty()) {
2410                         // We need to insert empty proxy in old properties so that undo will work
2411                         QMap <QString, QString> oldProps = clip->properties();
2412                         oldProps.insert("proxy", QString());
2413                         QMap <QString, QString> newProps;
2414                         newProps.insert("proxy", proxydir + item->referencedClip()->getClipHash() + ".png");
2415                         new EditClipCommand(this, clip->getId(), oldProps, newProps, true, command);
2416                     }
2417                 }
2418             }
2419             else if (item->hasProxy()) {
2420                 // remove proxy
2421                 QMap <QString, QString> newProps;
2422                 newProps.insert("proxy", QString());
2423                 newProps.insert("replace", "1");
2424                 new EditClipCommand(this, item->clipId(), item->referencedClip()->properties(), newProps, true, command);
2425             }
2426         }
2427         ++it;
2428     }
2429     if (command->childCount() > 0) m_doc->commandStack()->push(command);
2430     else delete command;
2431     if (!m_infoQueue.isEmpty() && !m_queueRunner.isRunning() && m_processingClips.isEmpty()) m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
2432 }
2433
2434 void ProjectList::slotProxyCurrentItem(bool doProxy)
2435 {
2436     QList<QTreeWidgetItem *> list = m_listView->selectedItems();
2437     QTreeWidgetItem *listItem;
2438     QUndoCommand *command = new QUndoCommand();
2439     if (doProxy) command->setText(i18np("Add proxy clip", "Add proxy clips", list.count()));
2440     else command->setText(i18np("Remove proxy clip", "Remove proxy clips", list.count()));
2441     
2442     // Make sure the proxy folder exists
2443     QString proxydir = m_doc->projectFolder().path( KUrl::AddTrailingSlash) + "proxy/";
2444     KStandardDirs::makeDir(proxydir);
2445                 
2446     QMap <QString, QString> newProps;
2447     QMap <QString, QString> oldProps;
2448     if (!doProxy) newProps.insert("proxy", "-");
2449     for (int i = 0; i < list.count(); i++) {
2450         listItem = list.at(i);
2451         if (listItem->type() == PROJECTFOLDERTYPE) {
2452             for (int j = 0; j < listItem->childCount(); j++) {
2453                 QTreeWidgetItem *sub = listItem->child(j);
2454                 if (!list.contains(sub)) list.append(sub);
2455             }
2456         }
2457         if (listItem->type() == PROJECTCLIPTYPE) {
2458             ProjectItem *item = static_cast <ProjectItem*>(listItem);
2459             CLIPTYPE t = item->clipType();
2460             if ((t == VIDEO || t == AV || t == UNKNOWN || t == IMAGE || t == PLAYLIST) && item->referencedClip()) {
2461                 oldProps = item->referencedClip()->properties();
2462                 if (doProxy) {
2463                     newProps.clear();
2464                     QString path = proxydir + item->referencedClip()->getClipHash() + "." + (t == IMAGE ? "png" : m_doc->getDocumentProperty("proxyextension"));
2465                     // insert required duration for proxy
2466                     newProps.insert("proxy_out", item->referencedClip()->producerProperty("out"));
2467                     newProps.insert("proxy", path);
2468                     // We need to insert empty proxy so that undo will work
2469                     oldProps.insert("proxy", QString());
2470                 }
2471                 new EditClipCommand(this, item->clipId(), oldProps, newProps, true, command);
2472             }
2473         }
2474     }
2475     if (command->childCount() > 0) {
2476         m_doc->commandStack()->push(command);
2477     }
2478     else delete command;
2479     //if (!m_infoQueue.isEmpty() && !m_queueRunner.isRunning() && m_processingClips.isEmpty()) m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
2480 }
2481
2482
2483 void ProjectList::slotDeleteProxy(const QString proxyPath)
2484 {
2485     if (proxyPath.isEmpty()) return;
2486     QUndoCommand *proxyCommand = new QUndoCommand();
2487     proxyCommand->setText(i18n("Remove Proxy"));
2488     QTreeWidgetItemIterator it(m_listView);
2489     ProjectItem *item;
2490     while (*it) {
2491         if ((*it)->type() == PROJECTCLIPTYPE) {
2492             item = static_cast <ProjectItem *>(*it);
2493             if (item->referencedClip()->getProperty("proxy") == proxyPath) {
2494                 QMap <QString, QString> props;
2495                 props.insert("proxy", QString());
2496                 new EditClipCommand(this, item->clipId(), item->referencedClip()->properties(), props, true, proxyCommand);
2497             
2498             }
2499         }
2500         ++it;
2501     }
2502     if (proxyCommand->childCount() == 0)
2503         delete proxyCommand;
2504     else
2505         m_commandStack->push(proxyCommand);
2506     QFile::remove(proxyPath);
2507 }
2508
2509 void ProjectList::setProxyStatus(const QString proxyPath, PROXYSTATUS status)
2510 {
2511     if (proxyPath.isEmpty()) return;
2512     QTreeWidgetItemIterator it(m_listView);
2513     ProjectItem *item;
2514     while (*it) {
2515         if ((*it)->type() == PROJECTCLIPTYPE) {
2516             item = static_cast <ProjectItem *>(*it);
2517             if (item->referencedClip()->getProperty("proxy") == proxyPath) {
2518                 setProxyStatus(item, status);
2519             }
2520         }
2521         ++it;
2522     }
2523 }
2524
2525 void ProjectList::setProxyStatus(ProjectItem *item, PROXYSTATUS status)
2526 {
2527     if (item == NULL) return;
2528     monitorItemEditing(false);
2529     item->setProxyStatus(status);
2530     monitorItemEditing(true);
2531 }
2532
2533 void ProjectList::monitorItemEditing(bool enable)
2534 {
2535     if (enable) connect(m_listView, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this, SLOT(slotItemEdited(QTreeWidgetItem *, int)));     
2536     else disconnect(m_listView, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this, SLOT(slotItemEdited(QTreeWidgetItem *, int)));     
2537 }
2538
2539 QStringList ProjectList::expandedFolders() const
2540 {
2541     QStringList result;
2542     FolderProjectItem *item;
2543     QTreeWidgetItemIterator it(m_listView);
2544     while (*it) {
2545         if ((*it)->type() != PROJECTFOLDERTYPE) {
2546             ++it;
2547             continue;
2548         }
2549         if ((*it)->isExpanded()) {
2550             item = static_cast<FolderProjectItem *>(*it);
2551             result.append(item->clipId());
2552         }
2553         ++it;
2554     }
2555     return result;
2556 }
2557
2558 #include "projectlist.moc"