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