]> git.sesse.net Git - kdenlive/blob - src/projectlist.cpp
Fix project tree disabled after trying to add invalid clip
[kdenlive] / src / projectlist.cpp
1 /***************************************************************************
2  *   Copyright (C) 2007 by Jean-Baptiste Mardelle (jb@kdenlive.org)        *
3  *                                                                         *
4  *   This program is free software; you can redistribute it and/or modify  *
5  *   it under the terms of the GNU General Public License as published by  *
6  *   the Free Software Foundation; either version 2 of the License, or     *
7  *   (at your option) any later version.                                   *
8  *                                                                         *
9  *   This program is distributed in the hope that it will be useful,       *
10  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
11  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
12  *   GNU General Public License for more details.                          *
13  *                                                                         *
14  *   You should have received a copy of the GNU General Public License     *
15  *   along with this program; if not, write to the                         *
16  *   Free Software Foundation, Inc.,                                       *
17  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA          *
18  ***************************************************************************/
19
20 #include "projectlist.h"
21 #include "projectitem.h"
22 #include "addfoldercommand.h"
23 #include "kdenlivesettings.h"
24 #include "slideshowclip.h"
25 #include "ui_colorclip_ui.h"
26 #include "titlewidget.h"
27 #include "definitions.h"
28 #include "clipmanager.h"
29 #include "docclipbase.h"
30 #include "kdenlivedoc.h"
31 #include "renderer.h"
32 #include "kthumb.h"
33 #include "projectlistview.h"
34 #include "timecodedisplay.h"
35 #include "profilesdialog.h"
36 #include "editclipcommand.h"
37 #include "editclipcutcommand.h"
38 #include "editfoldercommand.h"
39 #include "addclipcutcommand.h"
40
41 #include "ui_templateclip_ui.h"
42
43 #include <KDebug>
44 #include <KAction>
45 #include <KLocale>
46 #include <KFileDialog>
47 #include <KInputDialog>
48 #include <KMessageBox>
49 #include <KIO/NetAccess>
50 #include <KFileItem>
51 #include <KApplication>
52 #include <KStandardDirs>
53
54 #ifdef NEPOMUK
55 #include <nepomuk/global.h>
56 #include <nepomuk/resourcemanager.h>
57 //#include <nepomuk/tag.h>
58 #endif
59
60 #include <QMouseEvent>
61 #include <QStylePainter>
62 #include <QPixmap>
63 #include <QIcon>
64 #include <QMenu>
65 #include <QProcess>
66 #include <QHeaderView>
67 #include <QInputDialog>
68 #include <QtConcurrentRun>
69
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     connect(this, SIGNAL(processNextThumbnail()), this, SLOT(slotProcessNextThumbnail()));
118     connect(m_listView, SIGNAL(projectModified()), this, SIGNAL(projectModified()));
119     connect(m_listView, SIGNAL(itemSelectionChanged()), this, SLOT(slotClipSelected()));
120     connect(m_listView, SIGNAL(focusMonitor()), this, SLOT(slotClipSelected()));
121     connect(m_listView, SIGNAL(pauseMonitor()), this, SLOT(slotPauseMonitor()));
122     connect(m_listView, SIGNAL(requestMenu(const QPoint &, QTreeWidgetItem *)), this, SLOT(slotContextMenu(const QPoint &, QTreeWidgetItem *)));
123     connect(m_listView, SIGNAL(addClip()), this, SLOT(slotAddClip()));
124     connect(m_listView, SIGNAL(addClip(const QList <QUrl>, const QString &, const QString &)), this, SLOT(slotAddClip(const QList <QUrl>, const QString &, const QString &)));
125     connect(m_listView, SIGNAL(addClipCut(const QString &, int, int)), this, SLOT(slotAddClipCut(const QString &, int, int)));
126     connect(m_listView, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this, SLOT(slotItemEdited(QTreeWidgetItem *, int)));
127     connect(m_listView, SIGNAL(showProperties(DocClipBase *)), this, SIGNAL(showClipProperties(DocClipBase *)));
128
129     m_listViewDelegate = new ItemDelegate(m_listView);
130     m_listView->setItemDelegate(m_listViewDelegate);
131 #ifdef NEPOMUK
132     if (KdenliveSettings::activate_nepomuk()) {
133         Nepomuk::ResourceManager::instance()->init();
134         if (!Nepomuk::ResourceManager::instance()->initialized()) {
135             kDebug() << "Cannot communicate with Nepomuk, DISABLING it";
136             KdenliveSettings::setActivate_nepomuk(false);
137         }
138     }
139 #endif
140 }
141
142 ProjectList::~ProjectList()
143 {
144     delete m_menu;
145     m_listView->blockSignals(true);
146     m_listView->clear();
147     delete m_listViewDelegate;
148 }
149
150 void ProjectList::focusTree() const
151 {
152     m_listView->setFocus();
153 }
154
155 void ProjectList::setupMenu(QMenu *addMenu, QAction *defaultAction)
156 {
157     QList <QAction *> actions = addMenu->actions();
158     for (int i = 0; i < actions.count(); i++) {
159         if (actions.at(i)->data().toString() == "clip_properties") {
160             m_editButton->setDefaultAction(actions.at(i));
161             actions.removeAt(i);
162             i--;
163         } else if (actions.at(i)->data().toString() == "delete_clip") {
164             m_deleteButton->setDefaultAction(actions.at(i));
165             actions.removeAt(i);
166             i--;
167         } else if (actions.at(i)->data().toString() == "edit_clip") {
168             m_openAction = actions.at(i);
169             actions.removeAt(i);
170             i--;
171         } else if (actions.at(i)->data().toString() == "reload_clip") {
172             m_reloadAction = actions.at(i);
173             actions.removeAt(i);
174             i--;
175         } else if (actions.at(i)->data().toString() == "proxy_clip") {
176             m_proxyAction = 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
1098     // Make sure we get the correct producer length if it was adjusted in timeline
1099     CLIPTYPE t = item->clipType();
1100     if (t == COLOR || t == IMAGE || t == SLIDESHOW || t == TEXT) {
1101         int length = QString(clip->producerProperty("length")).toInt();
1102         if (length > 0 && !e.hasAttribute("length")) {
1103             e.setAttribute("length", length);
1104         }
1105     }
1106     e.setAttribute("replace", 1);
1107     m_infoQueue.insert(clip->getId(), e);
1108     if (!m_queueRunner.isRunning() && m_processingClips.isEmpty()) m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);   
1109 }
1110
1111 void ProjectList::slotResetProjectList()
1112 {
1113     m_listView->clear();
1114     emit clipSelected(NULL);
1115     m_thumbnailQueue.clear();
1116     m_infoQueue.clear();
1117     m_refreshed = false;
1118 }
1119
1120 void ProjectList::requestClipInfo(const QDomElement xml, const QString id)
1121 {
1122     m_infoQueue.insert(id, xml);
1123     //if (m_infoQueue.count() == 1 || ) QTimer::singleShot(300, this, SLOT(slotProcessNextClipInQueue()));
1124 }
1125
1126 void ProjectList::slotProcessNextClipInQueue()
1127 {
1128     if (m_infoQueue.isEmpty()) {
1129         emit processNextThumbnail();
1130         return;
1131     }
1132
1133     QMap<QString, QDomElement>::const_iterator j = m_infoQueue.constBegin();
1134     if (j != m_infoQueue.constEnd()) {
1135         QDomElement dom = j.value().cloneNode().toElement();
1136         const QString id = j.key();
1137         m_infoQueue.remove(id);
1138         m_processingClips.append(id);
1139         bool replace;
1140         if (dom.hasAttribute("replace")) {
1141             // Proxy action was enabled / disabled and we want to replace current producer
1142             dom.removeAttribute("replace");
1143             replace = true;
1144         }
1145         else replace = false;
1146         bool selectClip = !replace;
1147         if (m_infoQueue.count() > 1) selectClip = false;
1148         emit getFileProperties(dom, id, m_listView->iconSize().height(), replace, selectClip);
1149     }
1150 }
1151
1152 void ProjectList::slotUpdateClip(const QString &id)
1153 {
1154     ProjectItem *item = getItemById(id);
1155     monitorItemEditing(false);
1156     if (item) item->setData(0, UsageRole, QString::number(item->numReferences()));
1157     monitorItemEditing(true);
1158 }
1159
1160 void ProjectList::updateAllClips(bool displayRatioChanged, bool fpsChanged)
1161 {
1162     m_listView->setSortingEnabled(false);
1163
1164     QTreeWidgetItemIterator it(m_listView);
1165     DocClipBase *clip;
1166     ProjectItem *item;
1167     monitorItemEditing(false);
1168     int height = m_listView->iconSize().height();
1169     int width = (int)(height  * m_render->dar());
1170     QPixmap missingPixmap = QPixmap(width, height);
1171     missingPixmap.fill(Qt::transparent);
1172     KIcon icon("dialog-close");
1173     QPainter p(&missingPixmap);
1174     p.drawPixmap(3, 3, icon.pixmap(width - 6, height - 6));
1175     p.end();
1176                         
1177     while (*it) {
1178         if ((*it)->type() == PROJECTSUBCLIPTYPE) {
1179             // subitem
1180             SubProjectItem *sub = static_cast <SubProjectItem *>(*it);
1181             if (displayRatioChanged || sub->data(0, Qt::DecorationRole).isNull()) {
1182                 item = static_cast <ProjectItem *>((*it)->parent());
1183                 requestClipThumbnail(item->clipId() + '#' + QString::number(sub->zone().x()));
1184             }
1185             ++it;
1186             continue;
1187         } else if ((*it)->type() == PROJECTFOLDERTYPE) {
1188             // folder
1189             ++it;
1190             continue;
1191         } else {
1192             item = static_cast <ProjectItem *>(*it);
1193             clip = item->referencedClip();
1194             if (item->referencedClip()->producer() == NULL) {
1195                 if (clip->isPlaceHolder() == false) {
1196                     QDomElement xml = clip->toXML();
1197                     if (fpsChanged) {
1198                         xml.removeAttribute("out");
1199                         xml.removeAttribute("file_hash");
1200                         xml.removeAttribute("proxy_out");
1201                     }
1202                     requestClipInfo(xml, clip->getId());
1203                 }
1204                 else {
1205                     item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsDropEnabled);
1206                     if (item->data(0, Qt::DecorationRole).isNull()) {
1207                         item->setData(0, Qt::DecorationRole, missingPixmap);
1208                     }
1209                     else {
1210                         QPixmap pixmap = qVariantValue<QPixmap>(item->data(0, Qt::DecorationRole));
1211                         QPainter p(&pixmap);
1212                         p.drawPixmap(3, 3, KIcon("dialog-close").pixmap(pixmap.width() - 6, pixmap.height() - 6));
1213                         p.end();
1214                         item->setData(0, Qt::DecorationRole, pixmap);
1215                     }
1216                 }
1217             } else {
1218                 if (displayRatioChanged || item->data(0, Qt::DecorationRole).isNull())
1219                     requestClipThumbnail(clip->getId());
1220                 if (item->data(0, DurationRole).toString().isEmpty()) {
1221                     item->changeDuration(item->referencedClip()->producer()->get_playtime());
1222                 }
1223                 if (clip->isPlaceHolder()) {
1224                     QPixmap pixmap = qVariantValue<QPixmap>(item->data(0, Qt::DecorationRole));
1225                     if (pixmap.isNull()) {
1226                         pixmap = QPixmap(width, height);
1227                         pixmap.fill(Qt::transparent);
1228                     }
1229                     QPainter p(&pixmap);
1230                     p.drawPixmap(3, 3, KIcon("dialog-close").pixmap(pixmap.width() - 6, pixmap.height() - 6));
1231                     p.end();
1232                     item->setData(0, Qt::DecorationRole, pixmap);
1233                 }
1234             }
1235             item->setData(0, UsageRole, QString::number(item->numReferences()));
1236         }
1237         ++it;
1238     }
1239
1240     if (!m_queueRunner.isRunning() && m_processingClips.isEmpty()) m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
1241     if (m_listView->isEnabled())
1242         monitorItemEditing(true);
1243     m_listView->setSortingEnabled(true);
1244     if (m_infoQueue.isEmpty()) {
1245        slotProcessNextThumbnail();
1246     }
1247 }
1248
1249 // static
1250 QString ProjectList::getExtensions()
1251 {
1252     // Build list of mime types
1253     QStringList mimeTypes = QStringList() << "application/x-kdenlive" << "application/x-kdenlivetitle" << "video/mlt-playlist" << "text/plain"
1254                             << "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"
1255                             << "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"
1256                             << "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";
1257
1258     QString allExtensions;
1259     foreach(const QString & mimeType, mimeTypes) {
1260         KMimeType::Ptr mime(KMimeType::mimeType(mimeType));
1261         if (mime) {
1262             allExtensions.append(mime->patterns().join(" "));
1263             allExtensions.append(' ');
1264         }
1265     }
1266     return allExtensions.simplified();
1267 }
1268
1269 void ProjectList::slotAddClip(const QList <QUrl> givenList, const QString &groupName, const QString &groupId)
1270 {
1271     if (!m_commandStack)
1272         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1273
1274     KUrl::List list;
1275     if (givenList.isEmpty()) {
1276         QString allExtensions = getExtensions();
1277         const QString dialogFilter = allExtensions + ' ' + QLatin1Char('|') + i18n("All Supported Files") + "\n* " + QLatin1Char('|') + i18n("All Files");
1278         QCheckBox *b = new QCheckBox(i18n("Import image sequence"));
1279         b->setChecked(KdenliveSettings::autoimagesequence());
1280         QCheckBox *c = new QCheckBox(i18n("Transparent background for images"));
1281         c->setChecked(KdenliveSettings::autoimagetransparency());
1282         QFrame *f = new QFrame;
1283         f->setFrameShape(QFrame::NoFrame);
1284         QHBoxLayout *l = new QHBoxLayout;
1285         l->addWidget(b);
1286         l->addWidget(c);
1287         l->addStretch(5);
1288         f->setLayout(l);
1289         KFileDialog *d = new KFileDialog(KUrl("kfiledialog:///clipfolder"), dialogFilter, kapp->activeWindow(), f);
1290         d->setOperationMode(KFileDialog::Opening);
1291         d->setMode(KFile::Files);
1292         if (d->exec() == QDialog::Accepted) {
1293             KdenliveSettings::setAutoimagetransparency(c->isChecked());
1294         }
1295         list = d->selectedUrls();
1296         if (b->isChecked() && list.count() == 1) {
1297             // Check for image sequence
1298             KUrl url = list.at(0);
1299             QString fileName = url.fileName().section('.', 0, -2);
1300             if (fileName.at(fileName.size() - 1).isDigit()) {
1301                 KFileItem item(KFileItem::Unknown, KFileItem::Unknown, url);
1302                 if (item.mimetype().startsWith("image")) {
1303                     // import as sequence if we found more than one image in the sequence
1304                     QStringList list;
1305                     QString pattern = SlideshowClip::selectedPath(url.path(), false, QString(), &list);
1306                     int count = list.count();
1307                     if (count > 1) {
1308                         delete d;
1309                         QStringList groupInfo = getGroup();
1310
1311                         // get image sequence base name
1312                         while (fileName.at(fileName.size() - 1).isDigit()) {
1313                             fileName.chop(1);
1314                         }
1315
1316                         m_doc->slotCreateSlideshowClipFile(fileName, pattern, count, m_timecode.reformatSeparators(KdenliveSettings::sequence_duration()),
1317                                                            false, false, false,
1318                                                            m_timecode.getTimecodeFromFrames(int(ceil(m_timecode.fps()))), QString(), 0,
1319                                                            QString(), groupInfo.at(0), groupInfo.at(1));
1320                         return;
1321                     }
1322                 }
1323             }
1324         }
1325         delete d;
1326     } else {
1327         for (int i = 0; i < givenList.count(); i++)
1328             list << givenList.at(i);
1329     }
1330
1331     foreach(const KUrl & file, list) {
1332         // Check there is no folder here
1333         KMimeType::Ptr type = KMimeType::findByUrl(file);
1334         if (type->is("inode/directory")) {
1335             // user dropped a folder
1336             list.removeAll(file);
1337         }
1338     }
1339
1340     if (list.isEmpty())
1341         return;
1342
1343     if (givenList.isEmpty()) {
1344         QStringList groupInfo = getGroup();
1345         m_doc->slotAddClipList(list, groupInfo.at(0), groupInfo.at(1));
1346     } else {
1347         m_doc->slotAddClipList(list, groupName, groupId);
1348     }
1349 }
1350
1351 void ProjectList::slotRemoveInvalidClip(const QString &id, bool replace)
1352 {
1353     ProjectItem *item = getItemById(id);
1354     m_processingClips.removeAll(id);
1355     m_thumbnailQueue.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     m_thumbnailQueue.removeAll(id);
1390     if (!m_queueRunner.isRunning() && m_processingClips.isEmpty()) m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
1391 }
1392
1393 void ProjectList::slotAddColorClip()
1394 {
1395     if (!m_commandStack)
1396         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1397
1398     QDialog *dia = new QDialog(this);
1399     Ui::ColorClip_UI dia_ui;
1400     dia_ui.setupUi(dia);
1401     dia->setWindowTitle(i18n("Color Clip"));
1402     dia_ui.clip_name->setText(i18n("Color Clip"));
1403
1404     TimecodeDisplay *t = new TimecodeDisplay(m_timecode);
1405     t->setValue(KdenliveSettings::color_duration());
1406     t->setTimeCodeFormat(false);
1407     dia_ui.clip_durationBox->addWidget(t);
1408     dia_ui.clip_color->setColor(KdenliveSettings::colorclipcolor());
1409
1410     if (dia->exec() == QDialog::Accepted) {
1411         QString color = dia_ui.clip_color->color().name();
1412         KdenliveSettings::setColorclipcolor(color);
1413         color = color.replace(0, 1, "0x") + "ff";
1414         QStringList groupInfo = getGroup();
1415         m_doc->slotCreateColorClip(dia_ui.clip_name->text(), color, m_timecode.getTimecode(t->gentime()), groupInfo.at(0), groupInfo.at(1));
1416     }
1417     delete t;
1418     delete dia;
1419 }
1420
1421
1422 void ProjectList::slotAddSlideshowClip()
1423 {
1424     if (!m_commandStack)
1425         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1426
1427     SlideshowClip *dia = new SlideshowClip(m_timecode, this);
1428
1429     if (dia->exec() == QDialog::Accepted) {
1430         QStringList groupInfo = getGroup();
1431         m_doc->slotCreateSlideshowClipFile(dia->clipName(), dia->selectedPath(), dia->imageCount(), dia->clipDuration(),
1432                                            dia->loop(), dia->crop(), dia->fade(),
1433                                            dia->lumaDuration(), dia->lumaFile(), dia->softness(),
1434                                            dia->animation(), groupInfo.at(0), groupInfo.at(1));
1435     }
1436     delete dia;
1437 }
1438
1439 void ProjectList::slotAddTitleClip()
1440 {
1441     QStringList groupInfo = getGroup();
1442     m_doc->slotCreateTextClip(groupInfo.at(0), groupInfo.at(1));
1443 }
1444
1445 void ProjectList::slotAddTitleTemplateClip()
1446 {
1447     if (!m_commandStack)
1448         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1449
1450     QStringList groupInfo = getGroup();
1451
1452     // Get the list of existing templates
1453     QStringList filter;
1454     filter << "*.kdenlivetitle";
1455     const QString path = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1456     QStringList templateFiles = QDir(path).entryList(filter, QDir::Files);
1457
1458     QDialog *dia = new QDialog(this);
1459     Ui::TemplateClip_UI dia_ui;
1460     dia_ui.setupUi(dia);
1461     for (int i = 0; i < templateFiles.size(); ++i)
1462         dia_ui.template_list->comboBox()->addItem(templateFiles.at(i), path + templateFiles.at(i));
1463
1464     if (!templateFiles.isEmpty())
1465         dia_ui.buttonBox->button(QDialogButtonBox::Ok)->setFocus();
1466     dia_ui.template_list->fileDialog()->setFilter("application/x-kdenlivetitle");
1467     //warning: setting base directory doesn't work??
1468     KUrl startDir(path);
1469     dia_ui.template_list->fileDialog()->setUrl(startDir);
1470     dia_ui.text_box->setHidden(true);
1471     if (dia->exec() == QDialog::Accepted) {
1472         QString textTemplate = dia_ui.template_list->comboBox()->itemData(dia_ui.template_list->comboBox()->currentIndex()).toString();
1473         if (textTemplate.isEmpty()) textTemplate = dia_ui.template_list->comboBox()->currentText();
1474         // Create a cloned template clip
1475         m_doc->slotCreateTextTemplateClip(groupInfo.at(0), groupInfo.at(1), KUrl(textTemplate));
1476     }
1477     delete dia;
1478 }
1479
1480 QStringList ProjectList::getGroup() const
1481 {
1482     QStringList result;
1483     QTreeWidgetItem *item = m_listView->currentItem();
1484     while (item && item->type() != PROJECTFOLDERTYPE)
1485         item = item->parent();
1486
1487     if (item) {
1488         FolderProjectItem *folder = static_cast <FolderProjectItem *>(item);
1489         result << folder->groupName() << folder->clipId();
1490     } else {
1491         result << QString() << QString();
1492     }
1493     return result;
1494 }
1495
1496 void ProjectList::setDocument(KdenliveDoc *doc)
1497 {
1498     m_listView->blockSignals(true);
1499     m_listView->clear();
1500     m_processingClips.clear();
1501     m_listView->setSortingEnabled(false);
1502     emit clipSelected(NULL);
1503     m_thumbnailQueue.clear();
1504     m_infoQueue.clear();
1505     m_refreshed = false;
1506     m_fps = doc->fps();
1507     m_timecode = doc->timecode();
1508     m_commandStack = doc->commandStack();
1509     m_doc = doc;
1510
1511     QMap <QString, QString> flist = doc->clipManager()->documentFolderList();
1512     QStringList openedFolders = doc->getExpandedFolders();
1513     QMapIterator<QString, QString> f(flist);
1514     while (f.hasNext()) {
1515         f.next();
1516         FolderProjectItem *folder = new FolderProjectItem(m_listView, QStringList() << f.value(), f.key());
1517         folder->setExpanded(openedFolders.contains(f.key()));
1518     }
1519
1520     QList <DocClipBase*> list = doc->clipManager()->documentClipList();
1521     for (int i = 0; i < list.count(); i++)
1522         slotAddClip(list.at(i), false);
1523
1524     m_listView->blockSignals(false);
1525     connect(m_doc->clipManager(), SIGNAL(reloadClip(const QString &)), this, SLOT(slotReloadClip(const QString &)));
1526     connect(m_doc->clipManager(), SIGNAL(modifiedClip(const QString &)), this, SLOT(slotModifiedClip(const QString &)));
1527     connect(m_doc->clipManager(), SIGNAL(missingClip(const QString &)), this, SLOT(slotMissingClip(const QString &)));
1528     connect(m_doc->clipManager(), SIGNAL(availableClip(const QString &)), this, SLOT(slotAvailableClip(const QString &)));
1529     connect(m_doc->clipManager(), SIGNAL(checkAllClips(bool, bool)), this, SLOT(updateAllClips(bool, bool)));
1530 }
1531
1532 QList <DocClipBase*> ProjectList::documentClipList() const
1533 {
1534     if (m_doc == NULL)
1535         return QList <DocClipBase*> ();
1536
1537     return m_doc->clipManager()->documentClipList();
1538 }
1539
1540 QDomElement ProjectList::producersList()
1541 {
1542     QDomDocument doc;
1543     QDomElement prods = doc.createElement("producerlist");
1544     doc.appendChild(prods);
1545     kDebug() << "////////////  PRO LIST BUILD PRDSLIST ";
1546     QTreeWidgetItemIterator it(m_listView);
1547     while (*it) {
1548         if ((*it)->type() != PROJECTCLIPTYPE) {
1549             // subitem
1550             ++it;
1551             continue;
1552         }
1553         prods.appendChild(doc.importNode(((ProjectItem *)(*it))->toXml(), true));
1554         ++it;
1555     }
1556     return prods;
1557 }
1558
1559 void ProjectList::slotCheckForEmptyQueue()
1560 {
1561     if (m_processingClips.isEmpty() && m_thumbnailQueue.isEmpty() && m_infoQueue.isEmpty()) {
1562         if (!m_refreshed) {
1563             emit loadingIsOver();
1564             emit displayMessage(QString(), -1);
1565         }
1566         m_refreshed = true;
1567         m_listView->blockSignals(false);
1568         m_listView->setEnabled(true);
1569         updateButtons();
1570     } else if (!m_refreshed) {
1571         QTimer::singleShot(300, this, SLOT(slotCheckForEmptyQueue()));
1572     }
1573 }
1574
1575
1576 void ProjectList::requestClipThumbnail(const QString id)
1577 {
1578     if (!m_thumbnailQueue.contains(id)) m_thumbnailQueue.append(id);
1579 }
1580
1581 void ProjectList::slotProcessNextThumbnail()
1582 {
1583     if (m_thumbnailQueue.isEmpty() && m_infoQueue.isEmpty()) {
1584         slotCheckForEmptyQueue();
1585         return;
1586     }
1587     if (!m_infoQueue.isEmpty()) {
1588         //QTimer::singleShot(300, this, SLOT(slotProcessNextThumbnail()));
1589         return;
1590     }
1591     if (m_thumbnailQueue.count() > 1) {
1592         int max = m_doc->clipManager()->clipsCount();
1593         emit displayMessage(i18n("Loading thumbnails"), (int)(100 *(max - m_thumbnailQueue.count()) / max));
1594     }
1595     slotRefreshClipThumbnail(m_thumbnailQueue.takeFirst(), false);
1596 }
1597
1598 void ProjectList::slotRefreshClipThumbnail(const QString &clipId, bool update)
1599 {
1600     QTreeWidgetItem *item = getAnyItemById(clipId);
1601     if (item)
1602         slotRefreshClipThumbnail(item, update);
1603     else {
1604         slotProcessNextThumbnail();
1605     }
1606 }
1607
1608 void ProjectList::slotRefreshClipThumbnail(QTreeWidgetItem *it, bool update)
1609 {
1610     if (it == NULL) return;
1611     ProjectItem *item = NULL;
1612     bool isSubItem = false;
1613     int frame;
1614     if (it->type() == PROJECTFOLDERTYPE) return;
1615     if (it->type() == PROJECTSUBCLIPTYPE) {
1616         item = static_cast <ProjectItem *>(it->parent());
1617         frame = static_cast <SubProjectItem *>(it)->zone().x();
1618         isSubItem = true;
1619     } else {
1620         item = static_cast <ProjectItem *>(it);
1621         frame = item->referencedClip()->getClipThumbFrame();
1622     }
1623
1624     if (item) {
1625         DocClipBase *clip = item->referencedClip();
1626         if (!clip) {
1627             slotProcessNextThumbnail();
1628             return;
1629         }
1630         QPixmap pix;
1631         int height = m_listView->iconSize().height();
1632         int width = (int)(height  * m_render->dar());
1633         if (clip->clipType() == AUDIO)
1634             pix = KIcon("audio-x-generic").pixmap(QSize(width, height));
1635         else if (clip->clipType() == IMAGE)
1636             pix = QPixmap::fromImage(KThumb::getFrame(item->referencedClip()->producer(), 0, width, height));
1637         else
1638             pix = item->referencedClip()->extractImage(frame, width, height);
1639
1640         if (!pix.isNull()) {
1641             monitorItemEditing(false);
1642             it->setData(0, Qt::DecorationRole, pix);
1643             monitorItemEditing(true);
1644                 
1645             if (!isSubItem)
1646                 m_doc->cachePixmap(item->getClipHash(), pix);
1647             else
1648                 m_doc->cachePixmap(item->getClipHash() + '#' + QString::number(frame), pix);
1649         }
1650         if (update)
1651             emit projectModified();
1652         slotProcessNextThumbnail();
1653     }
1654 }
1655
1656 void ProjectList::slotReplyGetFileProperties(const QString &clipId, Mlt::Producer *producer, const QMap < QString, QString > &properties, const QMap < QString, QString > &metadata, bool replace, bool selectClip)
1657 {
1658     QString toReload;
1659     ProjectItem *item = getItemById(clipId);
1660     if (!m_refreshed) {
1661         // we are still finishing to load the document
1662         selectClip = false;
1663     }
1664     m_processingClips.removeAll(clipId);
1665     if (m_infoQueue.isEmpty() && m_processingClips.isEmpty()) m_listView->setEnabled(true);
1666     if (item && producer) {
1667         //m_listView->blockSignals(true);
1668         monitorItemEditing(false);
1669         DocClipBase *clip = item->referencedClip();
1670         item->setProperties(properties, metadata);
1671         if (clip->isPlaceHolder() && producer->is_valid()) {
1672             clip->setValid();
1673             item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsDropEnabled);
1674             toReload = clipId;
1675         }
1676         clip->setProducer(producer, replace);
1677         clip->askForAudioThumbs();
1678         // Proxy stuff
1679         QString size = properties.value("frame_size");
1680         if (!useProxy() && clip->getProperty("proxy").isEmpty()) setProxyStatus(item, NOPROXY);
1681         if (useProxy() && generateProxy() && clip->getProperty("proxy") == "-") setProxyStatus(item, NOPROXY);
1682         else if (useProxy() && !item->isProxyRunning()) {
1683             // proxy video and image clips
1684             int maxSize;
1685             CLIPTYPE t = item->clipType();
1686             if (t == IMAGE) maxSize = m_doc->getDocumentProperty("proxyimageminsize").toInt();
1687             else maxSize = m_doc->getDocumentProperty("proxyminsize").toInt();
1688             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)) {
1689                 if (clip->getProperty("proxy").isEmpty()) {
1690                     KUrl proxyPath = m_doc->projectFolder();
1691                     proxyPath.addPath("proxy/");
1692                     proxyPath.addPath(clip->getClipHash() + "." + (t == IMAGE ? "png" : m_doc->getDocumentProperty("proxyextension")));
1693                     QMap <QString, QString> newProps;
1694                     // insert required duration for proxy
1695                     if (t != IMAGE) newProps.insert("proxy_out", clip->producerProperty("out"));
1696                     newProps.insert("proxy", proxyPath.path());
1697                     QMap <QString, QString> oldProps = clip->properties();
1698                     oldProps.insert("proxy", QString());
1699                     EditClipCommand *command = new EditClipCommand(this, clipId, oldProps, newProps, true);
1700                     m_doc->commandStack()->push(command);
1701                 }
1702             }
1703         }
1704
1705         if (!replace && item->data(0, Qt::DecorationRole).isNull())
1706             requestClipThumbnail(clipId);
1707         if (!toReload.isEmpty())
1708             item->slotSetToolTip();
1709
1710         if (m_listView->isEnabled())
1711             monitorItemEditing(true);
1712     } else kDebug() << "////////  COULD NOT FIND CLIP TO UPDATE PRPS...";
1713     if (selectClip && m_infoQueue.isEmpty()) {
1714         if (item && m_infoQueue.isEmpty() && m_thumbnailQueue.isEmpty()) {
1715             m_listView->setCurrentItem(item);
1716             bool updatedProfile = false;
1717             if (item->parent()) {
1718                 if (item->parent()->type() == PROJECTFOLDERTYPE)
1719                     static_cast <FolderProjectItem *>(item->parent())->switchIcon();
1720             } else if (KdenliveSettings::checkfirstprojectclip() &&  m_listView->topLevelItemCount() == 1) {
1721                 // this is the first clip loaded in project, check if we want to adjust project settings to the clip
1722                 updatedProfile = adjustProjectProfileToItem(item);
1723             }
1724             if (updatedProfile == false) emit clipSelected(item->referencedClip());
1725         } else {
1726             int max = m_doc->clipManager()->clipsCount();
1727             emit displayMessage(i18n("Loading clips"), (int)(100 *(max - m_infoQueue.count()) / max));
1728         }
1729     }
1730     if (item && m_listView->isEnabled() && replace) {
1731             // update clip in clip monitor
1732             if (item->isSelected() && m_listView->selectedItems().count() == 1)
1733                 emit clipSelected(item->referencedClip());
1734             //TODO: Make sure the line below has no side effect
1735             toReload = clipId;
1736         }
1737     if (!toReload.isEmpty())
1738         emit clipNeedsReload(toReload, true);
1739
1740     if (!m_queueRunner.isRunning() && m_processingClips.isEmpty()) m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
1741 }
1742
1743 bool ProjectList::adjustProjectProfileToItem(ProjectItem *item)
1744 {
1745     if (item == NULL) {
1746         if (m_listView->currentItem() && m_listView->currentItem()->type() != PROJECTFOLDERTYPE)
1747             item = static_cast <ProjectItem*>(m_listView->currentItem());
1748     }
1749     if (item == NULL || item->referencedClip() == NULL) {
1750         KMessageBox::information(kapp->activeWindow(), i18n("Cannot find profile from current clip"));
1751         return false;
1752     }
1753     bool profileUpdated = false;
1754     QString size = item->referencedClip()->getProperty("frame_size");
1755     int width = size.section('x', 0, 0).toInt();
1756     int height = size.section('x', -1).toInt();
1757     double fps = item->referencedClip()->getProperty("fps").toDouble();
1758     double par = item->referencedClip()->getProperty("aspect_ratio").toDouble();
1759     if (item->clipType() == IMAGE || item->clipType() == AV || item->clipType() == VIDEO) {
1760         if (ProfilesDialog::matchProfile(width, height, fps, par, item->clipType() == IMAGE, m_doc->mltProfile()) == false) {
1761             // get a list of compatible profiles
1762             QMap <QString, QString> suggestedProfiles = ProfilesDialog::getProfilesFromProperties(width, height, fps, par, item->clipType() == IMAGE);
1763             if (!suggestedProfiles.isEmpty()) {
1764                 KDialog *dialog = new KDialog(this);
1765                 dialog->setCaption(i18n("Change project profile"));
1766                 dialog->setButtons(KDialog::Ok | KDialog::Cancel);
1767
1768                 QWidget container;
1769                 QVBoxLayout *l = new QVBoxLayout;
1770                 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));
1771                 l->addWidget(label);
1772                 QListWidget *list = new QListWidget;
1773                 list->setAlternatingRowColors(true);
1774                 QMapIterator<QString, QString> i(suggestedProfiles);
1775                 while (i.hasNext()) {
1776                     i.next();
1777                     QListWidgetItem *item = new QListWidgetItem(i.value(), list);
1778                     item->setData(Qt::UserRole, i.key());
1779                     item->setToolTip(i.key());
1780                 }
1781                 list->setCurrentRow(0);
1782                 l->addWidget(list);
1783                 container.setLayout(l);
1784                 dialog->setButtonText(KDialog::Ok, i18n("Update profile"));
1785                 dialog->setMainWidget(&container);
1786                 if (dialog->exec() == QDialog::Accepted) {
1787                     //Change project profile
1788                     profileUpdated = true;
1789                     if (list->currentItem())
1790                         emit updateProfile(list->currentItem()->data(Qt::UserRole).toString());
1791                 }
1792                 delete list;
1793                 delete label;
1794             } else if (fps > 0) {
1795                 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));
1796             }
1797         }
1798     }
1799     return profileUpdated;
1800 }
1801
1802 QString ProjectList::getDocumentProperty(const QString &key) const
1803 {
1804     return m_doc->getDocumentProperty(key);
1805 }
1806
1807 bool ProjectList::useProxy() const
1808 {
1809     return m_doc->getDocumentProperty("enableproxy").toInt();
1810 }
1811
1812 bool ProjectList::generateProxy() const
1813 {
1814     return m_doc->getDocumentProperty("generateproxy").toInt();
1815 }
1816
1817 bool ProjectList::generateImageProxy() const
1818 {
1819     return m_doc->getDocumentProperty("generateimageproxy").toInt();
1820 }
1821
1822 void ProjectList::slotReplyGetImage(const QString &clipId, const QPixmap &pix)
1823 {
1824     ProjectItem *item = getItemById(clipId);
1825     if (item && !pix.isNull()) {
1826         monitorItemEditing(false);
1827         item->setData(0, Qt::DecorationRole, pix);
1828         monitorItemEditing(true);
1829         m_doc->cachePixmap(item->getClipHash(), pix);
1830         if (m_listView->isEnabled())
1831             m_listView->blockSignals(false);
1832     }
1833 }
1834
1835 QTreeWidgetItem *ProjectList::getAnyItemById(const QString &id)
1836 {
1837     QTreeWidgetItemIterator it(m_listView);
1838     QString lookId = id;
1839     if (id.contains('#'))
1840         lookId = id.section('#', 0, 0);
1841
1842     ProjectItem *result = NULL;
1843     while (*it) {
1844         if ((*it)->type() != PROJECTCLIPTYPE) {
1845             // subitem
1846             ++it;
1847             continue;
1848         }
1849         ProjectItem *item = static_cast<ProjectItem *>(*it);
1850         if (item->clipId() == lookId) {
1851             result = item;
1852             break;
1853         }
1854         ++it;
1855     }
1856     if (result == NULL || !id.contains('#')) {
1857         return result;
1858     } else {
1859         for (int i = 0; i < result->childCount(); i++) {
1860             SubProjectItem *sub = static_cast <SubProjectItem *>(result->child(i));
1861             if (sub && sub->zone().x() == id.section('#', 1, 1).toInt())
1862                 return sub;
1863         }
1864     }
1865
1866     return NULL;
1867 }
1868
1869
1870 ProjectItem *ProjectList::getItemById(const QString &id)
1871 {
1872     ProjectItem *item;
1873     QTreeWidgetItemIterator it(m_listView);
1874     while (*it) {
1875         if ((*it)->type() != PROJECTCLIPTYPE) {
1876             // subitem or folder
1877             ++it;
1878             continue;
1879         }
1880         item = static_cast<ProjectItem *>(*it);
1881         if (item->clipId() == id)
1882             return item;
1883         ++it;
1884     }
1885     return NULL;
1886 }
1887
1888 FolderProjectItem *ProjectList::getFolderItemById(const QString &id)
1889 {
1890     FolderProjectItem *item;
1891     QTreeWidgetItemIterator it(m_listView);
1892     while (*it) {
1893         if ((*it)->type() == PROJECTFOLDERTYPE) {
1894             item = static_cast<FolderProjectItem *>(*it);
1895             if (item->clipId() == id)
1896                 return item;
1897         }
1898         ++it;
1899     }
1900     return NULL;
1901 }
1902
1903 void ProjectList::slotSelectClip(const QString &ix)
1904 {
1905     ProjectItem *clip = getItemById(ix);
1906     if (clip) {
1907         m_listView->setCurrentItem(clip);
1908         m_listView->scrollToItem(clip);
1909         m_editButton->defaultAction()->setEnabled(true);
1910         m_deleteButton->defaultAction()->setEnabled(true);
1911         m_reloadAction->setEnabled(true);
1912         m_transcodeAction->setEnabled(true);
1913         m_proxyAction->setEnabled(useProxy());
1914         if (clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) {
1915             m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
1916             m_openAction->setEnabled(true);
1917         } else if (clip->clipType() == AUDIO && !KdenliveSettings::defaultaudioapp().isEmpty()) {
1918             m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
1919             m_openAction->setEnabled(true);
1920         } else {
1921             m_openAction->setEnabled(false);
1922         }
1923     }
1924 }
1925
1926 QString ProjectList::currentClipUrl() const
1927 {
1928     ProjectItem *item;
1929     if (!m_listView->currentItem() || m_listView->currentItem()->type() == PROJECTFOLDERTYPE) return QString();
1930     if (m_listView->currentItem()->type() == PROJECTSUBCLIPTYPE) {
1931         // subitem
1932         item = static_cast <ProjectItem*>(m_listView->currentItem()->parent());
1933     } else {
1934         item = static_cast <ProjectItem*>(m_listView->currentItem());
1935     }
1936     if (item == NULL)
1937         return QString();
1938     return item->clipUrl().path();
1939 }
1940
1941 KUrl::List ProjectList::getConditionalUrls(const QString &condition) const
1942 {
1943     KUrl::List result;
1944     ProjectItem *item;
1945     QList<QTreeWidgetItem *> list = m_listView->selectedItems();
1946     for (int i = 0; i < list.count(); i++) {
1947         if (list.at(i)->type() == PROJECTFOLDERTYPE)
1948             continue;
1949         if (list.at(i)->type() == PROJECTSUBCLIPTYPE) {
1950             // subitem
1951             item = static_cast <ProjectItem*>(list.at(i)->parent());
1952         } else {
1953             item = static_cast <ProjectItem*>(list.at(i));
1954         }
1955         if (item == NULL || item->type() == COLOR || item->type() == SLIDESHOW || item->type() == TEXT)
1956             continue;
1957         DocClipBase *clip = item->referencedClip();
1958         if (!condition.isEmpty()) {
1959             if (condition.startsWith("vcodec") && !clip->hasVideoCodec(condition.section('=', 1, 1)))
1960                 continue;
1961             else if (condition.startsWith("acodec") && !clip->hasAudioCodec(condition.section('=', 1, 1)))
1962                 continue;
1963         }
1964         result.append(item->clipUrl());
1965     }
1966     return result;
1967 }
1968
1969 void ProjectList::regenerateTemplate(const QString &id)
1970 {
1971     ProjectItem *clip = getItemById(id);
1972     if (clip)
1973         regenerateTemplate(clip);
1974 }
1975
1976 void ProjectList::regenerateTemplate(ProjectItem *clip)
1977 {
1978     //TODO: remove this unused method, only force_reload is necessary
1979     clip->referencedClip()->producer()->set("force_reload", 1);
1980 }
1981
1982 QDomDocument ProjectList::generateTemplateXml(QString path, const QString &replaceString)
1983 {
1984     QDomDocument doc;
1985     QFile file(path);
1986     if (!file.open(QIODevice::ReadOnly)) {
1987         kWarning() << "ERROR, CANNOT READ: " << path;
1988         return doc;
1989     }
1990     if (!doc.setContent(&file)) {
1991         kWarning() << "ERROR, CANNOT READ: " << path;
1992         file.close();
1993         return doc;
1994     }
1995     file.close();
1996     QDomNodeList texts = doc.elementsByTagName("content");
1997     for (int i = 0; i < texts.count(); i++) {
1998         QString data = texts.item(i).firstChild().nodeValue();
1999         data.replace("%s", replaceString);
2000         texts.item(i).firstChild().setNodeValue(data);
2001     }
2002     return doc;
2003 }
2004
2005
2006 void ProjectList::slotAddClipCut(const QString &id, int in, int out)
2007 {
2008     ProjectItem *clip = getItemById(id);
2009     if (clip == NULL || clip->referencedClip()->hasCutZone(QPoint(in, out)))
2010         return;
2011     AddClipCutCommand *command = new AddClipCutCommand(this, id, in, out, QString(), true, false);
2012     m_commandStack->push(command);
2013 }
2014
2015 void ProjectList::addClipCut(const QString &id, int in, int out, const QString desc, bool newItem)
2016 {
2017     ProjectItem *clip = getItemById(id);
2018     if (clip) {
2019         DocClipBase *base = clip->referencedClip();
2020         base->addCutZone(in, out);
2021         monitorItemEditing(false);
2022         SubProjectItem *sub = new SubProjectItem(clip, in, out, desc);
2023         if (newItem && desc.isEmpty() && !m_listView->isColumnHidden(1)) {
2024             if (!clip->isExpanded())
2025                 clip->setExpanded(true);
2026             m_listView->scrollToItem(sub);
2027             m_listView->editItem(sub, 1);
2028         }
2029         QPixmap p = clip->referencedClip()->extractImage(in, (int)(sub->sizeHint(0).height()  * m_render->dar()), sub->sizeHint(0).height() - 2);
2030         sub->setData(0, Qt::DecorationRole, p);
2031         m_doc->cachePixmap(clip->getClipHash() + '#' + QString::number(in), p);
2032         monitorItemEditing(true);
2033     }
2034     emit projectModified();
2035 }
2036
2037 void ProjectList::removeClipCut(const QString &id, int in, int out)
2038 {
2039     ProjectItem *clip = getItemById(id);
2040     if (clip) {
2041         DocClipBase *base = clip->referencedClip();
2042         base->removeCutZone(in, out);
2043         SubProjectItem *sub = getSubItem(clip, QPoint(in, out));
2044         if (sub) {
2045             monitorItemEditing(false);
2046             delete sub;
2047             monitorItemEditing(true);
2048         }
2049     }
2050     emit projectModified();
2051 }
2052
2053 SubProjectItem *ProjectList::getSubItem(ProjectItem *clip, QPoint zone)
2054 {
2055     SubProjectItem *sub = NULL;
2056     if (clip) {
2057         for (int i = 0; i < clip->childCount(); i++) {
2058             QTreeWidgetItem *it = clip->child(i);
2059             if (it->type() == PROJECTSUBCLIPTYPE) {
2060                 sub = static_cast <SubProjectItem*>(it);
2061                 if (sub->zone() == zone)
2062                     break;
2063                 else
2064                     sub = NULL;
2065             }
2066         }
2067     }
2068     return sub;
2069 }
2070
2071 void ProjectList::slotUpdateClipCut(QPoint p)
2072 {
2073     if (!m_listView->currentItem() || m_listView->currentItem()->type() != PROJECTSUBCLIPTYPE)
2074         return;
2075     SubProjectItem *sub = static_cast <SubProjectItem*>(m_listView->currentItem());
2076     ProjectItem *item = static_cast <ProjectItem *>(sub->parent());
2077     EditClipCutCommand *command = new EditClipCutCommand(this, item->clipId(), sub->zone(), p, sub->text(1), sub->text(1), true);
2078     m_commandStack->push(command);
2079 }
2080
2081 void ProjectList::doUpdateClipCut(const QString &id, const QPoint oldzone, const QPoint zone, const QString &comment)
2082 {
2083     ProjectItem *clip = getItemById(id);
2084     SubProjectItem *sub = getSubItem(clip, oldzone);
2085     if (sub == NULL || clip == NULL)
2086         return;
2087     DocClipBase *base = clip->referencedClip();
2088     base->updateCutZone(oldzone.x(), oldzone.y(), zone.x(), zone.y(), comment);
2089     monitorItemEditing(false);
2090     sub->setZone(zone);
2091     sub->setDescription(comment);
2092     monitorItemEditing(true);
2093     emit projectModified();
2094 }
2095
2096 void ProjectList::slotForceProcessing(const QString &id)
2097 {
2098     while (m_infoQueue.contains(id)) {
2099         slotProcessNextClipInQueue();
2100     }
2101 }
2102
2103 void ProjectList::slotAddOrUpdateSequence(const QString frameName)
2104 {
2105     QString fileName = KUrl(frameName).fileName().section('_', 0, -2);
2106     QStringList list;
2107     QString pattern = SlideshowClip::selectedPath(frameName, false, QString(), &list);
2108     int count = list.count();
2109     if (count > 1) {
2110         const QList <DocClipBase *> existing = m_doc->clipManager()->getClipByResource(pattern);
2111         if (!existing.isEmpty()) {
2112             // Sequence already exists, update
2113             QString id = existing.at(0)->getId();
2114             //ProjectItem *item = getItemById(id);
2115             QMap <QString, QString> oldprops;
2116             QMap <QString, QString> newprops;
2117             int ttl = existing.at(0)->getProperty("ttl").toInt();
2118             oldprops["out"] = existing.at(0)->getProperty("out");
2119             newprops["out"] = QString::number(ttl * count - 1);
2120             slotUpdateClipProperties(id, newprops);
2121             EditClipCommand *command = new EditClipCommand(this, id, oldprops, newprops, false);
2122             m_commandStack->push(command);
2123         } else {
2124             // Create sequence
2125             QStringList groupInfo = getGroup();
2126             m_doc->slotCreateSlideshowClipFile(fileName, pattern, count, m_timecode.reformatSeparators(KdenliveSettings::sequence_duration()),
2127                                                false, false, false,
2128                                                m_timecode.getTimecodeFromFrames(int(ceil(m_timecode.fps()))), QString(), 0,
2129                                                QString(), groupInfo.at(0), groupInfo.at(1));
2130         }
2131     } else emit displayMessage(i18n("Sequence not found"), -2);
2132 }
2133
2134 QMap <QString, QString> ProjectList::getProxies()
2135 {
2136     QMap <QString, QString> list;
2137     ProjectItem *item;
2138     QTreeWidgetItemIterator it(m_listView);
2139     while (*it) {
2140         if ((*it)->type() != PROJECTCLIPTYPE) {
2141             ++it;
2142             continue;
2143         }
2144         item = static_cast<ProjectItem *>(*it);
2145         if (item && item->referencedClip() != NULL) {
2146             if (item->hasProxy()) {
2147                 QString proxy = item->referencedClip()->getProperty("proxy");
2148                 list.insert(proxy, item->clipUrl().path());
2149             }
2150         }
2151         ++it;
2152     }
2153     return list;
2154 }
2155
2156 void ProjectList::slotCreateProxy(const QString id)
2157 {
2158     ProjectItem *item = getItemById(id);
2159     if (!item || item->isProxyRunning() || item->referencedClip()->isPlaceHolder()) return;
2160     QString path = item->referencedClip()->getProperty("proxy");
2161     if (path.isEmpty()) {
2162         setProxyStatus(path, PROXYCRASHED);
2163         return;
2164     }
2165     setProxyStatus(path, PROXYWAITING);
2166     if (m_abortProxy.contains(path)) m_abortProxy.removeAll(path);
2167     if (m_processingProxy.contains(path)) {
2168         // Proxy is already being generated
2169         return;
2170     }
2171     if (QFile::exists(path)) {
2172         // Proxy already created
2173         setProxyStatus(path, PROXYDONE);
2174         slotGotProxy(path);
2175         return;
2176     }
2177     m_processingProxy.append(path);
2178     QtConcurrent::run(this, &ProjectList::slotGenerateProxy, path, item->clipUrl().path(), item->clipType(), QString(item->referencedClip()->producerProperty("_exif_orientation")).toInt());
2179 }
2180
2181 void ProjectList::slotAbortProxy(const QString id, const QString path)
2182 {
2183     QTreeWidgetItemIterator it(m_listView);
2184     ProjectItem *item = getItemById(id);
2185     setProxyStatus(item, NOPROXY);
2186     slotGotProxy(item);
2187     if (!path.isEmpty() && m_processingProxy.contains(path)) {
2188         m_abortProxy << path;
2189         setProxyStatus(path, NOPROXY);
2190     }
2191 }
2192
2193 void ProjectList::slotGenerateProxy(const QString destPath, const QString sourcePath, int clipType, int exif_orientation)
2194 {
2195     emit projectModified();
2196     // Make sure proxy path is writable
2197     QFile file(destPath);
2198     if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
2199         setProxyStatus(destPath, PROXYCRASHED);
2200         return;
2201     }
2202     file.close();
2203     QFile::remove(destPath);
2204     
2205     setProxyStatus(destPath, CREATINGPROXY);
2206
2207     // Special case: playlist clips (.mlt or .kdenlive project files)
2208     if (clipType == PLAYLIST) {
2209         // change FFmpeg params to MLT format
2210         QStringList parameters;
2211         parameters << sourcePath;
2212         parameters << "-consumer" << "avformat:" + destPath;
2213         QStringList params = m_doc->getDocumentProperty("proxyparams").simplified().split('-', QString::SkipEmptyParts);
2214         
2215         foreach(QString s, params) {
2216             s = s.simplified();
2217             if (s.count(' ') == 0) {
2218                 s.append("=1");
2219             }
2220             else s.replace(' ', '=');
2221             parameters << s;
2222         }
2223         
2224         parameters.append(QString("real_time=-%1").arg(KdenliveSettings::mltthreads()));
2225
2226         //TODO: currently, when rendering an xml file through melt, the display ration is lost, so we enforce it manualy
2227         double display_ratio = KdenliveDoc::getDisplayRatio(sourcePath);
2228         parameters << "aspect=" + QString::number(display_ratio);
2229
2230         //kDebug()<<"TRANSCOD: "<<parameters;
2231         QProcess myProcess;
2232         myProcess.start(KdenliveSettings::rendererpath(), parameters);
2233         myProcess.waitForStarted();
2234         int result = -1;
2235         while (myProcess.state() != QProcess::NotRunning) {
2236             // building proxy file
2237             if (m_abortProxy.contains(destPath)) {
2238                 myProcess.close();
2239                 myProcess.waitForFinished();
2240                 m_abortProxy.removeAll(destPath);
2241                 m_processingProxy.removeAll(destPath);
2242                 QFile::remove(destPath);
2243                 setProxyStatus(destPath, NOPROXY);
2244                 result = -2;
2245
2246             }
2247             myProcess.waitForFinished(500);
2248         }
2249         myProcess.waitForFinished();
2250         m_processingProxy.removeAll(destPath);
2251         if (result == -1) result = myProcess.exitStatus();
2252         if (result == 0) {
2253             // proxy successfully created
2254             setProxyStatus(destPath, PROXYDONE);
2255             slotGotProxy(destPath);
2256         }
2257         else if (result == 1) {
2258             // Proxy process crashed
2259             QFile::remove(destPath);
2260             setProxyStatus(destPath, PROXYCRASHED);
2261         }   
2262
2263     }
2264     
2265     if (clipType == IMAGE) {
2266         // Image proxy
2267         QImage i(sourcePath);
2268         if (i.isNull()) {
2269             // Cannot load image
2270             setProxyStatus(destPath, PROXYCRASHED);
2271             return;
2272         }
2273         QImage proxy;
2274         // Images are scaled to profile size. 
2275         //TODO: Make it be configurable?
2276         if (i.width() > i.height()) proxy = i.scaledToWidth(m_render->frameRenderWidth());
2277         else proxy = i.scaledToHeight(m_render->renderHeight());
2278         if (exif_orientation > 1) {
2279             // Rotate image according to exif data
2280             QImage processed;
2281             QMatrix matrix;
2282
2283             switch ( exif_orientation ) {
2284                 case 2:
2285                   matrix.scale( -1, 1 );
2286                   break;
2287                 case 3:
2288                   matrix.rotate( 180 );
2289                   break;
2290                 case 4:
2291                   matrix.scale( 1, -1 );
2292                   break;
2293                 case 5:
2294                   matrix.rotate( 270 );
2295                   matrix.scale( -1, 1 );
2296                   break;
2297                 case 6:
2298                   matrix.rotate( 90 );
2299                   break;
2300                 case 7:
2301                   matrix.rotate( 90 );
2302                   matrix.scale( -1, 1 );
2303                   break;
2304                 case 8:
2305                   matrix.rotate( 270 );
2306                   break;
2307               }
2308               processed = proxy.transformed( matrix );
2309               processed.save(destPath);
2310         }
2311         else proxy.save(destPath);
2312         setProxyStatus(destPath, PROXYDONE);
2313         slotGotProxy(destPath);
2314         m_abortProxy.removeAll(destPath);
2315         m_processingProxy.removeAll(destPath);
2316         return;
2317     }
2318
2319     QStringList parameters;
2320     parameters << "-i" << sourcePath;
2321     QString params = m_doc->getDocumentProperty("proxyparams").simplified();
2322     foreach(QString s, params.split(' '))
2323     parameters << s;
2324
2325     // Make sure we don't block when proxy file already exists
2326     parameters << "-y";
2327     parameters << destPath;
2328     kDebug()<<"// STARTING PROXY GEN: "<<parameters;
2329     QProcess myProcess;
2330     myProcess.start("ffmpeg", parameters);
2331     myProcess.waitForStarted();
2332     int result = -1;
2333     while (myProcess.state() != QProcess::NotRunning) {
2334         // building proxy file
2335         if (m_abortProxy.contains(destPath)) {
2336             myProcess.close();
2337             myProcess.waitForFinished();
2338             m_abortProxy.removeAll(destPath);
2339             m_processingProxy.removeAll(destPath);
2340             QFile::remove(destPath);
2341             setProxyStatus(destPath, NOPROXY);
2342             result = -2;
2343             
2344         }
2345         myProcess.waitForFinished(500);
2346     }
2347     myProcess.waitForFinished();
2348     if (result == -1) result = myProcess.exitStatus();
2349     if (result == 0) {
2350         // proxy successfully created
2351         setProxyStatus(destPath, PROXYDONE);
2352         slotGotProxy(destPath);
2353     }
2354     else if (result == 1) {
2355         // Proxy process crashed
2356         QFile::remove(destPath);
2357         setProxyStatus(destPath, PROXYCRASHED);
2358     }
2359     m_abortProxy.removeAll(destPath);
2360     m_processingProxy.removeAll(destPath);
2361 }
2362
2363 void ProjectList::updateProxyConfig()
2364 {
2365     ProjectItem *item;
2366     QTreeWidgetItemIterator it(m_listView);
2367     QUndoCommand *command = new QUndoCommand();
2368     command->setText(i18n("Update proxy settings"));
2369     QString proxydir = m_doc->projectFolder().path( KUrl::AddTrailingSlash) + "proxy/";
2370     while (*it) {
2371         if ((*it)->type() != PROJECTCLIPTYPE) {
2372             ++it;
2373             continue;
2374         }
2375         item = static_cast<ProjectItem *>(*it);
2376         if (item == NULL) {
2377             ++it;
2378             continue;
2379         }
2380         CLIPTYPE t = item->clipType();
2381         if ((t == VIDEO || t == AV || t == UNKNOWN) && item->referencedClip() != NULL) {
2382             if  (generateProxy() && useProxy() && !item->isProxyRunning()) {
2383                 DocClipBase *clip = item->referencedClip();
2384                 if (clip->getProperty("frame_size").section('x', 0, 0).toInt() > m_doc->getDocumentProperty("proxyminsize").toInt()) {
2385                     if (clip->getProperty("proxy").isEmpty()) {
2386                         // We need to insert empty proxy in old properties so that undo will work
2387                         QMap <QString, QString> oldProps;// = clip->properties();
2388                         oldProps.insert("proxy", QString());
2389                         QMap <QString, QString> newProps;
2390                         newProps.insert("proxy", proxydir + item->referencedClip()->getClipHash() + "." + m_doc->getDocumentProperty("proxyextension"));
2391                         new EditClipCommand(this, clip->getId(), oldProps, newProps, true, command);
2392                     }
2393                 }
2394             }
2395             else if (item->hasProxy()) {
2396                 // remove proxy
2397                 QMap <QString, QString> newProps;
2398                 newProps.insert("proxy", QString());
2399                 newProps.insert("replace", "1");
2400                 // insert required duration for proxy
2401                 newProps.insert("proxy_out", item->referencedClip()->producerProperty("out"));
2402                 new EditClipCommand(this, item->clipId(), item->referencedClip()->properties(), newProps, true, command);
2403             }
2404         }
2405         else if (t == IMAGE && item->referencedClip() != NULL) {
2406             if  (generateImageProxy() && useProxy()) {
2407                 DocClipBase *clip = item->referencedClip();
2408                 int maxImageSize = m_doc->getDocumentProperty("proxyimageminsize").toInt();
2409                 if (clip->getProperty("frame_size").section('x', 0, 0).toInt() > maxImageSize || clip->getProperty("frame_size").section('x', 1, 1).toInt() > maxImageSize) {
2410                     if (clip->getProperty("proxy").isEmpty()) {
2411                         // We need to insert empty proxy in old properties so that undo will work
2412                         QMap <QString, QString> oldProps = clip->properties();
2413                         oldProps.insert("proxy", QString());
2414                         QMap <QString, QString> newProps;
2415                         newProps.insert("proxy", proxydir + item->referencedClip()->getClipHash() + ".png");
2416                         new EditClipCommand(this, clip->getId(), oldProps, newProps, true, command);
2417                     }
2418                 }
2419             }
2420             else if (item->hasProxy()) {
2421                 // remove proxy
2422                 QMap <QString, QString> newProps;
2423                 newProps.insert("proxy", QString());
2424                 newProps.insert("replace", "1");
2425                 new EditClipCommand(this, item->clipId(), item->referencedClip()->properties(), newProps, true, command);
2426             }
2427         }
2428         ++it;
2429     }
2430     if (command->childCount() > 0) m_doc->commandStack()->push(command);
2431     else delete command;
2432     if (!m_infoQueue.isEmpty() && !m_queueRunner.isRunning() && m_processingClips.isEmpty()) m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
2433 }
2434
2435 void ProjectList::slotProxyCurrentItem(bool doProxy)
2436 {
2437     QList<QTreeWidgetItem *> list = m_listView->selectedItems();
2438     QTreeWidgetItem *listItem;
2439     QUndoCommand *command = new QUndoCommand();
2440     if (doProxy) command->setText(i18np("Add proxy clip", "Add proxy clips", list.count()));
2441     else command->setText(i18np("Remove proxy clip", "Remove proxy clips", list.count()));
2442     
2443     // Make sure the proxy folder exists
2444     QString proxydir = m_doc->projectFolder().path( KUrl::AddTrailingSlash) + "proxy/";
2445     KStandardDirs::makeDir(proxydir);
2446                 
2447     QMap <QString, QString> newProps;
2448     QMap <QString, QString> oldProps;
2449     if (!doProxy) newProps.insert("proxy", "-");
2450     for (int i = 0; i < list.count(); i++) {
2451         listItem = list.at(i);
2452         if (listItem->type() == PROJECTFOLDERTYPE) {
2453             for (int j = 0; j < listItem->childCount(); j++) {
2454                 QTreeWidgetItem *sub = listItem->child(j);
2455                 if (!list.contains(sub)) list.append(sub);
2456             }
2457         }
2458         if (listItem->type() == PROJECTCLIPTYPE) {
2459             ProjectItem *item = static_cast <ProjectItem*>(listItem);
2460             CLIPTYPE t = item->clipType();
2461             if ((t == VIDEO || t == AV || t == UNKNOWN || t == IMAGE || t == PLAYLIST) && item->referencedClip()) {
2462                 oldProps = item->referencedClip()->properties();
2463                 if (doProxy) {
2464                     newProps.clear();
2465                     QString path = proxydir + item->referencedClip()->getClipHash() + "." + (t == IMAGE ? "png" : m_doc->getDocumentProperty("proxyextension"));
2466                     // insert required duration for proxy
2467                     newProps.insert("proxy_out", item->referencedClip()->producerProperty("out"));
2468                     newProps.insert("proxy", path);
2469                     // We need to insert empty proxy so that undo will work
2470                     oldProps.insert("proxy", QString());
2471                 }
2472                 new EditClipCommand(this, item->clipId(), oldProps, newProps, true, command);
2473             }
2474         }
2475     }
2476     if (command->childCount() > 0) {
2477         m_doc->commandStack()->push(command);
2478     }
2479     else delete command;
2480     //if (!m_infoQueue.isEmpty() && !m_queueRunner.isRunning() && m_processingClips.isEmpty()) m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
2481 }
2482
2483
2484 void ProjectList::slotDeleteProxy(const QString proxyPath)
2485 {
2486     if (proxyPath.isEmpty()) return;
2487     QUndoCommand *proxyCommand = new QUndoCommand();
2488     proxyCommand->setText(i18n("Remove Proxy"));
2489     QTreeWidgetItemIterator it(m_listView);
2490     ProjectItem *item;
2491     while (*it) {
2492         if ((*it)->type() == PROJECTCLIPTYPE) {
2493             item = static_cast <ProjectItem *>(*it);
2494             if (item->referencedClip()->getProperty("proxy") == proxyPath) {
2495                 QMap <QString, QString> props;
2496                 props.insert("proxy", QString());
2497                 new EditClipCommand(this, item->clipId(), item->referencedClip()->properties(), props, true, proxyCommand);
2498             
2499             }
2500         }
2501         ++it;
2502     }
2503     if (proxyCommand->childCount() == 0)
2504         delete proxyCommand;
2505     else
2506         m_commandStack->push(proxyCommand);
2507     QFile::remove(proxyPath);
2508 }
2509
2510 void ProjectList::setProxyStatus(const QString proxyPath, PROXYSTATUS status)
2511 {
2512     if (proxyPath.isEmpty()) return;
2513     QTreeWidgetItemIterator it(m_listView);
2514     ProjectItem *item;
2515     while (*it) {
2516         if ((*it)->type() == PROJECTCLIPTYPE) {
2517             item = static_cast <ProjectItem *>(*it);
2518             if (item->referencedClip()->getProperty("proxy") == proxyPath) {
2519                 setProxyStatus(item, status);
2520             }
2521         }
2522         ++it;
2523     }
2524 }
2525
2526 void ProjectList::setProxyStatus(ProjectItem *item, PROXYSTATUS status)
2527 {
2528     if (item == NULL) return;
2529     monitorItemEditing(false);
2530     item->setProxyStatus(status);
2531     monitorItemEditing(true);
2532 }
2533
2534 void ProjectList::monitorItemEditing(bool enable)
2535 {
2536     if (enable) connect(m_listView, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this, SLOT(slotItemEdited(QTreeWidgetItem *, int)));     
2537     else disconnect(m_listView, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this, SLOT(slotItemEdited(QTreeWidgetItem *, int)));     
2538 }
2539
2540 QStringList ProjectList::expandedFolders() const
2541 {
2542     QStringList result;
2543     FolderProjectItem *item;
2544     QTreeWidgetItemIterator it(m_listView);
2545     while (*it) {
2546         if ((*it)->type() != PROJECTFOLDERTYPE) {
2547             ++it;
2548             continue;
2549         }
2550         if ((*it)->isExpanded()) {
2551             item = static_cast<FolderProjectItem *>(*it);
2552             result.append(item->clipId());
2553         }
2554         ++it;
2555     }
2556     return result;
2557 }
2558
2559 #include "projectlist.moc"