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