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