]> git.sesse.net Git - kdenlive/blob - src/projectlist.cpp
Load zone thumbnails from disk if available
[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::getCachedThumbnail(SubProjectItem *item)
1204 {
1205     if (!item) return;
1206     ProjectItem *parentItem = static_cast <ProjectItem *>(item->parent());
1207     if (!parentItem) return;
1208     DocClipBase *clip = parentItem->referencedClip();
1209     if (!clip) return;
1210     int pos = item->zone().x();
1211     QString cachedPixmap = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "thumbs/" + clip->getClipHash() + "#" + QString::number(pos) + ".png";
1212     if (QFile::exists(cachedPixmap)) {
1213         QPixmap pix(cachedPixmap);
1214         if (pix.isNull()) {
1215             KIO::NetAccess::del(KUrl(cachedPixmap), this);
1216             requestClipThumbnail(parentItem->clipId() + '#' + QString::number(pos));
1217         }
1218         else item->setData(0, Qt::DecorationRole, pix);
1219     }
1220     else requestClipThumbnail(parentItem->clipId() + '#' + QString::number(pos));
1221 }
1222
1223 void ProjectList::updateAllClips(bool displayRatioChanged, bool fpsChanged)
1224 {
1225     m_listView->setSortingEnabled(false);
1226
1227     QTreeWidgetItemIterator it(m_listView);
1228     DocClipBase *clip;
1229     ProjectItem *item;
1230     monitorItemEditing(false);
1231     int height = m_listView->iconSize().height();
1232     int width = (int)(height  * m_render->dar());
1233     QPixmap missingPixmap = QPixmap(width, height);
1234     missingPixmap.fill(Qt::transparent);
1235     KIcon icon("dialog-close");
1236     QPainter p(&missingPixmap);
1237     p.drawPixmap(3, 3, icon.pixmap(width - 6, height - 6));
1238     p.end();
1239     kDebug()<<"//////////////7  UPDATE ALL CLPS";
1240     while (*it) {
1241         if ((*it)->type() == PROJECTSUBCLIPTYPE) {
1242             // subitem
1243             SubProjectItem *sub = static_cast <SubProjectItem *>(*it);
1244             if (displayRatioChanged) {
1245                 item = static_cast <ProjectItem *>((*it)->parent());
1246                 requestClipThumbnail(item->clipId() + '#' + QString::number(sub->zone().x()));
1247             }
1248             else if (sub->data(0, Qt::DecorationRole).isNull()) {
1249                 getCachedThumbnail(sub);
1250             }
1251             ++it;
1252             continue;
1253         } else if ((*it)->type() == PROJECTFOLDERTYPE) {
1254             // folder
1255             ++it;
1256             continue;
1257         } else {
1258             item = static_cast <ProjectItem *>(*it);
1259             clip = item->referencedClip();
1260             if (item->referencedClip()->getProducer() == NULL) {
1261                 if (clip->isPlaceHolder() == false) {
1262                     QDomElement xml = clip->toXML();
1263                     if (fpsChanged) {
1264                         xml.removeAttribute("out");
1265                         xml.removeAttribute("file_hash");
1266                         xml.removeAttribute("proxy_out");
1267                     }
1268                     bool replace = xml.attribute("replace") == "1";
1269                     if (replace) resetThumbsProducer(clip);
1270                     m_render->getFileProperties(xml, clip->getId(), m_listView->iconSize().height(), replace);
1271                 }
1272                 else {
1273                     item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsDropEnabled);
1274                     if (item->data(0, Qt::DecorationRole).isNull()) {
1275                         item->setData(0, Qt::DecorationRole, missingPixmap);
1276                     }
1277                     else {
1278                         QPixmap pixmap = qVariantValue<QPixmap>(item->data(0, Qt::DecorationRole));
1279                         QPainter p(&pixmap);
1280                         p.drawPixmap(3, 3, KIcon("dialog-close").pixmap(pixmap.width() - 6, pixmap.height() - 6));
1281                         p.end();
1282                         item->setData(0, Qt::DecorationRole, pixmap);
1283                     }
1284                 }
1285             } else {              
1286                 if (displayRatioChanged)
1287                     requestClipThumbnail(clip->getId());
1288                 else if (item->data(0, Qt::DecorationRole).isNull()) {
1289                     getCachedThumbnail(item);
1290                 }
1291                 if (item->data(0, DurationRole).toString().isEmpty()) {
1292                     item->changeDuration(item->referencedClip()->getProducer()->get_playtime());
1293                 }
1294                 if (clip->isPlaceHolder()) {
1295                     QPixmap pixmap = qVariantValue<QPixmap>(item->data(0, Qt::DecorationRole));
1296                     if (pixmap.isNull()) {
1297                         pixmap = QPixmap(width, height);
1298                         pixmap.fill(Qt::transparent);
1299                     }
1300                     QPainter p(&pixmap);
1301                     p.drawPixmap(3, 3, KIcon("dialog-close").pixmap(pixmap.width() - 6, pixmap.height() - 6));
1302                     p.end();
1303                     item->setData(0, Qt::DecorationRole, pixmap);
1304                 }
1305             }
1306             item->setData(0, UsageRole, QString::number(item->numReferences()));
1307         }
1308         ++it;
1309     }
1310
1311     m_listView->setSortingEnabled(true);
1312     if (m_render->processingItems() == 0) {
1313        monitorItemEditing(true);
1314        slotProcessNextThumbnail();
1315     }
1316 }
1317
1318 // static
1319 QString ProjectList::getExtensions()
1320 {
1321     // Build list of mime types
1322     QStringList mimeTypes = QStringList() << "application/x-kdenlive" << "application/x-kdenlivetitle" << "video/mlt-playlist" << "text/plain"
1323                             << "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"
1324                             << "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"
1325                             << "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";
1326
1327     QString allExtensions;
1328     foreach(const QString & mimeType, mimeTypes) {
1329         KMimeType::Ptr mime(KMimeType::mimeType(mimeType));
1330         if (mime) {
1331             allExtensions.append(mime->patterns().join(" "));
1332             allExtensions.append(' ');
1333         }
1334     }
1335     return allExtensions.simplified();
1336 }
1337
1338 void ProjectList::slotAddClip(const QList <QUrl> givenList, const QString &groupName, const QString &groupId)
1339 {
1340     if (!m_commandStack)
1341         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1342
1343     KUrl::List list;
1344     if (givenList.isEmpty()) {
1345         QString allExtensions = getExtensions();
1346         const QString dialogFilter = allExtensions + ' ' + QLatin1Char('|') + i18n("All Supported Files") + "\n* " + QLatin1Char('|') + i18n("All Files");
1347         QCheckBox *b = new QCheckBox(i18n("Import image sequence"));
1348         b->setChecked(KdenliveSettings::autoimagesequence());
1349         QCheckBox *c = new QCheckBox(i18n("Transparent background for images"));
1350         c->setChecked(KdenliveSettings::autoimagetransparency());
1351         QFrame *f = new QFrame;
1352         f->setFrameShape(QFrame::NoFrame);
1353         QHBoxLayout *l = new QHBoxLayout;
1354         l->addWidget(b);
1355         l->addWidget(c);
1356         l->addStretch(5);
1357         f->setLayout(l);
1358         KFileDialog *d = new KFileDialog(KUrl("kfiledialog:///clipfolder"), dialogFilter, kapp->activeWindow(), f);
1359         d->setOperationMode(KFileDialog::Opening);
1360         d->setMode(KFile::Files);
1361         if (d->exec() == QDialog::Accepted) {
1362             KdenliveSettings::setAutoimagetransparency(c->isChecked());
1363         }
1364         list = d->selectedUrls();
1365         if (b->isChecked() && list.count() == 1) {
1366             // Check for image sequence
1367             KUrl url = list.at(0);
1368             QString fileName = url.fileName().section('.', 0, -2);
1369             if (fileName.at(fileName.size() - 1).isDigit()) {
1370                 KFileItem item(KFileItem::Unknown, KFileItem::Unknown, url);
1371                 if (item.mimetype().startsWith("image")) {
1372                     // import as sequence if we found more than one image in the sequence
1373                     QStringList list;
1374                     QString pattern = SlideshowClip::selectedPath(url.path(), false, QString(), &list);
1375                     int count = list.count();
1376                     if (count > 1) {
1377                         delete d;
1378                         QStringList groupInfo = getGroup();
1379
1380                         // get image sequence base name
1381                         while (fileName.at(fileName.size() - 1).isDigit()) {
1382                             fileName.chop(1);
1383                         }
1384
1385                         m_doc->slotCreateSlideshowClipFile(fileName, pattern, count, m_timecode.reformatSeparators(KdenliveSettings::sequence_duration()),
1386                                                            false, false, false,
1387                                                            m_timecode.getTimecodeFromFrames(int(ceil(m_timecode.fps()))), QString(), 0,
1388                                                            QString(), groupInfo.at(0), groupInfo.at(1));
1389                         return;
1390                     }
1391                 }
1392             }
1393         }
1394         delete d;
1395     } else {
1396         for (int i = 0; i < givenList.count(); i++)
1397             list << givenList.at(i);
1398     }
1399
1400     foreach(const KUrl & file, list) {
1401         // Check there is no folder here
1402         KMimeType::Ptr type = KMimeType::findByUrl(file);
1403         if (type->is("inode/directory")) {
1404             // user dropped a folder
1405             list.removeAll(file);
1406         }
1407     }
1408
1409     if (list.isEmpty())
1410         return;
1411
1412     if (givenList.isEmpty()) {
1413         QStringList groupInfo = getGroup();
1414         m_doc->slotAddClipList(list, groupInfo.at(0), groupInfo.at(1));
1415     } else {
1416         m_doc->slotAddClipList(list, groupName, groupId);
1417     }
1418 }
1419
1420 void ProjectList::slotRemoveInvalidClip(const QString &id, bool replace)
1421 {
1422     ProjectItem *item = getItemById(id);
1423     m_processingClips.removeAll(id);
1424     m_thumbnailQueue.removeAll(id);
1425     if (item) {
1426         item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsDropEnabled);
1427         const QString path = item->referencedClip()->fileURL().path();
1428         if (item->referencedClip()->isPlaceHolder()) replace = false;
1429         if (!path.isEmpty()) {
1430             if (m_invalidClipDialog) {
1431                 m_invalidClipDialog->addClip(id, path);
1432                 return;
1433             }
1434             else {
1435                 if (replace)
1436                     m_invalidClipDialog = new InvalidDialog(i18n("Invalid clip"),  i18n("Clip <b>%1</b><br />is invalid, will be removed from project.", QString()), replace, kapp->activeWindow());
1437                 else {
1438                     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());
1439                 }
1440                 m_invalidClipDialog->addClip(id, path);
1441                 int result = m_invalidClipDialog->exec();
1442                 if (result == KDialog::Yes) replace = true;
1443             }
1444         }
1445         if (m_invalidClipDialog) {
1446             if (replace)
1447                 emit deleteProjectClips(m_invalidClipDialog->getIds(), QMap <QString, QString>());
1448             delete m_invalidClipDialog;
1449             m_invalidClipDialog = NULL;
1450         }
1451         
1452     }
1453 }
1454
1455 void ProjectList::slotRemoveInvalidProxy(const QString &id, bool durationError)
1456 {
1457     ProjectItem *item = getItemById(id);
1458     if (item) {
1459         item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsDropEnabled);
1460         if (durationError) {
1461             kDebug() << "Proxy duration is wrong, try changing transcoding parameters.";
1462             emit displayMessage(i18n("Proxy clip unusable (duration is different from original)."), -2);
1463         }
1464         item->setProxyStatus(PROXYCRASHED);
1465         QString path = item->referencedClip()->getProperty("proxy");
1466         KUrl proxyFolder(m_doc->projectFolder().path( KUrl::AddTrailingSlash) + "proxy/");
1467
1468         //Security check: make sure the invalid proxy file is in the proxy folder
1469         if (proxyFolder.isParentOf(KUrl(path))) {
1470             QFile::remove(path);
1471         }
1472     }
1473     m_processingClips.removeAll(id);
1474     m_thumbnailQueue.removeAll(id);
1475 }
1476
1477 void ProjectList::slotAddColorClip()
1478 {
1479     if (!m_commandStack)
1480         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1481
1482     QDialog *dia = new QDialog(this);
1483     Ui::ColorClip_UI dia_ui;
1484     dia_ui.setupUi(dia);
1485     dia->setWindowTitle(i18n("Color Clip"));
1486     dia_ui.clip_name->setText(i18n("Color Clip"));
1487
1488     TimecodeDisplay *t = new TimecodeDisplay(m_timecode);
1489     t->setValue(KdenliveSettings::color_duration());
1490     t->setTimeCodeFormat(false);
1491     dia_ui.clip_durationBox->addWidget(t);
1492     dia_ui.clip_color->setColor(KdenliveSettings::colorclipcolor());
1493
1494     if (dia->exec() == QDialog::Accepted) {
1495         QString color = dia_ui.clip_color->color().name();
1496         KdenliveSettings::setColorclipcolor(color);
1497         color = color.replace(0, 1, "0x") + "ff";
1498         QStringList groupInfo = getGroup();
1499         m_doc->slotCreateColorClip(dia_ui.clip_name->text(), color, m_timecode.getTimecode(t->gentime()), groupInfo.at(0), groupInfo.at(1));
1500     }
1501     delete t;
1502     delete dia;
1503 }
1504
1505
1506 void ProjectList::slotAddSlideshowClip()
1507 {
1508     if (!m_commandStack)
1509         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1510
1511     SlideshowClip *dia = new SlideshowClip(m_timecode, this);
1512
1513     if (dia->exec() == QDialog::Accepted) {
1514         QStringList groupInfo = getGroup();
1515         m_doc->slotCreateSlideshowClipFile(dia->clipName(), dia->selectedPath(), dia->imageCount(), dia->clipDuration(),
1516                                            dia->loop(), dia->crop(), dia->fade(),
1517                                            dia->lumaDuration(), dia->lumaFile(), dia->softness(),
1518                                            dia->animation(), groupInfo.at(0), groupInfo.at(1));
1519     }
1520     delete dia;
1521 }
1522
1523 void ProjectList::slotAddTitleClip()
1524 {
1525     QStringList groupInfo = getGroup();
1526     m_doc->slotCreateTextClip(groupInfo.at(0), groupInfo.at(1));
1527 }
1528
1529 void ProjectList::slotAddTitleTemplateClip()
1530 {
1531     if (!m_commandStack)
1532         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1533
1534     QStringList groupInfo = getGroup();
1535
1536     // Get the list of existing templates
1537     QStringList filter;
1538     filter << "*.kdenlivetitle";
1539     const QString path = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1540     QStringList templateFiles = QDir(path).entryList(filter, QDir::Files);
1541
1542     QDialog *dia = new QDialog(this);
1543     Ui::TemplateClip_UI dia_ui;
1544     dia_ui.setupUi(dia);
1545     for (int i = 0; i < templateFiles.size(); ++i)
1546         dia_ui.template_list->comboBox()->addItem(templateFiles.at(i), path + templateFiles.at(i));
1547
1548     if (!templateFiles.isEmpty())
1549         dia_ui.buttonBox->button(QDialogButtonBox::Ok)->setFocus();
1550     dia_ui.template_list->fileDialog()->setFilter("application/x-kdenlivetitle");
1551     //warning: setting base directory doesn't work??
1552     KUrl startDir(path);
1553     dia_ui.template_list->fileDialog()->setUrl(startDir);
1554     dia_ui.text_box->setHidden(true);
1555     if (dia->exec() == QDialog::Accepted) {
1556         QString textTemplate = dia_ui.template_list->comboBox()->itemData(dia_ui.template_list->comboBox()->currentIndex()).toString();
1557         if (textTemplate.isEmpty()) textTemplate = dia_ui.template_list->comboBox()->currentText();
1558         // Create a cloned template clip
1559         m_doc->slotCreateTextTemplateClip(groupInfo.at(0), groupInfo.at(1), KUrl(textTemplate));
1560     }
1561     delete dia;
1562 }
1563
1564 QStringList ProjectList::getGroup() const
1565 {
1566     QStringList result;
1567     QTreeWidgetItem *item = m_listView->currentItem();
1568     while (item && item->type() != PROJECTFOLDERTYPE)
1569         item = item->parent();
1570
1571     if (item) {
1572         FolderProjectItem *folder = static_cast <FolderProjectItem *>(item);
1573         result << folder->groupName() << folder->clipId();
1574     } else {
1575         result << QString() << QString();
1576     }
1577     return result;
1578 }
1579
1580 void ProjectList::setDocument(KdenliveDoc *doc)
1581 {
1582     m_listView->blockSignals(true);
1583     m_abortAllProxies = true;
1584     m_proxyThreads.waitForFinished();
1585     m_proxyThreads.clearFutures();
1586     m_thumbnailQueue.clear();
1587     m_listView->clear();
1588     m_processingClips.clear();
1589     
1590     m_listView->setSortingEnabled(false);
1591     emit clipSelected(NULL);
1592     m_refreshed = false;
1593     m_fps = doc->fps();
1594     m_timecode = doc->timecode();
1595     m_commandStack = doc->commandStack();
1596     m_doc = doc;
1597     m_abortAllProxies = false;
1598
1599     QMap <QString, QString> flist = doc->clipManager()->documentFolderList();
1600     QStringList openedFolders = doc->getExpandedFolders();
1601     QMapIterator<QString, QString> f(flist);
1602     while (f.hasNext()) {
1603         f.next();
1604         FolderProjectItem *folder = new FolderProjectItem(m_listView, QStringList() << f.value(), f.key());
1605         folder->setExpanded(openedFolders.contains(f.key()));
1606     }
1607
1608     QList <DocClipBase*> list = doc->clipManager()->documentClipList();
1609     if (list.isEmpty()) m_refreshed = true;
1610     for (int i = 0; i < list.count(); i++)
1611         slotAddClip(list.at(i), false);
1612
1613     m_listView->blockSignals(false);
1614     connect(m_doc->clipManager(), SIGNAL(reloadClip(const QString &)), this, SLOT(slotReloadClip(const QString &)));
1615     connect(m_doc->clipManager(), SIGNAL(modifiedClip(const QString &)), this, SLOT(slotModifiedClip(const QString &)));
1616     connect(m_doc->clipManager(), SIGNAL(missingClip(const QString &)), this, SLOT(slotMissingClip(const QString &)));
1617     connect(m_doc->clipManager(), SIGNAL(availableClip(const QString &)), this, SLOT(slotAvailableClip(const QString &)));
1618     connect(m_doc->clipManager(), SIGNAL(checkAllClips(bool, bool)), this, SLOT(updateAllClips(bool, bool)));
1619 }
1620
1621 QList <DocClipBase*> ProjectList::documentClipList() const
1622 {
1623     if (m_doc == NULL)
1624         return QList <DocClipBase*> ();
1625
1626     return m_doc->clipManager()->documentClipList();
1627 }
1628
1629 QDomElement ProjectList::producersList()
1630 {
1631     QDomDocument doc;
1632     QDomElement prods = doc.createElement("producerlist");
1633     doc.appendChild(prods);
1634     kDebug() << "////////////  PRO LIST BUILD PRDSLIST ";
1635     QTreeWidgetItemIterator it(m_listView);
1636     while (*it) {
1637         if ((*it)->type() != PROJECTCLIPTYPE) {
1638             // subitem
1639             ++it;
1640             continue;
1641         }
1642         prods.appendChild(doc.importNode(((ProjectItem *)(*it))->toXml(), true));
1643         ++it;
1644     }
1645     return prods;
1646 }
1647
1648 void ProjectList::slotCheckForEmptyQueue()
1649 {
1650     if (m_render->processingItems() == 0 && m_thumbnailQueue.isEmpty()) {
1651         if (!m_refreshed) {
1652             emit loadingIsOver();
1653             emit displayMessage(QString(), -1);
1654             m_refreshed = true;
1655         }
1656         updateButtons();
1657     } else if (!m_refreshed) {
1658         QTimer::singleShot(300, this, SLOT(slotCheckForEmptyQueue()));
1659     }
1660 }
1661
1662
1663 void ProjectList::requestClipThumbnail(const QString id)
1664 {
1665     if (!m_thumbnailQueue.contains(id)) m_thumbnailQueue.append(id);
1666     slotProcessNextThumbnail();
1667 }
1668
1669 void ProjectList::resetThumbsProducer(DocClipBase *clip)
1670 {
1671     if (!clip) return;
1672     clip->clearThumbProducer();
1673     QString id = clip->getId();
1674     m_thumbnailQueue.removeAll(id);
1675 }
1676
1677 void ProjectList::slotProcessNextThumbnail()
1678 {
1679     if (m_render->processingItems() > 0) {
1680         return;
1681     }
1682     if (m_thumbnailQueue.isEmpty()) {
1683         slotCheckForEmptyQueue();
1684         return;
1685     }
1686     int max = m_doc->clipManager()->clipsCount();
1687     emit displayMessage(i18n("Loading thumbnails"), (int)(100 *(max - m_thumbnailQueue.count()) / max));
1688     slotRefreshClipThumbnail(m_thumbnailQueue.takeFirst(), false);
1689 }
1690
1691 void ProjectList::slotRefreshClipThumbnail(const QString &clipId, bool update)
1692 {
1693     QTreeWidgetItem *item = getAnyItemById(clipId);
1694     if (item)
1695         slotRefreshClipThumbnail(item, update);
1696     else {
1697         slotProcessNextThumbnail();
1698     }
1699 }
1700
1701 void ProjectList::slotRefreshClipThumbnail(QTreeWidgetItem *it, bool update)
1702 {
1703     if (it == NULL) return;
1704     ProjectItem *item = NULL;
1705     bool isSubItem = false;
1706     int frame;
1707     if (it->type() == PROJECTFOLDERTYPE) return;
1708     if (it->type() == PROJECTSUBCLIPTYPE) {
1709         item = static_cast <ProjectItem *>(it->parent());
1710         frame = static_cast <SubProjectItem *>(it)->zone().x();
1711         isSubItem = true;
1712     } else {
1713         item = static_cast <ProjectItem *>(it);
1714         frame = item->referencedClip()->getClipThumbFrame();
1715     }
1716
1717     if (item) {
1718         DocClipBase *clip = item->referencedClip();
1719         if (!clip) {
1720             slotProcessNextThumbnail();
1721             return;
1722         }
1723         QPixmap pix;
1724         int height = m_listView->iconSize().height();
1725         int swidth = (int)(height  * m_render->frameRenderWidth() / m_render->renderHeight()+ 0.5);
1726         int dwidth = (int)(height  * m_render->dar() + 0.5);
1727         if (clip->clipType() == AUDIO)
1728             pix = KIcon("audio-x-generic").pixmap(QSize(dwidth, height));
1729         else if (clip->clipType() == IMAGE)
1730             pix = QPixmap::fromImage(KThumb::getFrame(item->referencedClip()->getProducer(), 0, swidth, dwidth, height));
1731         else {
1732             pix = item->referencedClip()->extractImage(frame, dwidth, height);
1733         }
1734
1735         if (!pix.isNull()) {
1736             monitorItemEditing(false);
1737             it->setData(0, Qt::DecorationRole, pix);
1738             monitorItemEditing(true);
1739                 
1740             if (!isSubItem)
1741                 m_doc->cachePixmap(item->getClipHash(), pix);
1742             else
1743                 m_doc->cachePixmap(item->getClipHash() + '#' + QString::number(frame), pix);
1744         }
1745         if (update)
1746             emit projectModified();
1747         slotProcessNextThumbnail();
1748     }
1749 }
1750
1751
1752 void ProjectList::slotReplyGetFileProperties(const QString &clipId, Mlt::Producer *producer, const stringMap &properties, const stringMap &metadata, bool replace)
1753 {
1754     QString toReload;
1755     ProjectItem *item = getItemById(clipId);
1756
1757     int queue = m_render->processingItems();
1758     if (queue == 0) {
1759         m_listView->setEnabled(true);
1760     }
1761     if (item && producer) {
1762         monitorItemEditing(false);
1763         DocClipBase *clip = item->referencedClip();
1764         if (producer->is_valid()) {
1765             if (clip->isPlaceHolder()) {
1766                 clip->setValid();
1767                 toReload = clipId;
1768             }
1769             item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsDropEnabled);
1770         }
1771         item->setProperties(properties, metadata);
1772         clip->setProducer(producer, replace);
1773         clip->askForAudioThumbs();
1774
1775         // Proxy stuff
1776         QString size = properties.value("frame_size");
1777         if (!useProxy() && clip->getProperty("proxy").isEmpty()) setProxyStatus(item, NOPROXY);
1778         if (useProxy() && generateProxy() && clip->getProperty("proxy") == "-") setProxyStatus(item, NOPROXY);
1779         else if (useProxy() && !item->hasProxy() && !item->isProxyRunning()) {
1780             // proxy video and image clips
1781             int maxSize;
1782             CLIPTYPE t = item->clipType();
1783             if (t == IMAGE) maxSize = m_doc->getDocumentProperty("proxyimageminsize").toInt();
1784             else maxSize = m_doc->getDocumentProperty("proxyminsize").toInt();
1785             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)) {
1786                 if (clip->getProperty("proxy").isEmpty()) {
1787                     KUrl proxyPath = m_doc->projectFolder();
1788                     proxyPath.addPath("proxy/");
1789                     proxyPath.addPath(clip->getClipHash() + "." + (t == IMAGE ? "png" : m_doc->getDocumentProperty("proxyextension")));
1790                     QMap <QString, QString> newProps;
1791                     // insert required duration for proxy
1792                     if (t != IMAGE) newProps.insert("proxy_out", clip->producerProperty("out"));
1793                     newProps.insert("proxy", proxyPath.path());
1794                     QMap <QString, QString> oldProps = clip->properties();
1795                     oldProps.insert("proxy", QString());
1796                     EditClipCommand *command = new EditClipCommand(this, clipId, oldProps, newProps, true);
1797                     m_doc->commandStack()->push(command);
1798                 }
1799             }
1800         }
1801
1802         if (!replace && item->data(0, Qt::DecorationRole).isNull()) {
1803             requestClipThumbnail(clipId);
1804         }
1805         if (!toReload.isEmpty())
1806             item->slotSetToolTip();
1807     } else kDebug() << "////////  COULD NOT FIND CLIP TO UPDATE PRPS...";
1808     if (queue == 0) {
1809         monitorItemEditing(true);
1810         if (item && m_thumbnailQueue.isEmpty()) {
1811             m_listView->setCurrentItem(item);
1812             bool updatedProfile = false;
1813             if (item->parent()) {
1814                 if (item->parent()->type() == PROJECTFOLDERTYPE)
1815                     static_cast <FolderProjectItem *>(item->parent())->switchIcon();
1816             } else if (KdenliveSettings::checkfirstprojectclip() &&  m_listView->topLevelItemCount() == 1) {
1817                 // this is the first clip loaded in project, check if we want to adjust project settings to the clip
1818                 updatedProfile = adjustProjectProfileToItem(item);
1819             }
1820             if (updatedProfile == false) {
1821                 //emit clipSelected(item->referencedClip());
1822             }
1823         } else {
1824             int max = m_doc->clipManager()->clipsCount();
1825             emit displayMessage(i18n("Loading clips"), (int)(100 *(max - queue) / max));
1826         }
1827         processNextThumbnail();
1828     }
1829     if (replace && item) {
1830         toReload = clipId;
1831     }
1832     if (!item) {
1833         // no item for producer, delete it
1834         delete producer;
1835     }
1836     if (!toReload.isEmpty())
1837         emit clipNeedsReload(toReload);
1838 }
1839
1840 bool ProjectList::adjustProjectProfileToItem(ProjectItem *item)
1841 {
1842     if (item == NULL) {
1843         if (m_listView->currentItem() && m_listView->currentItem()->type() != PROJECTFOLDERTYPE)
1844             item = static_cast <ProjectItem*>(m_listView->currentItem());
1845     }
1846     if (item == NULL || item->referencedClip() == NULL) {
1847         KMessageBox::information(kapp->activeWindow(), i18n("Cannot find profile from current clip"));
1848         return false;
1849     }
1850     bool profileUpdated = false;
1851     QString size = item->referencedClip()->getProperty("frame_size");
1852     int width = size.section('x', 0, 0).toInt();
1853     int height = size.section('x', -1).toInt();
1854     double fps = item->referencedClip()->getProperty("fps").toDouble();
1855     double par = item->referencedClip()->getProperty("aspect_ratio").toDouble();
1856     if (item->clipType() == IMAGE || item->clipType() == AV || item->clipType() == VIDEO) {
1857         if (ProfilesDialog::matchProfile(width, height, fps, par, item->clipType() == IMAGE, m_doc->mltProfile()) == false) {
1858             // get a list of compatible profiles
1859             QMap <QString, QString> suggestedProfiles = ProfilesDialog::getProfilesFromProperties(width, height, fps, par, item->clipType() == IMAGE);
1860             if (!suggestedProfiles.isEmpty()) {
1861                 KDialog *dialog = new KDialog(this);
1862                 dialog->setCaption(i18n("Change project profile"));
1863                 dialog->setButtons(KDialog::Ok | KDialog::Cancel);
1864
1865                 QWidget container;
1866                 QVBoxLayout *l = new QVBoxLayout;
1867                 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));
1868                 l->addWidget(label);
1869                 QListWidget *list = new QListWidget;
1870                 list->setAlternatingRowColors(true);
1871                 QMapIterator<QString, QString> i(suggestedProfiles);
1872                 while (i.hasNext()) {
1873                     i.next();
1874                     QListWidgetItem *item = new QListWidgetItem(i.value(), list);
1875                     item->setData(Qt::UserRole, i.key());
1876                     item->setToolTip(i.key());
1877                 }
1878                 list->setCurrentRow(0);
1879                 l->addWidget(list);
1880                 container.setLayout(l);
1881                 dialog->setButtonText(KDialog::Ok, i18n("Update profile"));
1882                 dialog->setMainWidget(&container);
1883                 if (dialog->exec() == QDialog::Accepted) {
1884                     //Change project profile
1885                     profileUpdated = true;
1886                     if (list->currentItem())
1887                         emit updateProfile(list->currentItem()->data(Qt::UserRole).toString());
1888                 }
1889                 delete list;
1890                 delete label;
1891             } else if (fps > 0) {
1892                 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));
1893             }
1894         }
1895     }
1896     return profileUpdated;
1897 }
1898
1899 QString ProjectList::getDocumentProperty(const QString &key) const
1900 {
1901     return m_doc->getDocumentProperty(key);
1902 }
1903
1904 bool ProjectList::useProxy() const
1905 {
1906     return m_doc->getDocumentProperty("enableproxy").toInt();
1907 }
1908
1909 bool ProjectList::generateProxy() const
1910 {
1911     return m_doc->getDocumentProperty("generateproxy").toInt();
1912 }
1913
1914 bool ProjectList::generateImageProxy() const
1915 {
1916     return m_doc->getDocumentProperty("generateimageproxy").toInt();
1917 }
1918
1919 void ProjectList::slotReplyGetImage(const QString &clipId, const QImage &img)
1920 {
1921     QPixmap pix = QPixmap::fromImage(img);
1922     setThumbnail(clipId, pix);
1923 }
1924
1925 void ProjectList::slotReplyGetImage(const QString &clipId, const QString &name, int width, int height)
1926 {
1927     QPixmap pix =  KIcon(name).pixmap(QSize(width, height));
1928     setThumbnail(clipId, pix);
1929 }
1930
1931 void ProjectList::setThumbnail(const QString &clipId, const QPixmap &pix)
1932 {
1933     ProjectItem *item = getItemById(clipId);
1934     if (item && !pix.isNull()) {
1935         monitorItemEditing(false);
1936         item->setData(0, Qt::DecorationRole, pix);
1937         monitorItemEditing(true);
1938         //update();
1939         m_doc->cachePixmap(item->getClipHash(), pix);
1940     }
1941 }
1942
1943 QTreeWidgetItem *ProjectList::getAnyItemById(const QString &id)
1944 {
1945     QTreeWidgetItemIterator it(m_listView);
1946     QString lookId = id;
1947     if (id.contains('#'))
1948         lookId = id.section('#', 0, 0);
1949
1950     ProjectItem *result = NULL;
1951     while (*it) {
1952         if ((*it)->type() != PROJECTCLIPTYPE) {
1953             // subitem
1954             ++it;
1955             continue;
1956         }
1957         ProjectItem *item = static_cast<ProjectItem *>(*it);
1958         if (item->clipId() == lookId) {
1959             result = item;
1960             break;
1961         }
1962         ++it;
1963     }
1964     if (result == NULL || !id.contains('#')) {
1965         return result;
1966     } else {
1967         for (int i = 0; i < result->childCount(); i++) {
1968             SubProjectItem *sub = static_cast <SubProjectItem *>(result->child(i));
1969             if (sub && sub->zone().x() == id.section('#', 1, 1).toInt())
1970                 return sub;
1971         }
1972     }
1973
1974     return NULL;
1975 }
1976
1977
1978 ProjectItem *ProjectList::getItemById(const QString &id)
1979 {
1980     ProjectItem *item;
1981     QTreeWidgetItemIterator it(m_listView);
1982     while (*it) {
1983         if ((*it)->type() != PROJECTCLIPTYPE) {
1984             // subitem or folder
1985             ++it;
1986             continue;
1987         }
1988         item = static_cast<ProjectItem *>(*it);
1989         if (item->clipId() == id)
1990             return item;
1991         ++it;
1992     }
1993     return NULL;
1994 }
1995
1996 FolderProjectItem *ProjectList::getFolderItemById(const QString &id)
1997 {
1998     FolderProjectItem *item;
1999     QTreeWidgetItemIterator it(m_listView);
2000     while (*it) {
2001         if ((*it)->type() == PROJECTFOLDERTYPE) {
2002             item = static_cast<FolderProjectItem *>(*it);
2003             if (item->clipId() == id)
2004                 return item;
2005         }
2006         ++it;
2007     }
2008     return NULL;
2009 }
2010
2011 void ProjectList::slotSelectClip(const QString &ix)
2012 {
2013     ProjectItem *clip = getItemById(ix);
2014     if (clip) {
2015         m_listView->setCurrentItem(clip);
2016         m_listView->scrollToItem(clip);
2017         m_editButton->defaultAction()->setEnabled(true);
2018         m_deleteButton->defaultAction()->setEnabled(true);
2019         m_reloadAction->setEnabled(true);
2020         m_transcodeAction->setEnabled(true);
2021         if (clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) {
2022             m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
2023             m_openAction->setEnabled(true);
2024         } else if (clip->clipType() == AUDIO && !KdenliveSettings::defaultaudioapp().isEmpty()) {
2025             m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
2026             m_openAction->setEnabled(true);
2027         } else {
2028             m_openAction->setEnabled(false);
2029         }
2030     }
2031 }
2032
2033 QString ProjectList::currentClipUrl() const
2034 {
2035     ProjectItem *item;
2036     if (!m_listView->currentItem() || m_listView->currentItem()->type() == PROJECTFOLDERTYPE) return QString();
2037     if (m_listView->currentItem()->type() == PROJECTSUBCLIPTYPE) {
2038         // subitem
2039         item = static_cast <ProjectItem*>(m_listView->currentItem()->parent());
2040     } else {
2041         item = static_cast <ProjectItem*>(m_listView->currentItem());
2042     }
2043     if (item == NULL)
2044         return QString();
2045     return item->clipUrl().path();
2046 }
2047
2048 KUrl::List ProjectList::getConditionalUrls(const QString &condition) const
2049 {
2050     KUrl::List result;
2051     ProjectItem *item;
2052     QList<QTreeWidgetItem *> list = m_listView->selectedItems();
2053     for (int i = 0; i < list.count(); i++) {
2054         if (list.at(i)->type() == PROJECTFOLDERTYPE)
2055             continue;
2056         if (list.at(i)->type() == PROJECTSUBCLIPTYPE) {
2057             // subitem
2058             item = static_cast <ProjectItem*>(list.at(i)->parent());
2059         } else {
2060             item = static_cast <ProjectItem*>(list.at(i));
2061         }
2062         if (item == NULL || item->type() == COLOR || item->type() == SLIDESHOW || item->type() == TEXT)
2063             continue;
2064         DocClipBase *clip = item->referencedClip();
2065         if (!condition.isEmpty()) {
2066             if (condition.startsWith("vcodec") && !clip->hasVideoCodec(condition.section('=', 1, 1)))
2067                 continue;
2068             else if (condition.startsWith("acodec") && !clip->hasAudioCodec(condition.section('=', 1, 1)))
2069                 continue;
2070         }
2071         result.append(item->clipUrl());
2072     }
2073     return result;
2074 }
2075
2076 void ProjectList::regenerateTemplate(const QString &id)
2077 {
2078     ProjectItem *clip = getItemById(id);
2079     if (clip)
2080         regenerateTemplate(clip);
2081 }
2082
2083 void ProjectList::regenerateTemplate(ProjectItem *clip)
2084 {
2085     //TODO: remove this unused method, only force_reload is necessary
2086     clip->referencedClip()->getProducer()->set("force_reload", 1);
2087 }
2088
2089 QDomDocument ProjectList::generateTemplateXml(QString path, const QString &replaceString)
2090 {
2091     QDomDocument doc;
2092     QFile file(path);
2093     if (!file.open(QIODevice::ReadOnly)) {
2094         kWarning() << "ERROR, CANNOT READ: " << path;
2095         return doc;
2096     }
2097     if (!doc.setContent(&file)) {
2098         kWarning() << "ERROR, CANNOT READ: " << path;
2099         file.close();
2100         return doc;
2101     }
2102     file.close();
2103     QDomNodeList texts = doc.elementsByTagName("content");
2104     for (int i = 0; i < texts.count(); i++) {
2105         QString data = texts.item(i).firstChild().nodeValue();
2106         data.replace("%s", replaceString);
2107         texts.item(i).firstChild().setNodeValue(data);
2108     }
2109     return doc;
2110 }
2111
2112
2113 void ProjectList::slotAddClipCut(const QString &id, int in, int out)
2114 {
2115     ProjectItem *clip = getItemById(id);
2116     if (clip == NULL || clip->referencedClip()->hasCutZone(QPoint(in, out)))
2117         return;
2118     AddClipCutCommand *command = new AddClipCutCommand(this, id, in, out, QString(), true, false);
2119     m_commandStack->push(command);
2120 }
2121
2122 void ProjectList::addClipCut(const QString &id, int in, int out, const QString desc, bool newItem)
2123 {
2124     ProjectItem *clip = getItemById(id);
2125     if (clip) {
2126         DocClipBase *base = clip->referencedClip();
2127         base->addCutZone(in, out);
2128         monitorItemEditing(false);
2129         SubProjectItem *sub = new SubProjectItem(clip, in, out, desc);
2130         if (newItem && desc.isEmpty() && !m_listView->isColumnHidden(1)) {
2131             if (!clip->isExpanded())
2132                 clip->setExpanded(true);
2133             m_listView->scrollToItem(sub);
2134             m_listView->editItem(sub, 1);
2135         }
2136         QPixmap p = clip->referencedClip()->extractImage(in, (int)(sub->sizeHint(0).height()  * m_render->dar()), sub->sizeHint(0).height() - 2);
2137         sub->setData(0, Qt::DecorationRole, p);
2138         m_doc->cachePixmap(clip->getClipHash() + '#' + QString::number(in), p);
2139         monitorItemEditing(true);
2140     }
2141     emit projectModified();
2142 }
2143
2144 void ProjectList::removeClipCut(const QString &id, int in, int out)
2145 {
2146     ProjectItem *clip = getItemById(id);
2147     if (clip) {
2148         DocClipBase *base = clip->referencedClip();
2149         base->removeCutZone(in, out);
2150         SubProjectItem *sub = getSubItem(clip, QPoint(in, out));
2151         if (sub) {
2152             monitorItemEditing(false);
2153             delete sub;
2154             monitorItemEditing(true);
2155         }
2156     }
2157     emit projectModified();
2158 }
2159
2160 SubProjectItem *ProjectList::getSubItem(ProjectItem *clip, QPoint zone)
2161 {
2162     SubProjectItem *sub = NULL;
2163     if (clip) {
2164         for (int i = 0; i < clip->childCount(); i++) {
2165             QTreeWidgetItem *it = clip->child(i);
2166             if (it->type() == PROJECTSUBCLIPTYPE) {
2167                 sub = static_cast <SubProjectItem*>(it);
2168                 if (sub->zone() == zone)
2169                     break;
2170                 else
2171                     sub = NULL;
2172             }
2173         }
2174     }
2175     return sub;
2176 }
2177
2178 void ProjectList::slotUpdateClipCut(QPoint p)
2179 {
2180     if (!m_listView->currentItem() || m_listView->currentItem()->type() != PROJECTSUBCLIPTYPE)
2181         return;
2182     SubProjectItem *sub = static_cast <SubProjectItem*>(m_listView->currentItem());
2183     ProjectItem *item = static_cast <ProjectItem *>(sub->parent());
2184     EditClipCutCommand *command = new EditClipCutCommand(this, item->clipId(), sub->zone(), p, sub->text(1), sub->text(1), true);
2185     m_commandStack->push(command);
2186 }
2187
2188 void ProjectList::doUpdateClipCut(const QString &id, const QPoint oldzone, const QPoint zone, const QString &comment)
2189 {
2190     ProjectItem *clip = getItemById(id);
2191     SubProjectItem *sub = getSubItem(clip, oldzone);
2192     if (sub == NULL || clip == NULL)
2193         return;
2194     DocClipBase *base = clip->referencedClip();
2195     base->updateCutZone(oldzone.x(), oldzone.y(), zone.x(), zone.y(), comment);
2196     monitorItemEditing(false);
2197     sub->setZone(zone);
2198     sub->setDescription(comment);
2199     monitorItemEditing(true);
2200     emit projectModified();
2201 }
2202
2203 void ProjectList::slotForceProcessing(const QString &id)
2204 {
2205     m_render->forceProcessing(id);
2206 }
2207
2208 void ProjectList::slotAddOrUpdateSequence(const QString frameName)
2209 {
2210     QString fileName = KUrl(frameName).fileName().section('_', 0, -2);
2211     QStringList list;
2212     QString pattern = SlideshowClip::selectedPath(frameName, false, QString(), &list);
2213     int count = list.count();
2214     if (count > 1) {
2215         const QList <DocClipBase *> existing = m_doc->clipManager()->getClipByResource(pattern);
2216         if (!existing.isEmpty()) {
2217             // Sequence already exists, update
2218             QString id = existing.at(0)->getId();
2219             //ProjectItem *item = getItemById(id);
2220             QMap <QString, QString> oldprops;
2221             QMap <QString, QString> newprops;
2222             int ttl = existing.at(0)->getProperty("ttl").toInt();
2223             oldprops["out"] = existing.at(0)->getProperty("out");
2224             newprops["out"] = QString::number(ttl * count - 1);
2225             slotUpdateClipProperties(id, newprops);
2226             EditClipCommand *command = new EditClipCommand(this, id, oldprops, newprops, false);
2227             m_commandStack->push(command);
2228         } else {
2229             // Create sequence
2230             QStringList groupInfo = getGroup();
2231             m_doc->slotCreateSlideshowClipFile(fileName, pattern, count, m_timecode.reformatSeparators(KdenliveSettings::sequence_duration()),
2232                                                false, false, false,
2233                                                m_timecode.getTimecodeFromFrames(int(ceil(m_timecode.fps()))), QString(), 0,
2234                                                QString(), groupInfo.at(0), groupInfo.at(1));
2235         }
2236     } else emit displayMessage(i18n("Sequence not found"), -2);
2237 }
2238
2239 QMap <QString, QString> ProjectList::getProxies()
2240 {
2241     QMap <QString, QString> list;
2242     ProjectItem *item;
2243     QTreeWidgetItemIterator it(m_listView);
2244     while (*it) {
2245         if ((*it)->type() != PROJECTCLIPTYPE) {
2246             ++it;
2247             continue;
2248         }
2249         item = static_cast<ProjectItem *>(*it);
2250         if (item && item->referencedClip() != NULL) {
2251             if (item->hasProxy()) {
2252                 QString proxy = item->referencedClip()->getProperty("proxy");
2253                 list.insert(proxy, item->clipUrl().path());
2254             }
2255         }
2256         ++it;
2257     }
2258     return list;
2259 }
2260
2261 void ProjectList::slotCreateProxy(const QString id)
2262 {
2263     ProjectItem *item = getItemById(id);
2264     if (!item || item->isProxyRunning() || item->referencedClip()->isPlaceHolder()) return;
2265     QString path = item->referencedClip()->getProperty("proxy");
2266     if (path.isEmpty()) {
2267         setProxyStatus(path, PROXYCRASHED);
2268         return;
2269     }
2270     setProxyStatus(path, PROXYWAITING);
2271     if (m_abortProxy.contains(path)) m_abortProxy.removeAll(path);
2272     if (m_processingProxy.contains(path)) {
2273         // Proxy is already being generated
2274         return;
2275     }
2276     if (QFile::exists(path)) {
2277         // Proxy already created
2278         setProxyStatus(path, PROXYDONE);
2279         slotGotProxy(path);
2280         return;
2281     }
2282     m_processingProxy.append(path);
2283
2284     PROXYINFO info;
2285     info.dest = path;
2286     info.src = item->clipUrl().path();
2287     info.type = item->clipType();
2288     info.exif = QString(item->referencedClip()->producerProperty("_exif_orientation")).toInt();
2289     m_proxyList.append(info);
2290     m_proxyThreads.addFuture(QtConcurrent::run(this, &ProjectList::slotGenerateProxy));
2291 }
2292
2293 void ProjectList::slotAbortProxy(const QString id, const QString path)
2294 {
2295     QTreeWidgetItemIterator it(m_listView);
2296     ProjectItem *item = getItemById(id);
2297     setProxyStatus(item, NOPROXY);
2298     slotGotProxy(item);
2299     if (!path.isEmpty() && m_processingProxy.contains(path)) {
2300         m_abortProxy << path;
2301         setProxyStatus(path, NOPROXY);
2302     }
2303 }
2304
2305 void ProjectList::slotGenerateProxy()
2306 {
2307     if (m_proxyList.isEmpty() || m_abortAllProxies) return;
2308     emit projectModified();
2309     PROXYINFO info = m_proxyList.takeFirst();
2310     if (m_abortProxy.contains(info.dest)) {
2311         m_abortProxy.removeAll(info.dest);
2312         return;
2313     }
2314
2315     // Make sure proxy path is writable
2316     QFile file(info.dest);
2317     if (!file.open(QIODevice::WriteOnly)) {
2318         setProxyStatus(info.dest, PROXYCRASHED);
2319         m_processingProxy.removeAll(info.dest);
2320         return;
2321     }
2322     file.close();
2323     QFile::remove(info.dest);
2324     
2325     setProxyStatus(info.dest, CREATINGPROXY);
2326
2327     // Special case: playlist clips (.mlt or .kdenlive project files)
2328     if (info.type == PLAYLIST) {
2329         // change FFmpeg params to MLT format
2330         QStringList parameters;
2331         parameters << info.src;
2332         parameters << "-consumer" << "avformat:" + info.dest;
2333         QStringList params = m_doc->getDocumentProperty("proxyparams").simplified().split('-', QString::SkipEmptyParts);
2334         
2335         foreach(QString s, params) {
2336             s = s.simplified();
2337             if (s.count(' ') == 0) {
2338                 s.append("=1");
2339             }
2340             else s.replace(' ', '=');
2341             parameters << s;
2342         }
2343         
2344         parameters.append(QString("real_time=-%1").arg(KdenliveSettings::mltthreads()));
2345
2346         //TODO: currently, when rendering an xml file through melt, the display ration is lost, so we enforce it manualy
2347         double display_ratio = KdenliveDoc::getDisplayRatio(info.src);
2348         parameters << "aspect=" + QString::number(display_ratio);
2349
2350         //kDebug()<<"TRANSCOD: "<<parameters;
2351         QProcess myProcess;
2352         myProcess.setProcessChannelMode(QProcess::MergedChannels);
2353         myProcess.start(KdenliveSettings::rendererpath(), parameters);
2354         myProcess.waitForStarted();
2355         int result = -1;
2356         int duration = 0;
2357         while (myProcess.state() != QProcess::NotRunning) {
2358             // building proxy file
2359             if (m_abortProxy.contains(info.dest) || m_abortAllProxies) {
2360                 myProcess.close();
2361                 myProcess.waitForFinished();
2362                 QFile::remove(info.dest);
2363                 m_abortProxy.removeAll(info.dest);
2364                 m_processingProxy.removeAll(info.dest);
2365                 setProxyStatus(info.dest, NOPROXY);
2366                 result = -2;
2367             }
2368             else {
2369                 QString log = QString(myProcess.readAll());
2370                 processLogInfo(info.dest, &duration, log);
2371             }
2372             myProcess.waitForFinished(500);
2373         }
2374         myProcess.waitForFinished();
2375         m_processingProxy.removeAll(info.dest);
2376         if (result == -1) result = myProcess.exitStatus();
2377         if (result == 0) {
2378             // proxy successfully created
2379             setProxyStatus(info.dest, PROXYDONE);
2380             slotGotProxy(info.dest);
2381         }
2382         else if (result == 1) {
2383             // Proxy process crashed
2384             QFile::remove(info.dest);
2385             setProxyStatus(info.dest, PROXYCRASHED);
2386         }   
2387
2388     }
2389     
2390     if (info.type == IMAGE) {
2391         // Image proxy
2392         QImage i(info.src);
2393         if (i.isNull()) {
2394             // Cannot load image
2395             setProxyStatus(info.dest, PROXYCRASHED);
2396             return;
2397         }
2398         QImage proxy;
2399         // Images are scaled to profile size. 
2400         //TODO: Make it be configurable?
2401         if (i.width() > i.height()) proxy = i.scaledToWidth(m_render->frameRenderWidth());
2402         else proxy = i.scaledToHeight(m_render->renderHeight());
2403         if (info.exif > 1) {
2404             // Rotate image according to exif data
2405             QImage processed;
2406             QMatrix matrix;
2407
2408             switch ( info.exif ) {
2409                 case 2:
2410                   matrix.scale( -1, 1 );
2411                   break;
2412                 case 3:
2413                   matrix.rotate( 180 );
2414                   break;
2415                 case 4:
2416                   matrix.scale( 1, -1 );
2417                   break;
2418                 case 5:
2419                   matrix.rotate( 270 );
2420                   matrix.scale( -1, 1 );
2421                   break;
2422                 case 6:
2423                   matrix.rotate( 90 );
2424                   break;
2425                 case 7:
2426                   matrix.rotate( 90 );
2427                   matrix.scale( -1, 1 );
2428                   break;
2429                 case 8:
2430                   matrix.rotate( 270 );
2431                   break;
2432               }
2433               processed = proxy.transformed( matrix );
2434               processed.save(info.dest);
2435         }
2436         else proxy.save(info.dest);
2437         setProxyStatus(info.dest, PROXYDONE);
2438         slotGotProxy(info.dest);
2439         m_abortProxy.removeAll(info.dest);
2440         m_processingProxy.removeAll(info.dest);
2441         return;
2442     }
2443
2444     QStringList parameters;
2445     parameters << "-i" << info.src;
2446     QString params = m_doc->getDocumentProperty("proxyparams").simplified();
2447     foreach(QString s, params.split(' '))
2448     parameters << s;
2449
2450     // Make sure we don't block when proxy file already exists
2451     parameters << "-y";
2452     parameters << info.dest;
2453     kDebug()<<"// STARTING PROXY GEN: "<<parameters;
2454     QProcess myProcess;
2455     myProcess.setProcessChannelMode(QProcess::MergedChannels);
2456     myProcess.start("ffmpeg", parameters);
2457     myProcess.waitForStarted();
2458     int result = -1;
2459     int duration = 0;
2460     while (myProcess.state() != QProcess::NotRunning) {
2461         // building proxy file
2462         if (m_abortProxy.contains(info.dest) || m_abortAllProxies) {
2463             myProcess.close();
2464             myProcess.waitForFinished();
2465             m_abortProxy.removeAll(info.dest);
2466             m_processingProxy.removeAll(info.dest);
2467             QFile::remove(info.dest);
2468             setProxyStatus(info.dest, NOPROXY);
2469             result = -2;
2470             
2471         }
2472         else {
2473             QString log = QString(myProcess.readAll());
2474             processLogInfo(info.dest, &duration, log);
2475         }
2476         myProcess.waitForFinished(500);
2477     }
2478     myProcess.waitForFinished();
2479     if (result == -1) result = myProcess.exitStatus();
2480     if (result == 0) {
2481         // proxy successfully created
2482         setProxyStatus(info.dest, PROXYDONE);
2483         slotGotProxy(info.dest);
2484     }
2485     else if (result == 1) {
2486         // Proxy process crashed
2487         QFile::remove(info.dest);
2488         setProxyStatus(info.dest, PROXYCRASHED);
2489     }
2490     m_abortProxy.removeAll(info.dest);
2491     m_processingProxy.removeAll(info.dest);
2492 }
2493
2494
2495 void ProjectList::processLogInfo(const QString &path, int *duration, const QString &log)
2496 {
2497     int progress;
2498     if (*duration == 0) {
2499         if (log.contains("Duration:")) {
2500             QString data = log.section("Duration:", 1, 1).section(',', 0, 0).simplified();
2501             QStringList numbers = data.split(':');
2502             *duration = (int) (numbers.at(0).toInt() * 3600 + numbers.at(1).toInt() * 60 + numbers.at(2).toDouble());
2503         }
2504     }
2505     else if (log.contains("time=")) {
2506         QString time = log.section("time=", 1, 1).simplified().section(' ', 0, 0);
2507         if (time.contains(':')) {
2508             QStringList numbers = time.split(':');
2509             progress = numbers.at(0).toInt() * 3600 + numbers.at(1).toInt() * 60 + numbers.at(2).toDouble();
2510         }
2511         else progress = (int) time.toDouble();
2512         setProxyStatus(path, CREATINGPROXY, (int) (100.0 * progress / (*duration)));
2513     }
2514 }
2515
2516 void ProjectList::updateProxyConfig()
2517 {
2518     ProjectItem *item;
2519     QTreeWidgetItemIterator it(m_listView);
2520     QUndoCommand *command = new QUndoCommand();
2521     command->setText(i18n("Update proxy settings"));
2522     QString proxydir = m_doc->projectFolder().path( KUrl::AddTrailingSlash) + "proxy/";
2523     while (*it) {
2524         if ((*it)->type() != PROJECTCLIPTYPE) {
2525             ++it;
2526             continue;
2527         }
2528         item = static_cast<ProjectItem *>(*it);
2529         if (item == NULL) {
2530             ++it;
2531             continue;
2532         }
2533         CLIPTYPE t = item->clipType();
2534         if ((t == VIDEO || t == AV || t == UNKNOWN) && item->referencedClip() != NULL) {
2535             if  (generateProxy() && useProxy() && !item->isProxyRunning()) {
2536                 DocClipBase *clip = item->referencedClip();
2537                 if (clip->getProperty("frame_size").section('x', 0, 0).toInt() > m_doc->getDocumentProperty("proxyminsize").toInt()) {
2538                     if (clip->getProperty("proxy").isEmpty()) {
2539                         // We need to insert empty proxy in old properties so that undo will work
2540                         QMap <QString, QString> oldProps;// = clip->properties();
2541                         oldProps.insert("proxy", QString());
2542                         QMap <QString, QString> newProps;
2543                         newProps.insert("proxy", proxydir + item->referencedClip()->getClipHash() + "." + m_doc->getDocumentProperty("proxyextension"));
2544                         new EditClipCommand(this, clip->getId(), oldProps, newProps, true, command);
2545                     }
2546                 }
2547             }
2548             else if (item->hasProxy()) {
2549                 // remove proxy
2550                 QMap <QString, QString> newProps;
2551                 newProps.insert("proxy", QString());
2552                 newProps.insert("replace", "1");
2553                 // insert required duration for proxy
2554                 newProps.insert("proxy_out", item->referencedClip()->producerProperty("out"));
2555                 new EditClipCommand(this, item->clipId(), item->referencedClip()->properties(), newProps, true, command);
2556             }
2557         }
2558         else if (t == IMAGE && item->referencedClip() != NULL) {
2559             if  (generateImageProxy() && useProxy()) {
2560                 DocClipBase *clip = item->referencedClip();
2561                 int maxImageSize = m_doc->getDocumentProperty("proxyimageminsize").toInt();
2562                 if (clip->getProperty("frame_size").section('x', 0, 0).toInt() > maxImageSize || clip->getProperty("frame_size").section('x', 1, 1).toInt() > maxImageSize) {
2563                     if (clip->getProperty("proxy").isEmpty()) {
2564                         // We need to insert empty proxy in old properties so that undo will work
2565                         QMap <QString, QString> oldProps = clip->properties();
2566                         oldProps.insert("proxy", QString());
2567                         QMap <QString, QString> newProps;
2568                         newProps.insert("proxy", proxydir + item->referencedClip()->getClipHash() + ".png");
2569                         new EditClipCommand(this, clip->getId(), oldProps, newProps, true, command);
2570                     }
2571                 }
2572             }
2573             else if (item->hasProxy()) {
2574                 // remove proxy
2575                 QMap <QString, QString> newProps;
2576                 newProps.insert("proxy", QString());
2577                 newProps.insert("replace", "1");
2578                 new EditClipCommand(this, item->clipId(), item->referencedClip()->properties(), newProps, true, command);
2579             }
2580         }
2581         ++it;
2582     }
2583     if (command->childCount() > 0) m_doc->commandStack()->push(command);
2584     else delete command;
2585 }
2586
2587 void ProjectList::slotProxyCurrentItem(bool doProxy)
2588 {
2589     QList<QTreeWidgetItem *> list = m_listView->selectedItems();
2590     QTreeWidgetItem *listItem;
2591     QUndoCommand *command = new QUndoCommand();
2592     if (doProxy) command->setText(i18np("Add proxy clip", "Add proxy clips", list.count()));
2593     else command->setText(i18np("Remove proxy clip", "Remove proxy clips", list.count()));
2594     
2595     // Make sure the proxy folder exists
2596     QString proxydir = m_doc->projectFolder().path( KUrl::AddTrailingSlash) + "proxy/";
2597     KStandardDirs::makeDir(proxydir);
2598                 
2599     QMap <QString, QString> newProps;
2600     QMap <QString, QString> oldProps;
2601     if (!doProxy) newProps.insert("proxy", "-");
2602     for (int i = 0; i < list.count(); i++) {
2603         listItem = list.at(i);
2604         if (listItem->type() == PROJECTFOLDERTYPE) {
2605             for (int j = 0; j < listItem->childCount(); j++) {
2606                 QTreeWidgetItem *sub = listItem->child(j);
2607                 if (!list.contains(sub)) list.append(sub);
2608             }
2609         }
2610         else if (listItem->type() == PROJECTSUBCLIPTYPE) {
2611             QTreeWidgetItem *sub = listItem->parent();
2612             if (!list.contains(sub)) list.append(sub);
2613         }
2614         else if (listItem->type() == PROJECTCLIPTYPE) {
2615             ProjectItem *item = static_cast <ProjectItem*>(listItem);
2616             CLIPTYPE t = item->clipType();
2617             if ((t == VIDEO || t == AV || t == UNKNOWN || t == IMAGE || t == PLAYLIST) && item->referencedClip()) {
2618                 if ((doProxy && item->hasProxy()) || (!doProxy && !item->hasProxy())) continue;
2619                 DocClipBase *clip = item->referencedClip();
2620                 if (!clip || !clip->isClean() || m_render->isProcessing(item->clipId())) {
2621                     kDebug()<<"//// TRYING TO PROXY: "<<item->clipId()<<", but it is busy";
2622                     continue;
2623                 }
2624                 
2625                 resetThumbsProducer(clip);
2626                 oldProps = clip->properties();
2627                 if (doProxy) {
2628                     newProps.clear();
2629                     QString path = proxydir + clip->getClipHash() + "." + (t == IMAGE ? "png" : m_doc->getDocumentProperty("proxyextension"));
2630                     // insert required duration for proxy
2631                     newProps.insert("proxy_out", clip->producerProperty("out"));
2632                     newProps.insert("proxy", path);
2633                     // We need to insert empty proxy so that undo will work
2634                     oldProps.insert("proxy", QString());
2635                 }
2636                 new EditClipCommand(this, item->clipId(), oldProps, newProps, true, command);
2637             }
2638         }
2639     }
2640     if (command->childCount() > 0) {
2641         m_doc->commandStack()->push(command);
2642     }
2643     else delete command;
2644 }
2645
2646
2647 void ProjectList::slotDeleteProxy(const QString proxyPath)
2648 {
2649     if (proxyPath.isEmpty()) return;
2650     QUndoCommand *proxyCommand = new QUndoCommand();
2651     proxyCommand->setText(i18n("Remove Proxy"));
2652     QTreeWidgetItemIterator it(m_listView);
2653     ProjectItem *item;
2654     while (*it) {
2655         if ((*it)->type() == PROJECTCLIPTYPE) {
2656             item = static_cast <ProjectItem *>(*it);
2657             if (item->referencedClip()->getProperty("proxy") == proxyPath) {
2658                 QMap <QString, QString> props;
2659                 props.insert("proxy", QString());
2660                 new EditClipCommand(this, item->clipId(), item->referencedClip()->properties(), props, true, proxyCommand);
2661             
2662             }
2663         }
2664         ++it;
2665     }
2666     if (proxyCommand->childCount() == 0)
2667         delete proxyCommand;
2668     else
2669         m_commandStack->push(proxyCommand);
2670     QFile::remove(proxyPath);
2671 }
2672
2673 void ProjectList::setProxyStatus(const QString proxyPath, PROXYSTATUS status, int progress)
2674 {
2675     if (proxyPath.isEmpty() || m_abortAllProxies) return;
2676     QTreeWidgetItemIterator it(m_listView);
2677     ProjectItem *item;
2678     while (*it) {
2679         if ((*it)->type() == PROJECTCLIPTYPE) {
2680             item = static_cast <ProjectItem *>(*it);
2681             if (item->referencedClip()->getProperty("proxy") == proxyPath) {
2682                 setProxyStatus(item, status, progress);
2683             }
2684         }
2685         ++it;
2686     }
2687 }
2688
2689 void ProjectList::setProxyStatus(ProjectItem *item, PROXYSTATUS status, int progress)
2690 {
2691     if (item == NULL) return;
2692     monitorItemEditing(false);
2693     item->setProxyStatus(status, progress);
2694     monitorItemEditing(true);
2695 }
2696
2697 void ProjectList::monitorItemEditing(bool enable)
2698 {
2699     if (enable) connect(m_listView, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this, SLOT(slotItemEdited(QTreeWidgetItem *, int)));     
2700     else disconnect(m_listView, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this, SLOT(slotItemEdited(QTreeWidgetItem *, int)));     
2701 }
2702
2703 QStringList ProjectList::expandedFolders() const
2704 {
2705     QStringList result;
2706     FolderProjectItem *item;
2707     QTreeWidgetItemIterator it(m_listView);
2708     while (*it) {
2709         if ((*it)->type() != PROJECTFOLDERTYPE) {
2710             ++it;
2711             continue;
2712         }
2713         if ((*it)->isExpanded()) {
2714             item = static_cast<FolderProjectItem *>(*it);
2715             result.append(item->clipId());
2716         }
2717         ++it;
2718     }
2719     return result;
2720 }
2721
2722 #include "projectlist.moc"