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