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