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