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