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