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