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