]> git.sesse.net Git - kdenlive/blob - src/projectlist.cpp
nepomuk: fix warning
[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 "commands/addfoldercommand.h"
23 #include "projecttree/proxyclipjob.h"
24 #include "projecttree/cutclipjob.h"
25 #include "projecttree/meltjob.h"
26 #include "kdenlivesettings.h"
27 #include "slideshowclip.h"
28 #include "ui_colorclip_ui.h"
29 #include "widgets/titlewidget.h"
30 #include "definitions.h"
31 #include "clipmanager.h"
32 #include "docclipbase.h"
33 #include "kdenlivedoc.h"
34 #include "renderer.h"
35 #include "kthumb.h"
36 #include "projectlistview.h"
37 #include "timecodedisplay.h"
38 #include "profilesdialog.h"
39 #include "clipstabilize.h"
40 #include "commands/editclipcommand.h"
41 #include "commands/editclipcutcommand.h"
42 #include "commands/editfoldercommand.h"
43 #include "commands/addclipcutcommand.h"
44
45 #include "ui_templateclip_ui.h"
46 #include "ui_cutjobdialog_ui.h"
47 #include "ui_scenecutdialog_ui.h"
48
49 #include <KDebug>
50 #include <KAction>
51 #include <KLocalizedString>
52 #include <KFileDialog>
53 #include <KInputDialog>
54 #include <KMessageBox>
55 #include <KIO/NetAccess>
56 #include <KFileItem>
57 #include <KApplication>
58 #include <KStandardDirs>
59 #include <KColorScheme>
60 #include <KActionCollection>
61 #include <KUrlRequester>
62 #include <KVBox>
63 #include <KHBox>
64
65 #ifdef USE_NEPOMUK
66   #include <nepomuk/global.h>
67   #include <nepomuk/resourcemanager.h>
68   #include <Nepomuk/Resource>
69   //#include <nepomuk/tag.h>
70 #endif
71
72 #ifdef USE_NEPOMUKCORE
73   #include <nepomuk2/resourcemanager.h>
74   #include <Nepomuk2/Resource>
75 #endif
76
77 #include <QMouseEvent>
78 #include <QStylePainter>
79 #include <QPixmap>
80 #include <QIcon>
81 #include <QMenu>
82 #include <QProcess>
83 #include <QScrollBar>
84 #include <QHeaderView>
85 #include <QInputDialog>
86 #include <QtConcurrentRun>
87 #include <QVBoxLayout>
88 #include <KPassivePopup>
89
90
91 MyMessageWidget::MyMessageWidget(QWidget *parent) : KMessageWidget(parent) {}
92 MyMessageWidget::MyMessageWidget(const QString &text, QWidget *parent) : KMessageWidget(text, parent) {}
93
94
95 bool MyMessageWidget::event(QEvent* ev) {
96     if (ev->type() == QEvent::Hide || ev->type() == QEvent::Close) emit messageClosing();
97     return KMessageWidget::event(ev);
98 }
99
100 SmallInfoLabel::SmallInfoLabel(QWidget *parent) : QPushButton(parent)
101 {
102     setFixedWidth(0);
103     setFlat(true);
104     
105     /*QString style = "QToolButton {background-color: %1;border-style: outset;border-width: 2px;
106      border-radius: 5px;border-color: beige;}";*/
107     m_timeLine = new QTimeLine(500, this);
108     QObject::connect(m_timeLine, SIGNAL(valueChanged(qreal)), this, SLOT(slotTimeLineChanged(qreal)));
109     QObject::connect(m_timeLine, SIGNAL(finished()), this, SLOT(slotTimeLineFinished()));
110     hide();
111 }
112
113 const QString SmallInfoLabel::getStyleSheet(const QPalette &p)
114 {
115     KColorScheme scheme(p.currentColorGroup(), KColorScheme::Window, KSharedConfig::openConfig(KdenliveSettings::colortheme()));
116     QColor bg = scheme.background(KColorScheme::LinkBackground).color();
117     QColor fg = scheme.foreground(KColorScheme::LinkText).color();
118     QString style = QString("QPushButton {padding:2px;background-color: rgb(%1, %2, %3);border-radius: 4px;border: none;color: rgb(%4, %5, %6)}").arg(bg.red()).arg(bg.green()).arg(bg.blue()).arg(fg.red()).arg(fg.green()).arg(fg.blue());
119     
120     bg = scheme.background(KColorScheme::ActiveBackground).color();
121     fg = scheme.foreground(KColorScheme::ActiveText).color();
122     style.append(QString("\nQPushButton:hover {padding:2px;background-color: rgb(%1, %2, %3);border-radius: 4px;border: none;color: rgb(%4, %5, %6)}").arg(bg.red()).arg(bg.green()).arg(bg.blue()).arg(fg.red()).arg(fg.green()).arg(fg.blue()));
123     
124     return style;
125 }
126
127 void SmallInfoLabel::slotTimeLineChanged(qreal value)
128 {
129     setFixedWidth(qMin(value * 2, qreal(1.0)) * sizeHint().width());
130     update();
131 }
132
133 void SmallInfoLabel::slotTimeLineFinished()
134 {
135     if (m_timeLine->direction() == QTimeLine::Forward) {
136         // Show
137         show();
138     } else {
139         // Hide
140         hide();
141         setText(QString());
142     }
143 }
144
145 void SmallInfoLabel::slotSetJobCount(int jobCount)
146 {
147     if (jobCount > 0) {
148         // prepare animation
149         setText(i18np("%1 job", "%1 jobs", jobCount));
150         setToolTip(i18np("%1 pending job", "%1 pending jobs", jobCount));
151         
152         if (!(KGlobalSettings::graphicEffectsLevel() & KGlobalSettings::SimpleAnimationEffects)) {
153             setFixedWidth(sizeHint().width());
154             show();
155             return;
156         }
157         
158         if (isVisible()) {
159             setFixedWidth(sizeHint().width());
160             update();
161             return;
162         }
163         
164         setFixedWidth(0);
165         show();
166         int wantedWidth = sizeHint().width();
167         setGeometry(-wantedWidth, 0, wantedWidth, height());
168         m_timeLine->setDirection(QTimeLine::Forward);
169         if (m_timeLine->state() == QTimeLine::NotRunning) {
170             m_timeLine->start();
171         }
172     }
173     else {
174         if (!(KGlobalSettings::graphicEffectsLevel() & KGlobalSettings::SimpleAnimationEffects)) {
175             setFixedWidth(0);
176             hide();
177             return;
178         }
179         // hide
180         m_timeLine->setDirection(QTimeLine::Backward);
181         if (m_timeLine->state() == QTimeLine::NotRunning) {
182             m_timeLine->start();
183         }
184     }
185     
186 }
187
188 ProjectList::ProjectList(QWidget *parent) :
189     QWidget(parent)
190   , m_render(NULL)
191   , m_fps(-1)
192   , m_menu(NULL)
193   , m_commandStack(NULL)
194   , m_openAction(NULL)
195   , m_reloadAction(NULL)
196   , m_extractAudioAction(NULL)
197   , m_transcodeAction(NULL)
198   , m_clipsActionsMenu(NULL)
199   , m_doc(NULL)
200   , m_refreshed(false)
201   , m_allClipsProcessed(false)
202   , m_thumbnailQueue()
203   , m_proxyAction(NULL)
204   , m_abortAllJobs(false)
205   , m_closing(false)
206   , m_invalidClipDialog(NULL)
207 {
208     qRegisterMetaType<stringMap> ("stringMap");
209     QVBoxLayout *layout = new QVBoxLayout;
210     layout->setContentsMargins(0, 0, 0, 0);
211     layout->setSpacing(0);
212     qRegisterMetaType<QDomElement>("QDomElement");
213     // setup toolbar
214     QFrame *frame = new QFrame;
215     frame->setFrameStyle(QFrame::NoFrame);
216     QHBoxLayout *box = new QHBoxLayout;
217     box->setContentsMargins(0, 0, 0, 0);
218     
219     KTreeWidgetSearchLine *searchView = new KTreeWidgetSearchLine;
220     box->addWidget(searchView);
221     
222     // small info button for pending jobs
223     m_infoLabel = new SmallInfoLabel(this);
224     m_infoLabel->setStyleSheet(SmallInfoLabel::getStyleSheet(palette()));
225     connect(this, SIGNAL(jobCount(int)), m_infoLabel, SLOT(slotSetJobCount(int)));
226     m_jobsMenu = new QMenu(this);
227     connect(m_jobsMenu, SIGNAL(aboutToShow()), this, SLOT(slotPrepareJobsMenu()));
228     QAction *cancelJobs = new QAction(i18n("Cancel All Jobs"), this);
229     cancelJobs->setCheckable(false);
230     connect(cancelJobs, SIGNAL(triggered()), this, SLOT(slotCancelJobs()));
231     connect(this, SIGNAL(checkJobProcess()), this, SLOT(slotCheckJobProcess()));
232     m_discardCurrentClipJobs = new QAction(i18n("Cancel Current Clip Jobs"), this);
233     m_discardCurrentClipJobs->setCheckable(false);
234     connect(m_discardCurrentClipJobs, SIGNAL(triggered()), this, SLOT(slotDiscardClipJobs()));
235     m_jobsMenu->addAction(cancelJobs);
236     m_jobsMenu->addAction(m_discardCurrentClipJobs);
237     m_infoLabel->setMenu(m_jobsMenu);
238     box->addWidget(m_infoLabel);
239
240     int size = style()->pixelMetric(QStyle::PM_SmallIconSize);
241     QSize iconSize(size, size);
242
243     m_addButton = new QToolButton;
244     m_addButton->setPopupMode(QToolButton::MenuButtonPopup);
245     m_addButton->setAutoRaise(true);
246     m_addButton->setIconSize(iconSize);
247     box->addWidget(m_addButton);
248
249     m_editButton = new QToolButton;
250     m_editButton->setAutoRaise(true);
251     m_editButton->setIconSize(iconSize);
252     box->addWidget(m_editButton);
253
254     m_deleteButton = new QToolButton;
255     m_deleteButton->setAutoRaise(true);
256     m_deleteButton->setIconSize(iconSize);
257     box->addWidget(m_deleteButton);
258     frame->setLayout(box);
259     layout->addWidget(frame);
260
261     m_listView = new ProjectListView(this);
262     layout->addWidget(m_listView);
263     
264 #if KDE_IS_VERSION(4,7,0)
265     m_infoMessage = new MyMessageWidget;
266     layout->addWidget(m_infoMessage);
267     m_infoMessage->setCloseButtonVisible(true);
268     connect(m_infoMessage, SIGNAL(messageClosing()), this, SLOT(slotResetInfoMessage()));
269     //m_infoMessage->setWordWrap(true);
270     m_infoMessage->hide();
271     m_logAction = new QAction(i18n("Show Log"), this);
272     m_logAction->setCheckable(false);
273     connect(m_logAction, SIGNAL(triggered()), this, SLOT(slotShowJobLog()));
274 #endif
275
276     setLayout(layout);
277     searchView->setTreeWidget(m_listView);
278
279     connect(this, SIGNAL(processNextThumbnail()), this, SLOT(slotProcessNextThumbnail()));
280     connect(m_listView, SIGNAL(projectModified()), this, SIGNAL(projectModified()));
281     connect(m_listView, SIGNAL(itemSelectionChanged()), this, SLOT(slotClipSelected()));
282     connect(m_listView, SIGNAL(focusMonitor(bool)), this, SIGNAL(raiseClipMonitor(bool)));
283     connect(m_listView, SIGNAL(pauseMonitor()), this, SIGNAL(pauseMonitor()));
284     connect(m_listView, SIGNAL(requestMenu(QPoint,QTreeWidgetItem*)), this, SLOT(slotContextMenu(QPoint,QTreeWidgetItem*)));
285     connect(m_listView, SIGNAL(addClip()), this, SIGNAL(pauseMonitor()));
286     connect(m_listView, SIGNAL(addClip()), this, SLOT(slotAddClip()));
287     connect(m_listView, SIGNAL(addClip(QList<QUrl>,QString,QString)), this, SLOT(slotAddClip(QList<QUrl>,QString,QString)));
288     connect(this, SIGNAL(addClip(QString,QString,QString)), this, SLOT(slotAddClip(QString,QString,QString)));
289     connect(m_listView, SIGNAL(addClipCut(QString,int,int)), this, SLOT(slotAddClipCut(QString,int,int)));
290     connect(m_listView, SIGNAL(itemChanged(QTreeWidgetItem*,int)), this, SLOT(slotItemEdited(QTreeWidgetItem*,int)));
291     connect(m_listView, SIGNAL(showProperties(DocClipBase*)), this, SIGNAL(showClipProperties(DocClipBase*)));
292     
293     connect(this, SIGNAL(cancelRunningJob(QString,stringMap)), this, SLOT(slotCancelRunningJob(QString,stringMap)));
294     connect(this, SIGNAL(processLog(QString,int,int,QString)), this, SLOT(slotProcessLog(QString,int,int,QString)));
295     
296     connect(this, SIGNAL(updateJobStatus(QString,int,int,QString,QString,QString)), this, SLOT(slotUpdateJobStatus(QString,int,int,QString,QString,QString)));
297     
298     connect(this, SIGNAL(gotProxy(QString)), this, SLOT(slotGotProxyForId(QString)));
299     
300     m_listViewDelegate = new ItemDelegate(m_listView);
301     m_listView->setItemDelegate(m_listViewDelegate);
302 #ifdef USE_NEPOMUK
303     if (KdenliveSettings::activate_nepomuk()) {
304         Nepomuk::ResourceManager::instance()->init();
305         if (!Nepomuk::ResourceManager::instance()->initialized()) {
306             kDebug() << "Cannot communicate with Nepomuk, DISABLING it";
307             KdenliveSettings::setActivate_nepomuk(false);
308         }
309     }
310 #endif
311 #ifdef USE_NEPOMUKCORE
312     if (KdenliveSettings::activate_nepomuk()) {
313         Nepomuk2::ResourceManager::instance()->init();
314         if (!Nepomuk2::ResourceManager::instance()->initialized()) {
315             kDebug() << "Cannot communicate with Nepomuk, DISABLING it";
316             KdenliveSettings::setActivate_nepomuk(false);
317         }
318     }
319 #endif
320
321 }
322
323 ProjectList::~ProjectList()
324 {
325     m_abortAllJobs = true;
326     for (int i = 0; i < m_jobList.count(); ++i) {
327         m_jobList.at(i)->setStatus(JobAborted);
328     }
329     m_closing = true;
330     m_thumbnailQueue.clear();
331     m_jobThreads.waitForFinished();
332     m_jobThreads.clearFutures();
333     if (!m_jobList.isEmpty()) qDeleteAll(m_jobList);
334     m_jobList.clear();
335     if (m_menu) delete m_menu;
336     m_listView->blockSignals(true);
337     m_listView->clear();
338     delete m_listViewDelegate;
339 #if KDE_IS_VERSION(4,7,0)
340     delete m_infoMessage;
341 #endif
342 }
343
344 void ProjectList::focusTree() const
345 {
346     m_listView->setFocus();
347 }
348
349 void ProjectList::setupMenu(QMenu *addMenu, QAction *defaultAction)
350 {
351     QList <QAction *> actions = addMenu->actions();
352     for (int i = 0; i < actions.count(); ++i) {
353         if (actions.at(i)->data().toString() == "clip_properties") {
354             m_editButton->setDefaultAction(actions.at(i));
355             actions.removeAt(i);
356             --i;
357         } else if (actions.at(i)->data().toString() == "delete_clip") {
358             m_deleteButton->setDefaultAction(actions.at(i));
359             actions.removeAt(i);
360             --i;
361         } else if (actions.at(i)->data().toString() == "edit_clip") {
362             m_openAction = actions.at(i);
363             actions.removeAt(i);
364             --i;
365         } else if (actions.at(i)->data().toString() == "reload_clip") {
366             m_reloadAction = actions.at(i);
367             actions.removeAt(i);
368             --i;
369         } else if (actions.at(i)->data().toString() == "proxy_clip") {
370             m_proxyAction = actions.at(i);
371             actions.removeAt(i);
372             --i;
373         }
374     }
375
376     QMenu *m = new QMenu();
377     m->addActions(actions);
378     m_addButton->setMenu(m);
379     m_addButton->setDefaultAction(defaultAction);
380     m_menu = new QMenu();
381     m_menu->addActions(addMenu->actions());
382 }
383
384 void ProjectList::setupGeneratorMenu(const QHash<QString,QMenu*>& menus)
385 {
386     if (!m_menu) {
387         kDebug()<<"Warning, menu was not created, something is wrong";
388         return;
389     }
390     if (!menus.contains("addMenu") && ! menus.value("addMenu") )
391         return;
392     QMenu *menu = m_addButton->menu();
393     if (menus.contains("addMenu") && menus.value("addMenu")){
394         QMenu* addMenu=menus.value("addMenu");
395         menu->addMenu(addMenu);
396         m_addButton->setMenu(menu);
397         if (addMenu->isEmpty())
398             addMenu->setEnabled(false);
399     }
400     if (menus.contains("extractAudioMenu") && menus.value("extractAudioMenu") ){
401         QMenu* extractAudioMenu = menus.value("extractAudioMenu");
402         m_menu->addMenu(extractAudioMenu);
403         m_extractAudioAction = extractAudioMenu;
404     }
405     if (menus.contains("transcodeMenu") && menus.value("transcodeMenu") ){
406         QMenu* transcodeMenu = menus.value("transcodeMenu");
407         m_menu->addMenu(transcodeMenu);
408         if (transcodeMenu->isEmpty())
409             transcodeMenu->setEnabled(false);
410         m_transcodeAction = transcodeMenu;
411     }
412     if (menus.contains("clipActionsMenu") && menus.value("clipActionsMenu") ){
413         QMenu* stabilizeMenu=menus.value("clipActionsMenu");
414         m_menu->addMenu(stabilizeMenu);
415         if (stabilizeMenu->isEmpty())
416             stabilizeMenu->setEnabled(false);
417         m_clipsActionsMenu = stabilizeMenu;
418
419     }
420     if (m_reloadAction) m_menu->addAction(m_reloadAction);
421     if (m_proxyAction) m_menu->addAction(m_proxyAction);
422     if (menus.contains("inTimelineMenu") && menus.value("inTimelineMenu")){
423         QMenu* inTimelineMenu=menus.value("inTimelineMenu");
424         m_menu->addMenu(inTimelineMenu);
425         inTimelineMenu->setEnabled(false);
426     }
427     m_menu->addAction(m_editButton->defaultAction());
428     m_menu->addAction(m_openAction);
429     m_menu->addAction(m_deleteButton->defaultAction());
430     m_menu->insertSeparator(m_deleteButton->defaultAction());
431 }
432
433 void ProjectList::clearSelection()
434 {
435     m_listView->clearSelection();
436 }
437
438 QByteArray ProjectList::headerInfo() const
439 {
440     return m_listView->header()->saveState();
441 }
442
443 void ProjectList::setHeaderInfo(const QByteArray &state)
444 {
445     m_listView->header()->restoreState(state);
446 }
447
448 void ProjectList::updateProjectFormat(Timecode t)
449 {
450     m_timecode = t;
451 }
452
453 void ProjectList::slotEditClip()
454 {
455     QList<QTreeWidgetItem *> list = m_listView->selectedItems();
456     if (list.isEmpty()) return;
457     if (list.count() > 1 || list.at(0)->type() == ProjectFoldeType) {
458         editClipSelection(list);
459         return;
460     }
461     ProjectItem *item;
462     if (!m_listView->currentItem() || m_listView->currentItem()->type() == ProjectFoldeType)
463         return;
464     if (m_listView->currentItem()->type() == ProjectSubclipType)
465         item = static_cast <ProjectItem*>(m_listView->currentItem()->parent());
466     else
467         item = static_cast <ProjectItem*>(m_listView->currentItem());
468     if (item && (item->flags() & Qt::ItemIsDragEnabled)) {
469         emit clipSelected(item->referencedClip());
470         emit showClipProperties(item->referencedClip());
471     }
472 }
473
474 void ProjectList::editClipSelection(QList<QTreeWidgetItem *> list)
475 {
476     // Gather all common properties
477     QMap <QString, QString> commonproperties;
478     QList <DocClipBase *> clipList;
479     commonproperties.insert("force_aspect_num", "-");
480     commonproperties.insert("force_aspect_den", "-");
481     commonproperties.insert("force_fps", "-");
482     commonproperties.insert("force_progressive", "-");
483     commonproperties.insert("force_tff", "-");
484     commonproperties.insert("threads", "-");
485     commonproperties.insert("video_index", "-");
486     commonproperties.insert("audio_index", "-");
487     commonproperties.insert("force_colorspace", "-");
488     commonproperties.insert("full_luma", "-");
489     QString transparency = "-";
490
491     bool allowDurationChange = true;
492     int commonDuration = -1;
493     bool hasImages = false;;
494     ProjectItem *item;
495     for (int i = 0; i < list.count(); ++i) {
496         item = NULL;
497         if (list.at(i)->type() == ProjectFoldeType) {
498             // Add folder items to the list
499             int ct = list.at(i)->childCount();
500             for (int j = 0; j < ct; j++) {
501                 list.append(list.at(i)->child(j));
502             }
503             continue;
504         }
505         else if (list.at(i)->type() == ProjectSubclipType)
506             item = static_cast <ProjectItem*>(list.at(i)->parent());
507         else
508             item = static_cast <ProjectItem*>(list.at(i));
509         if (!(item->flags() & Qt::ItemIsDragEnabled))
510             continue;
511         if (item) {
512             // check properties
513             DocClipBase *clip = item->referencedClip();
514             if (clipList.contains(clip)) continue;
515             if (clip->clipType() == Image) {
516                 hasImages = true;
517                 if (clip->getProperty("transparency").isEmpty() || clip->getProperty("transparency").toInt() == 0) {
518                     if (transparency == "-") {
519                         // first non transparent image
520                         transparency = '0';
521                     }
522                     else if (transparency == "1") {
523                         // we have transparent and non transparent clips
524                         transparency = "-1";
525                     }
526                 }
527                 else {
528                     if (transparency == "-") {
529                         // first transparent image
530                         transparency = '1';
531                     }
532                     else if (transparency == "0") {
533                         // we have transparent and non transparent clips
534                         transparency = "-1";
535                     }
536                 }
537             }
538             if (clip->clipType() != Color && clip->clipType() != Image && clip->clipType() != Text)
539                 allowDurationChange = false;
540             if (allowDurationChange && commonDuration != 0) {
541                 if (commonDuration == -1)
542                     commonDuration = clip->duration().frames(m_fps);
543                 else if (commonDuration != clip->duration().frames(m_fps))
544                     commonDuration = 0;
545             }
546             clipList.append(clip);
547             QMap <QString, QString> clipprops = clip->properties();
548             QMapIterator<QString, QString> p(commonproperties);
549             while (p.hasNext()) {
550                 p.next();
551                 if (p.value().isEmpty()) continue;
552                 if (clipprops.contains(p.key())) {
553                     if (p.value() == "-")
554                         commonproperties.insert(p.key(), clipprops.value(p.key()));
555                     else if (p.value() != clipprops.value(p.key()))
556                         commonproperties.insert(p.key(), QString());
557                 } else {
558                     commonproperties.insert(p.key(), QString());
559                 }
560             }
561         }
562     }
563     if (allowDurationChange)
564         commonproperties.insert("out", QString::number(commonDuration));
565     if (hasImages)
566         commonproperties.insert("transparency", transparency);
567     /*QMapIterator<QString, QString> p(commonproperties);
568     while (p.hasNext()) {
569         p.next();
570         kDebug() << "Result: " << p.key() << " = " << p.value();
571     }*/
572     if (clipList.isEmpty()) {
573         emit displayMessage(i18n("No available clip selected"), -2, ErrorMessage);
574     }
575     else emit showClipProperties(clipList, commonproperties);
576 }
577
578 void ProjectList::slotOpenClip()
579 {
580     ProjectItem *item;
581     if (!m_listView->currentItem() || m_listView->currentItem()->type() == ProjectFoldeType)
582         return;
583     if (m_listView->currentItem()->type() == QTreeWidgetItem::UserType + 1)
584         item = static_cast <ProjectItem*>(m_listView->currentItem()->parent());
585     else
586         item = static_cast <ProjectItem*>(m_listView->currentItem());
587     if (item) {
588         if (item->clipType() == Image) {
589             if (KdenliveSettings::defaultimageapp().isEmpty())
590                 KMessageBox::sorry(kapp->activeWindow(), i18n("Please set a default application to open images in the Settings dialog"));
591             else
592                 QProcess::startDetached(KdenliveSettings::defaultimageapp(), QStringList() << item->clipUrl().path());
593         }
594         if (item->clipType() == Audio) {
595             if (KdenliveSettings::defaultaudioapp().isEmpty())
596                 KMessageBox::sorry(kapp->activeWindow(), i18n("Please set a default application to open audio files in the Settings dialog"));
597             else
598                 QProcess::startDetached(KdenliveSettings::defaultaudioapp(), QStringList() << item->clipUrl().path());
599         }
600     }
601 }
602
603 void ProjectList::cleanup()
604 {
605     m_listView->clearSelection();
606     QTreeWidgetItemIterator it(m_listView);
607     ProjectItem *item;
608     while (*it) {
609         if ((*it)->type() != ProjectClipType) {
610             it++;
611             continue;
612         }
613         item = static_cast <ProjectItem *>(*it);
614         if (item->numReferences() == 0)
615             item->setSelected(true);
616         it++;
617     }
618     slotRemoveClip();
619 }
620
621 void ProjectList::trashUnusedClips()
622 {
623     QTreeWidgetItemIterator it(m_listView);
624     ProjectItem *item;
625     QStringList ids;
626     QStringList urls;
627     while (*it) {
628         if ((*it)->type() != ProjectClipType) {
629             it++;
630             continue;
631         }
632         item = static_cast <ProjectItem *>(*it);
633         if (item->numReferences() == 0) {
634             ids << item->clipId();
635             KUrl url = item->clipUrl();
636             if (!url.isEmpty() && !urls.contains(url.path()))
637                 urls << url.path();
638         }
639         it++;
640     }
641
642     // Check that we don't use the URL in another clip
643     QTreeWidgetItemIterator it2(m_listView);
644     while (*it2) {
645         if ((*it2)->type() != ProjectClipType) {
646             it2++;
647             continue;
648         }
649         item = static_cast <ProjectItem *>(*it2);
650         if (item->numReferences() > 0) {
651             KUrl url = item->clipUrl();
652             if (!url.isEmpty() && urls.contains(url.path())) urls.removeAll(url.path());
653         }
654         it2++;
655     }
656
657     emit deleteProjectClips(ids, QMap <QString, QString>());
658     for (int i = 0; i < urls.count(); ++i)
659         KIO::NetAccess::del(KUrl(urls.at(i)), this);
660 }
661
662 void ProjectList::slotReloadClip(const QString &id)
663 {
664     QList<QTreeWidgetItem *> selected;
665     if (id.isEmpty())
666         selected = m_listView->selectedItems();
667     else {
668         ProjectItem *itemToReLoad = getItemById(id);
669         if (itemToReLoad) selected.append(itemToReLoad);
670     }
671     ProjectItem *item;
672     for (int i = 0; i < selected.count(); ++i) {
673         if (selected.at(i)->type() != ProjectClipType) {
674             if (selected.at(i)->type() == ProjectFoldeType) {
675                 for (int j = 0; j < selected.at(i)->childCount(); j++)
676                     selected.append(selected.at(i)->child(j));
677             }
678             continue;
679         }
680         item = static_cast <ProjectItem *>(selected.at(i));
681         if (item && !hasPendingJob(item, PROXYJOB)) {
682             DocClipBase *clip = item->referencedClip();
683             if (!clip || !clip->isClean() || m_render->isProcessing(item->clipId())) {
684                 kDebug()<<"//// TRYING TO RELOAD: "<<item->clipId()<<", but it is busy";
685                 continue;
686             }
687             ClipType t = item->clipType();
688             if (t == Text) {
689                 if (clip && !clip->getProperty("xmltemplate").isEmpty())
690                     regenerateTemplate(item);
691             } else if (t != Color && t != SlideShow && clip && clip->checkHash() == false) {
692                 item->referencedClip()->setPlaceHolder(true);
693                 item->setProperty("file_hash", QString());
694             } else if (t == Image) {
695                 //clip->getProducer() clip->getProducer()->set("force_reload", 1);
696             }
697
698             QDomElement e = item->toXml();
699             // Make sure we get the correct producer length if it was adjusted in timeline
700             if (t == Color || t == Image || t == SlideShow || t == Text) {
701                 int length = QString(clip->producerProperty("length")).toInt();
702                 if (length > 0 && !e.hasAttribute("length")) {
703                     e.setAttribute("length", length);
704                 }
705                 e.setAttribute("duration", clip->getProperty("duration"));
706             }
707             resetThumbsProducer(clip);
708             m_render->getFileProperties(e, item->clipId(), m_listView->iconSize().height(), true);
709         }
710     }
711 }
712
713 void ProjectList::slotModifiedClip(const QString &id)
714 {
715     ProjectItem *item = getItemById(id);
716     if (item) {
717         QPixmap pixmap = qVariantValue<QPixmap>(item->data(0, Qt::DecorationRole));
718         if (!pixmap.isNull()) {
719             QPainter p(&pixmap);
720             p.fillRect(0, 0, pixmap.width(), pixmap.height(), QColor(255, 255, 255, 200));
721             p.drawPixmap(0, 0, KIcon("view-refresh").pixmap(m_listView->iconSize()));
722             p.end();
723         } else {
724             pixmap = KIcon("view-refresh").pixmap(m_listView->iconSize());
725         }
726         item->setPixmap(pixmap);
727     }
728 }
729
730 void ProjectList::slotMissingClip(const QString &id)
731 {
732     ProjectItem *item = getItemById(id);
733     if (item) {
734         item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsDropEnabled);
735         int height = m_listView->iconSize().height();
736         if (m_render == NULL) {
737             kDebug() << "*********  ERROR, NULL RENDR";
738             return;
739         }
740         int width = (int)(height  * m_render->dar());
741         QPixmap pixmap = qVariantValue<QPixmap>(item->data(0, Qt::DecorationRole));
742         if (pixmap.isNull()) {
743             pixmap = QPixmap(width, height);
744             pixmap.fill(Qt::transparent);
745         }
746         KIcon icon("dialog-close");
747         QPainter p(&pixmap);
748         p.drawPixmap(3, 3, icon.pixmap(width - 6, height - 6));
749         p.end();
750         item->setPixmap(pixmap);
751         if (item->referencedClip()) {
752             item->referencedClip()->setPlaceHolder(true);
753             Mlt::Producer *newProd = m_render->invalidProducer(id);
754             if (item->referencedClip()->getProducer()) {
755                 Mlt::Properties props(newProd->get_properties());
756                 Mlt::Properties src_props(item->referencedClip()->getProducer()->get_properties());
757                 props.inherit(src_props);
758             }
759             item->referencedClip()->setProducer(newProd, true);
760             item->slotSetToolTip();
761             emit clipNeedsReload(id);
762         }
763     }
764     update();
765     emit displayMessage(i18n("Check missing clips"), -2, ErrorMessage);
766     emit updateRenderStatus();
767 }
768
769 void ProjectList::slotAvailableClip(const QString &id)
770 {
771     ProjectItem *item = getItemById(id);
772     if (item == NULL)
773         return;
774     item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsDropEnabled);
775     if (item->referencedClip()) { // && item->referencedClip()->checkHash() == false) {
776         item->setProperty("file_hash", QString());
777         slotReloadClip(id);
778     }
779     /*else {
780     item->referencedClip()->setValid();
781     item->slotSetToolTip();
782     }
783     update();*/
784     emit updateRenderStatus();
785 }
786
787 bool ProjectList::hasMissingClips()
788 {
789     bool missing = false;
790     QTreeWidgetItemIterator it(m_listView);
791     while (*it) {
792         if ((*it)->type() == ProjectClipType && !((*it)->flags() & Qt::ItemIsDragEnabled)) {
793             missing = true;
794             break;
795         }
796         it++;
797     }
798     return missing;
799 }
800
801 void ProjectList::setRenderer(Render *projectRender)
802 {
803     m_render = projectRender;
804     m_listView->setIconSize(QSize((ProjectItem::itemDefaultHeight() - 2) * m_render->dar(), ProjectItem::itemDefaultHeight() - 2));
805     connect(m_render, SIGNAL(requestProxy(QString)), this, SLOT(slotCreateProxy(QString)));
806 }
807
808 void ProjectList::slotClipSelected()
809 {
810     QTreeWidgetItem *item = m_listView->currentItem();
811     ProjectItem *clip = NULL;
812     if (item) {
813         if (item->type() == ProjectFoldeType) {
814             emit clipSelected(NULL);
815             m_editButton->defaultAction()->setEnabled(item->childCount() > 0);
816             m_deleteButton->defaultAction()->setEnabled(true);
817             m_openAction->setEnabled(false);
818             m_reloadAction->setEnabled(false);
819             m_extractAudioAction->setEnabled(false);
820             m_transcodeAction->setEnabled(false);
821             m_clipsActionsMenu->setEnabled(false);
822         } else {
823             if (item->type() == ProjectSubclipType) {
824                 // this is a sub item, use base clip
825                 m_deleteButton->defaultAction()->setEnabled(true);
826                 clip = static_cast <ProjectItem*>(item->parent());
827                 if (clip == NULL) {
828                     kDebug() << "-----------ERROR";
829                     return;
830                 }
831                 SubProjectItem *sub = static_cast <SubProjectItem*>(item);
832                 if (clip->referencedClip()->getProducer() == NULL) m_render->getFileProperties(clip->referencedClip()->toXML(), clip->clipId(), m_listView->iconSize().height(), true);
833                 emit clipSelected(clip->referencedClip(), sub->zone());
834                 m_extractAudioAction->setEnabled(false);
835                 m_transcodeAction->setEnabled(false);
836                 m_clipsActionsMenu->setEnabled(false);
837                 m_reloadAction->setEnabled(false);
838                 adjustProxyActions(clip);
839                 return;
840             }
841             clip = static_cast <ProjectItem*>(item);
842             if (clip && clip->referencedClip())
843                 emit clipSelected(clip->referencedClip());
844             if (clip->referencedClip()->getProducer() == NULL) m_render->getFileProperties(clip->referencedClip()->toXML(), clip->clipId(), m_listView->iconSize().height(), true);
845             m_editButton->defaultAction()->setEnabled(true);
846             m_deleteButton->defaultAction()->setEnabled(true);
847             m_reloadAction->setEnabled(true);
848             m_extractAudioAction->setEnabled(true);
849             m_transcodeAction->setEnabled(true);
850             m_clipsActionsMenu->setEnabled(true);
851             if (clip && clip->clipType() == Image && !KdenliveSettings::defaultimageapp().isEmpty()) {
852                 m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
853                 m_openAction->setEnabled(true);
854             } else if (clip && clip->clipType() == Audio && !KdenliveSettings::defaultaudioapp().isEmpty()) {
855                 m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
856                 m_openAction->setEnabled(true);
857             } else {
858                 m_openAction->setEnabled(false);
859             }
860             // Display relevant transcoding actions only
861             adjustTranscodeActions(clip);
862             adjustStabilizeActions(clip);
863             // Display uses in timeline
864             emit findInTimeline(clip->clipId());
865         }
866     } else {
867         emit clipSelected(NULL);
868         m_editButton->defaultAction()->setEnabled(false);
869         m_deleteButton->defaultAction()->setEnabled(false);
870         m_openAction->setEnabled(false);
871         m_reloadAction->setEnabled(false);
872         m_extractAudioAction->setEnabled(true);
873         m_transcodeAction->setEnabled(false);
874         m_clipsActionsMenu->setEnabled(false);
875     }
876     adjustProxyActions(clip);
877 }
878
879 void ProjectList::adjustProxyActions(ProjectItem *clip) const
880 {
881     if (!m_proxyAction) return;
882     if (clip == NULL || clip->type() != ProjectClipType || clip->clipType() == Color || clip->clipType() == Text || clip->clipType() == SlideShow || clip->clipType() == Audio) {
883         m_proxyAction->setEnabled(false);
884         return;
885     }
886     bool enabled = useProxy();
887     if (clip->referencedClip() && !clip->referencedClip()->getProperty("_missingsource").isEmpty()) enabled = false;
888     m_proxyAction->setEnabled(enabled);
889     m_proxyAction->blockSignals(true);
890     m_proxyAction->setChecked(clip->hasProxy());
891     m_proxyAction->blockSignals(false);
892 }
893
894 void ProjectList::adjustStabilizeActions(ProjectItem *clip) const
895 {
896
897     if (clip == NULL || clip->type() != ProjectClipType || clip->clipType() == Color || clip->clipType() == Text || clip->clipType() == SlideShow) {
898         m_clipsActionsMenu->setEnabled(false);
899         return;
900     }
901     m_clipsActionsMenu->setEnabled(true);
902
903 }
904
905 void ProjectList::adjustTranscodeActions(ProjectItem *clip) const
906 {
907     if (clip == NULL || clip->type() != ProjectClipType || clip->clipType() == Color || clip->clipType() == Text || clip->clipType() == Playlist || clip->clipType() == SlideShow) {
908         m_transcodeAction->setEnabled(false);
909         m_extractAudioAction->setEnabled(false);
910         return;
911     }
912     m_transcodeAction->setEnabled(true);
913     m_extractAudioAction->setEnabled(true);
914     QList<QAction *> transcodeActions = m_transcodeAction->actions();
915     QStringList data;
916     QString condition;
917     for (int i = 0; i < transcodeActions.count(); ++i) {
918         data = transcodeActions.at(i)->data().toStringList();
919         if (data.count() > 2) {
920             condition = data.at(2);
921             if (condition.startsWith("vcodec"))
922                 transcodeActions.at(i)->setEnabled(clip->referencedClip()->hasVideoCodec(condition.section('=', 1, 1)));
923             else if (condition.startsWith("acodec"))
924                 transcodeActions.at(i)->setEnabled(clip->referencedClip()->hasVideoCodec(condition.section('=', 1, 1)));
925         }
926     }
927
928 }
929
930 void ProjectList::slotPauseMonitor()
931 {
932     if (m_render)
933         m_render->pause();
934 }
935
936 void ProjectList::slotUpdateClipProperties(const QString &id, QMap <QString, QString> properties)
937 {
938     ProjectItem *item = getItemById(id);
939     if (item) {
940         slotUpdateClipProperties(item, properties);
941         if (properties.contains("out") || properties.contains("force_fps") || properties.contains("resource") || properties.contains("video_index") || properties.contains("audio_index") || properties.contains("full_luma") || properties.contains("force_progressive") || properties.contains("force_tff") || properties.contains("force_colorspace")) {
942             slotReloadClip(id);
943         } else if (properties.contains("colour") ||
944                    properties.contains("xmldata") ||
945                    properties.contains("force_aspect_num") ||
946                    properties.contains("force_aspect_den") ||
947                    properties.contains("templatetext")) {
948             slotRefreshClipThumbnail(item);
949             emit refreshClip(id, true);
950         } else if (properties.contains("loop")) {
951             emit refreshClip(id, false);
952         }
953     }
954 }
955
956 void ProjectList::slotUpdateClipProperties(ProjectItem *clip, QMap <QString, QString> properties)
957 {
958     if (!clip)
959         return;
960     clip->setProperties(properties);
961     if (properties.contains("proxy")) {
962         if (properties.value("proxy") == "-" || properties.value("proxy").isEmpty())
963             // this should only apply to proxy jobs
964             clip->setConditionalJobStatus(NoJob, PROXYJOB);
965     }
966     if (properties.contains("name")) {
967         monitorItemEditing(false);
968         clip->setText(0, properties.value("name"));
969         monitorItemEditing(true);
970         emit clipNameChanged(clip->clipId(), properties.value("name"));
971     }
972     if (properties.contains("description")) {
973 #ifdef USE_NEPOMUK
974         ClipType type = clip->clipType();
975 #endif
976         monitorItemEditing(false);
977         clip->setText(1, properties.value("description"));
978         monitorItemEditing(true);
979
980 #ifdef USE_NEPOMUK
981         bool hasType = (type == Audio || type == Video || type == AV ||
982                         type == Image || type == Playlist);
983
984         if (KdenliveSettings::activate_nepomuk() && hasType) {
985             // Use Nepomuk system to store clip description
986             Nepomuk::Resource f(clip->clipUrl().path());
987             f.setDescription(properties.value("description"));
988         }
989 #endif
990         emit projectModified();
991     }
992 }
993
994 void ProjectList::slotItemEdited(QTreeWidgetItem *item, int column)
995 {
996     if (item->type() == ProjectSubclipType) {
997         // this is a sub-item
998         if (column == 1) {
999             // user edited description
1000             SubProjectItem *sub = static_cast <SubProjectItem*>(item);
1001             ProjectItem *item = static_cast <ProjectItem *>(sub->parent());
1002             EditClipCutCommand *command = new EditClipCutCommand(this, item->clipId(), sub->zone(), sub->zone(), sub->description(), sub->text(1), true);
1003             m_commandStack->push(command);
1004             //slotUpdateCutClipProperties(sub->clipId(), sub->zone(), sub->text(1), sub->text(1));
1005         }
1006         return;
1007     }
1008     if (item->type() == ProjectFoldeType) {
1009         if (column == 0) {
1010             FolderProjectItem *folder = static_cast <FolderProjectItem*>(item);
1011             if (item->text(0) == folder->groupName()) return;
1012             editFolder(item->text(0), folder->groupName(), folder->clipId());
1013             folder->setGroupName(item->text(0));
1014             m_doc->clipManager()->addFolder(folder->clipId(), item->text(0));
1015             const int children = item->childCount();
1016             for (int i = 0; i < children; ++i) {
1017                 ProjectItem *child = static_cast <ProjectItem *>(item->child(i));
1018                 child->setProperty("groupname", item->text(0));
1019             }
1020         }
1021         return;
1022     }
1023
1024     ProjectItem *clip = static_cast <ProjectItem*>(item);
1025     if (column == 1) {
1026         if (clip->referencedClip()) {
1027             QMap <QString, QString> oldprops;
1028             QMap <QString, QString> newprops;
1029             oldprops["description"] = clip->referencedClip()->getProperty("description");
1030             newprops["description"] = item->text(1);
1031
1032             if (clip->clipType() == Text) {
1033                 // This is a text template clip, update the image
1034                 /*oldprops.insert("xmldata", clip->referencedClip()->getProperty("xmldata"));
1035                 newprops.insert("xmldata", generateTemplateXml(clip->referencedClip()->getProperty("xmltemplate"), item->text(2)).toString());*/
1036                 oldprops.insert("templatetext", clip->referencedClip()->getProperty("templatetext"));
1037                 newprops.insert("templatetext", item->text(1));
1038             }
1039             slotUpdateClipProperties(clip->clipId(), newprops);
1040             EditClipCommand *command = new EditClipCommand(this, clip->clipId(), oldprops, newprops, false);
1041             m_commandStack->push(command);
1042         }
1043     } else if (column == 0) {
1044         if (clip->referencedClip()) {
1045             QMap <QString, QString> oldprops;
1046             QMap <QString, QString> newprops;
1047             oldprops["name"] = clip->referencedClip()->getProperty("name");
1048             if (oldprops.value("name") != item->text(0)) {
1049                 newprops["name"] = item->text(0);
1050                 slotUpdateClipProperties(clip, newprops);
1051                 emit projectModified();
1052                 EditClipCommand *command = new EditClipCommand(this, clip->clipId(), oldprops, newprops, false);
1053                 m_commandStack->push(command);
1054                 QTimer::singleShot(100, this, SLOT(slotCheckScrolling()));
1055             }
1056         }
1057     }
1058 }
1059
1060 void ProjectList::slotCheckScrolling()
1061 {
1062     m_listView->scrollToItem(m_listView->currentItem());
1063 }
1064
1065 void ProjectList::slotContextMenu(const QPoint &pos, QTreeWidgetItem *item)
1066 {
1067     if (!m_menu) {
1068         kDebug()<<"Warning, menu was not created, something is wrong";
1069         return;
1070     }
1071     bool enable = item ? true : false;
1072     m_editButton->defaultAction()->setEnabled(enable);
1073     m_deleteButton->defaultAction()->setEnabled(enable);
1074     m_reloadAction->setEnabled(enable);
1075     m_extractAudioAction->setEnabled(enable);
1076     m_transcodeAction->setEnabled(enable);
1077     m_clipsActionsMenu->setEnabled(enable);
1078     if (enable) {
1079         ProjectItem *clip = NULL;
1080         if (m_listView->currentItem()->type() == ProjectSubclipType) {
1081             clip = static_cast <ProjectItem*>(item->parent());
1082             m_extractAudioAction->setEnabled(false);
1083             m_transcodeAction->setEnabled(false);
1084             m_clipsActionsMenu->setEnabled(false);
1085             adjustProxyActions(clip);
1086         } else if (m_listView->currentItem()->type() == ProjectClipType) {
1087             clip = static_cast <ProjectItem*>(item);
1088             // Display relevant transcoding actions only
1089             adjustTranscodeActions(clip);
1090             adjustStabilizeActions(clip);
1091             adjustProxyActions(clip);
1092             // Display uses in timeline
1093             emit findInTimeline(clip->clipId());
1094         } else {
1095             m_extractAudioAction->setEnabled(false);
1096             m_transcodeAction->setEnabled(false);
1097             m_clipsActionsMenu->setEnabled(false);
1098         }
1099         if (clip && clip->clipType() == Image && !KdenliveSettings::defaultimageapp().isEmpty()) {
1100             m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
1101             m_openAction->setEnabled(true);
1102         } else if (clip && clip->clipType() == Audio && !KdenliveSettings::defaultaudioapp().isEmpty()) {
1103             m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
1104             m_openAction->setEnabled(true);
1105         } else {
1106             m_openAction->setEnabled(false);
1107         }
1108
1109     } else {
1110         m_openAction->setEnabled(false);
1111     }
1112     m_menu->popup(pos);
1113 }
1114
1115 void ProjectList::slotRemoveClip()
1116 {
1117     if (!m_listView->currentItem())
1118         return;
1119     QStringList ids;
1120     QMap <QString, QString> folderids;
1121     QList<QTreeWidgetItem *> selected = m_listView->selectedItems();
1122
1123     QUndoCommand *delCommand = new QUndoCommand();
1124     delCommand->setText(i18n("Delete Clip Zone"));
1125     for (int i = 0; i < selected.count(); ++i) {
1126         if (selected.at(i)->type() == ProjectSubclipType) {
1127             // subitem
1128             SubProjectItem *sub = static_cast <SubProjectItem *>(selected.at(i));
1129             ProjectItem *item = static_cast <ProjectItem *>(sub->parent());
1130             new AddClipCutCommand(this, item->clipId(), sub->zone().x(), sub->zone().y(), sub->description(), false, true, delCommand);
1131         } else if (selected.at(i)->type() == ProjectFoldeType) {
1132             // folder
1133             FolderProjectItem *folder = static_cast <FolderProjectItem *>(selected.at(i));
1134             folderids[folder->groupName()] = folder->clipId();
1135             int children = folder->childCount();
1136
1137             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)
1138                 return;
1139             for (int i = 0; i < children; ++i) {
1140                 ProjectItem *child = static_cast <ProjectItem *>(folder->child(i));
1141                 ids << child->clipId();
1142             }
1143         } else {
1144             ProjectItem *item = static_cast <ProjectItem *>(selected.at(i));
1145             ids << item->clipId();
1146             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->text(1)), i18n("Delete Clip"), KStandardGuiItem::yes(), KStandardGuiItem::no(), "DeleteAll") == KMessageBox::No) {
1147                 KMessageBox::enableMessage("DeleteAll");
1148                 return;
1149             }
1150         }
1151     }
1152     KMessageBox::enableMessage("DeleteAll");
1153     if (delCommand->childCount() == 0)
1154         delete delCommand;
1155     else
1156         m_commandStack->push(delCommand);
1157     emit deleteProjectClips(ids, folderids);
1158 }
1159
1160 void ProjectList::updateButtons() const
1161 {
1162     if (m_listView->topLevelItemCount() == 0) {
1163         m_deleteButton->defaultAction()->setEnabled(false);
1164         m_editButton->defaultAction()->setEnabled(false);
1165     } else {
1166         m_deleteButton->defaultAction()->setEnabled(true);
1167         if (!m_listView->currentItem())
1168             m_listView->setCurrentItem(m_listView->topLevelItem(0));
1169         QTreeWidgetItem *item = m_listView->currentItem();
1170         if (item && item->type() == ProjectClipType) {
1171             m_editButton->defaultAction()->setEnabled(true);
1172             m_openAction->setEnabled(true);
1173             m_reloadAction->setEnabled(true);
1174             m_transcodeAction->setEnabled(true);
1175             m_clipsActionsMenu->setEnabled(true);
1176             return;
1177         }
1178         else if (item && item->type() == ProjectFoldeType && item->childCount() > 0) {
1179             m_editButton->defaultAction()->setEnabled(true);
1180         }
1181         else m_editButton->defaultAction()->setEnabled(false);
1182     }
1183     m_openAction->setEnabled(false);
1184     if (m_reloadAction) m_reloadAction->setEnabled(false);
1185     m_transcodeAction->setEnabled(false);
1186     m_clipsActionsMenu->setEnabled(false);
1187     if (m_proxyAction) m_proxyAction->setEnabled(false);
1188 }
1189
1190 void ProjectList::selectItemById(const QString &clipId)
1191 {
1192     ProjectItem *item = getItemById(clipId);
1193     if (item)
1194         m_listView->setCurrentItem(item);
1195 }
1196
1197
1198 void ProjectList::slotDeleteClip(const QString &clipId)
1199 {
1200     ProjectItem *item = getItemById(clipId);
1201     if (!item) {
1202         kDebug() << "/// Cannot find clip to delete";
1203         return;
1204     }
1205     deleteJobsForClip(clipId);
1206     m_listView->blockSignals(true);
1207     QTreeWidgetItem *newSelectedItem = m_listView->itemAbove(item);
1208     if (!newSelectedItem)
1209         newSelectedItem = m_listView->itemBelow(item);
1210     delete item;
1211     // Pause playing to prevent crash while deleting clip
1212     slotPauseMonitor();
1213     m_doc->clipManager()->deleteClip(clipId);
1214     m_listView->blockSignals(false);
1215     if (newSelectedItem) {
1216         m_listView->setCurrentItem(newSelectedItem);
1217     } else {
1218         updateButtons();
1219         emit clipSelected(NULL);
1220     }
1221 }
1222
1223
1224 void ProjectList::editFolder(const QString folderName, const QString oldfolderName, const QString &clipId)
1225 {
1226     EditFolderCommand *command = new EditFolderCommand(this, folderName, oldfolderName, clipId, false);
1227     m_commandStack->push(command);
1228     m_doc->setModified(true);
1229 }
1230
1231 void ProjectList::slotAddFolder(const QString &name)
1232 {
1233     AddFolderCommand *command = new AddFolderCommand(this, name.isEmpty() ? i18n("Folder") : name, QString::number(m_doc->clipManager()->getFreeFolderId()), true);
1234     m_commandStack->push(command);
1235 }
1236
1237 void ProjectList::slotAddFolder(const QString &foldername, const QString &clipId, bool remove, bool edit)
1238 {
1239     if (remove) {
1240         FolderProjectItem *item = getFolderItemById(clipId);
1241         if (item) {
1242             m_doc->clipManager()->deleteFolder(clipId);
1243             QTreeWidgetItem *newSelectedItem = m_listView->itemAbove(item);
1244             if (!newSelectedItem)
1245                 newSelectedItem = m_listView->itemBelow(item);
1246             delete item;
1247             if (newSelectedItem)
1248                 m_listView->setCurrentItem(newSelectedItem);
1249             else
1250                 updateButtons();
1251         }
1252     } else {
1253         if (edit) {
1254             FolderProjectItem *item = getFolderItemById(clipId);
1255             if (item) {
1256                 m_listView->blockSignals(true);
1257                 item->setGroupName(foldername);
1258                 m_listView->blockSignals(false);
1259                 m_doc->clipManager()->addFolder(clipId, foldername);
1260                 const int children = item->childCount();
1261                 for (int i = 0; i < children; ++i) {
1262                     ProjectItem *child = static_cast <ProjectItem *>(item->child(i));
1263                     child->setProperty("groupname", foldername);
1264                 }
1265             }
1266         } else {
1267             m_listView->blockSignals(true);
1268             m_listView->setCurrentItem(new FolderProjectItem(m_listView, QStringList() << foldername, clipId));
1269             m_doc->clipManager()->addFolder(clipId, foldername);
1270             m_listView->blockSignals(false);
1271             m_listView->editItem(m_listView->currentItem(), 0);
1272         }
1273         updateButtons();
1274     }
1275     m_doc->setModified(true);
1276 }
1277
1278
1279
1280 void ProjectList::deleteProjectFolder(QMap <QString, QString> map)
1281 {
1282     QMapIterator<QString, QString> i(map);
1283     QUndoCommand *delCommand = new QUndoCommand();
1284     delCommand->setText(i18n("Delete Folder"));
1285     while (i.hasNext()) {
1286         i.next();
1287         new AddFolderCommand(this, i.key(), i.value(), false, delCommand);
1288     }
1289     if (delCommand->childCount() > 0) m_commandStack->push(delCommand);
1290     else delete delCommand;
1291 }
1292
1293 void ProjectList::slotAddClip(DocClipBase *clip, bool getProperties)
1294 {
1295     //m_listView->setEnabled(false);
1296     const QString parent = clip->getProperty("groupid");
1297     QString groupName = clip->getProperty("groupname");
1298     QSize pixelSize((int)(m_listView->iconSize().height()  * m_render->dar()), m_listView->iconSize().height());
1299     ProjectItem *item = NULL;
1300     monitorItemEditing(false);
1301     if (!parent.isEmpty()) {
1302         FolderProjectItem *parentitem = getFolderItemById(parent);
1303         if (!parentitem) {
1304             QStringList text;
1305             //kDebug() << "Adding clip to new group: " << groupName;
1306             if (groupName.isEmpty()) groupName = i18n("Folder");
1307             text << groupName;
1308             parentitem = new FolderProjectItem(m_listView, text, parent);
1309         }
1310
1311         if (parentitem)
1312             item = new ProjectItem(parentitem, clip, pixelSize);
1313     }
1314     if (item == NULL) {
1315         item = new ProjectItem(m_listView, clip, pixelSize);
1316     }
1317     if (item->data(0, ItemDelegate::DurationRole).isNull()) item->setData(0, ItemDelegate::DurationRole, i18n("Loading"));
1318     connect(clip, SIGNAL(createProxy(QString)), this, SLOT(slotCreateProxy(QString)));
1319     connect(clip, SIGNAL(abortProxy(QString,QString)), this, SLOT(slotAbortProxy(QString,QString)));
1320
1321     if (getProperties) {
1322         //item->setFlags(Qt::ItemIsSelectable);
1323         m_listView->processLayout();
1324         QDomElement e = clip->toXML().cloneNode().toElement();
1325         if (!groupName.isEmpty()) {
1326             e.setAttribute("groupId", parent);
1327             e.setAttribute("group", groupName);
1328         }
1329         e.removeAttribute("file_hash");
1330         resetThumbsProducer(clip);
1331         m_render->getFileProperties(e, clip->getId(), m_listView->iconSize().height(), true);
1332     }
1333     // WARNING: code below triggers unnecessary reload of all proxy clips on document loading... is it useful in some cases?
1334     /*else if (item->hasProxy() && !item->isJobRunning()) {
1335         slotCreateProxy(clip->getId());
1336     }*/
1337     
1338     KUrl url = clip->fileURL();
1339 #ifdef USE_NEPOMUK
1340     if (!url.isEmpty() && KdenliveSettings::activate_nepomuk() && clip->getProperty("description").isEmpty()) {
1341         // if file has Nepomuk comment, use it
1342         Nepomuk::Resource f(url.path());
1343         QString annotation = f.description();
1344         if (!annotation.isEmpty()) {
1345             item->setText(1, annotation);
1346             clip->setProperty("description", annotation);
1347         }
1348         item->setText(2, QString::number(f.rating()));
1349     }
1350 #endif
1351
1352     // Add info to date column
1353     QFileInfo fileInfo(url.path());
1354     if (fileInfo.exists()) {
1355         item->setText(3, fileInfo.lastModified().toString(QString("yyyy/MM/dd hh:mm:ss")));
1356     }
1357
1358     // Add cut zones
1359     QList <CutZoneInfo> cuts = clip->cutZones();
1360     if (!cuts.isEmpty()) {
1361         for (int i = 0; i < cuts.count(); ++i) {
1362             SubProjectItem *sub = new SubProjectItem(m_render->dar(), item, cuts.at(i).zone.x(), cuts.at(i).zone.y(), cuts.at(i).description);
1363             if (!clip->getClipHash().isEmpty()) {
1364                 QString cachedPixmap = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "thumbs/" + clip->getClipHash() + '#' + QString::number(cuts.at(i).zone.x()) + ".png";
1365                 if (QFile::exists(cachedPixmap)) {
1366                     QPixmap pix(cachedPixmap);
1367                     if (pix.isNull())
1368                         KIO::NetAccess::del(KUrl(cachedPixmap), this);
1369                     sub->setData(0, Qt::DecorationRole, pix);
1370                 }
1371             }
1372         }
1373     }
1374     monitorItemEditing(true);
1375     updateButtons();
1376 }
1377
1378 void ProjectList::slotGotProxy(const QString &proxyPath)
1379 {
1380     if (proxyPath.isEmpty() || m_abortAllJobs) return;
1381     QTreeWidgetItemIterator it(m_listView);
1382     ProjectItem *item;
1383
1384     while (*it && !m_closing) {
1385         if ((*it)->type() == ProjectClipType) {
1386             item = static_cast <ProjectItem *>(*it);
1387             if (item->referencedClip()->getProperty("proxy") == proxyPath)
1388                 slotGotProxy(item);
1389         }
1390         ++it;
1391     }
1392 }
1393
1394 void ProjectList::slotGotProxyForId(const QString id)
1395 {
1396     if (m_closing) return;
1397     ProjectItem *item = getItemById(id);
1398     slotGotProxy(item);
1399 }
1400
1401 void ProjectList::slotGotProxy(ProjectItem *item)
1402 {
1403     if (item == NULL) return;
1404     DocClipBase *clip = item->referencedClip();
1405     if (!clip || !clip->isClean() || m_render->isProcessing(item->clipId())) {
1406         // Clip is being reprocessed, abort
1407         kDebug()<<"//// TRYING TO PROXY: "<<item->clipId()<<", but it is busy";
1408         return;
1409     }
1410     
1411     // Proxy clip successfully created
1412     QDomElement e = clip->toXML().cloneNode().toElement();
1413
1414     // Make sure we get the correct producer length if it was adjusted in timeline
1415     ClipType t = item->clipType();
1416     if (t == Color || t == Image || t == SlideShow || t == Text) {
1417         int length = QString(clip->producerProperty("length")).toInt();
1418         if (length > 0 && !e.hasAttribute("length")) {
1419             e.setAttribute("length", length);
1420         }
1421     }
1422     resetThumbsProducer(clip);
1423     m_render->getFileProperties(e, clip->getId(), m_listView->iconSize().height(), true);
1424 }
1425
1426 void ProjectList::slotResetProjectList()
1427 {
1428     m_listView->blockSignals(true);
1429     m_abortAllJobs = true;
1430     for (int i = 0; i < m_jobList.count(); ++i) {
1431         m_jobList.at(i)->setStatus(JobAborted);
1432     }
1433     m_closing = true;
1434     m_jobThreads.waitForFinished();
1435     m_jobThreads.clearFutures();
1436     m_thumbnailQueue.clear();
1437     if (!m_jobList.isEmpty()) qDeleteAll(m_jobList);
1438     m_jobList.clear();
1439     m_listView->clear();
1440     m_listView->setEnabled(true);
1441     emit clipSelected(NULL);
1442     m_refreshed = false;
1443     m_allClipsProcessed = false;
1444     m_abortAllJobs = false;
1445     m_closing = false;
1446     m_listView->blockSignals(false);
1447 }
1448
1449 void ProjectList::slotUpdateClip(const QString &id)
1450 {
1451     ProjectItem *item = getItemById(id);
1452     monitorItemEditing(false);
1453     if (item){
1454         item->setData(0, ItemDelegate::UsageRole, QString::number(item->numReferences()));
1455     }
1456     monitorItemEditing(true);
1457 }
1458
1459 void ProjectList::getCachedThumbnail(ProjectItem *item)
1460 {
1461     if (!item) return;
1462     DocClipBase *clip = item->referencedClip();
1463     if (!clip) {
1464         return;
1465     }
1466     QString cachedPixmap = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "thumbs/" + clip->getClipHash() + ".png";
1467     if (QFile::exists(cachedPixmap)) {
1468         QPixmap pix(cachedPixmap);
1469         if (pix.isNull()) {
1470             KIO::NetAccess::del(KUrl(cachedPixmap), this);
1471             requestClipThumbnail(item->clipId());
1472         }
1473         else {
1474             QPixmap result = roundedPixmap(pix);
1475             processThumbOverlays(item, result);
1476             item->setPixmap(result);
1477         }
1478     }
1479     else {
1480         requestClipThumbnail(item->clipId());
1481     }
1482 }
1483
1484 QPixmap ProjectList::roundedPixmap(const QImage &img)
1485 {
1486     QPixmap pix(img.width(), img.height());
1487     pix.fill(Qt::transparent);
1488     QPainter p(&pix);
1489     p.setRenderHint(QPainter::Antialiasing, true);
1490     QPainterPath path;
1491     path.addRoundedRect(0.5, 0.5, pix.width() - 1, pix.height() - 1, 2, 2);
1492     p.setClipPath(path);
1493     p.drawImage(0, 0, img);
1494     p.end();
1495     return pix;
1496 }
1497
1498 QPixmap ProjectList::roundedPixmap(const QPixmap &source)
1499 {
1500     QPixmap pix(source.width(), source.height());
1501     pix.fill(Qt::transparent);
1502     QPainter p(&pix);
1503     p.setRenderHint(QPainter::Antialiasing, true);
1504     QPainterPath path;
1505     path.addRoundedRect(0.5, 0.5, pix.width() - 1, pix.height() - 1, 2, 2);
1506     p.setClipPath(path);
1507     p.drawPixmap(0, 0, source);
1508     p.end();
1509     return pix;
1510 }
1511
1512 void ProjectList::getCachedThumbnail(SubProjectItem *item)
1513 {
1514     if (!item) return;
1515     ProjectItem *parentItem = static_cast <ProjectItem *>(item->parent());
1516     if (!parentItem) return;
1517     DocClipBase *clip = parentItem->referencedClip();
1518     if (!clip) return;
1519     int pos = item->zone().x();
1520     QString cachedPixmap = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "thumbs/" + clip->getClipHash() + '#' + QString::number(pos) + ".png";
1521     if (QFile::exists(cachedPixmap)) {
1522         QPixmap pix(cachedPixmap);
1523         if (pix.isNull()) {
1524             KIO::NetAccess::del(KUrl(cachedPixmap), this);
1525             requestClipThumbnail(parentItem->clipId() + '#' + QString::number(pos));
1526         }
1527         else item->setData(0, Qt::DecorationRole, pix);
1528     }
1529     else requestClipThumbnail(parentItem->clipId() + '#' + QString::number(pos));
1530 }
1531
1532 void ProjectList::updateAllClips(bool displayRatioChanged, bool fpsChanged, const QStringList &brokenClips)
1533 {
1534     if (!m_allClipsProcessed) m_listView->setEnabled(false);
1535     m_listView->setSortingEnabled(false);
1536     QTreeWidgetItemIterator it(m_listView);
1537     DocClipBase *clip;
1538     ProjectItem *item;
1539     monitorItemEditing(false);
1540     int height = m_listView->iconSize().height();
1541     int width = (int)(height  * m_render->dar());
1542     QPixmap missingPixmap = QPixmap(width, height);
1543     missingPixmap.fill(Qt::transparent);
1544     KIcon icon("dialog-close");
1545     QPainter p(&missingPixmap);
1546     p.drawPixmap(3, 3, icon.pixmap(width - 6, height - 6));
1547     p.end();
1548     
1549     int max = m_doc->clipManager()->clipsCount();
1550     max = qMax(1, max);
1551     int ct = 0;
1552
1553     while (*it) {
1554         emit displayMessage(i18n("Loading thumbnails"), (int)(100 *(max - ct++) / max));
1555         if ((*it)->type() == ProjectSubclipType) {
1556             // subitem
1557             SubProjectItem *sub = static_cast <SubProjectItem *>(*it);
1558             if (displayRatioChanged) {
1559                 item = static_cast <ProjectItem *>((*it)->parent());
1560                 requestClipThumbnail(item->clipId() + '#' + QString::number(sub->zone().x()));
1561             }
1562             else if (sub->data(0, Qt::DecorationRole).isNull()) {
1563                 getCachedThumbnail(sub);
1564             }
1565             ++it;
1566             continue;
1567         } else if ((*it)->type() == ProjectFoldeType) {
1568             // folder
1569             ++it;
1570             continue;
1571         } else {
1572             item = static_cast <ProjectItem *>(*it);
1573             clip = item->referencedClip();
1574             if (clip->getProducer() == NULL) {
1575                 bool replace = false;
1576                 if (brokenClips.contains(item->clipId())) {
1577                     // if this is a proxy clip, disable proxy
1578                     item->setConditionalJobStatus(NoJob, PROXYJOB);
1579                     discardJobs(item->clipId(), PROXYJOB);
1580                     clip->setProperty("proxy", "-");
1581                     replace = true;
1582                 }
1583                 if (clip->isPlaceHolder() == false && !hasPendingJob(item, PROXYJOB)) {
1584                     QDomElement xml = clip->toXML();
1585                     getCachedThumbnail(item);
1586                     if (fpsChanged) {
1587                         xml.removeAttribute("out");
1588                         xml.removeAttribute("file_hash");
1589                         xml.removeAttribute("proxy_out");
1590                     }
1591                     if (!replace) replace = xml.attribute("_replaceproxy") == "1";
1592                     xml.removeAttribute("_replaceproxy");
1593                     if (replace) {
1594                         resetThumbsProducer(clip);
1595                         m_render->getFileProperties(xml, clip->getId(), m_listView->iconSize().height(), replace);
1596                     }
1597                     else if (item->numReferences() > 0) {
1598                         // In some cases, like slowmotion clips, the producer is not loaded automatically be MLT
1599                         m_render->getFileProperties(xml, clip->getId(), m_listView->iconSize().height(), replace);
1600                     }
1601                 }
1602                 else if (clip->isPlaceHolder()) {
1603                     item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsDropEnabled);
1604                     if (!item->hasPixmap()) {
1605                         item->setPixmap(missingPixmap);
1606                     }
1607                     else {
1608                         QPixmap pixmap = qVariantValue<QPixmap>(item->data(0, Qt::DecorationRole));
1609                         QPainter p(&pixmap);
1610                         p.drawPixmap(3, 3, KIcon("dialog-close").pixmap(pixmap.width() - 6, pixmap.height() - 6));
1611                         p.end();
1612                         item->setPixmap(pixmap);
1613                     }
1614                 }
1615             } else {
1616                 if (displayRatioChanged) {
1617                     requestClipThumbnail(clip->getId());
1618                 }
1619                 else if (!item->hasPixmap()) {
1620                     getCachedThumbnail(item);
1621                 }
1622                 if (item->data(0, ItemDelegate::DurationRole).toString().isEmpty()) {
1623                     item->changeDuration(clip->getProducer()->get_playtime());
1624                 }
1625                 if (clip->isPlaceHolder()) {
1626                     QPixmap pixmap = qVariantValue<QPixmap>(item->data(0, Qt::DecorationRole));
1627                     if (pixmap.isNull()) {
1628                         pixmap = QPixmap(width, height);
1629                         pixmap.fill(Qt::transparent);
1630                     }
1631                     QPainter p(&pixmap);
1632                     p.drawPixmap(3, 3, KIcon("dialog-close").pixmap(pixmap.width() - 6, pixmap.height() - 6));
1633                     p.end();
1634                     item->setPixmap(pixmap);
1635                 }
1636                 else if (clip->getProperty("_replaceproxy") == "1") {
1637                     clip->setProperty("_replaceproxy", QString());
1638                     slotCreateProxy(clip->getId());
1639                 }
1640             }
1641             item->setData(0, ItemDelegate::UsageRole, QString::number(item->numReferences()));
1642         }
1643         ++it;
1644     }
1645
1646     m_listView->setSortingEnabled(true);
1647     m_allClipsProcessed = true;
1648     if (m_render->processingItems() == 0) {
1649         monitorItemEditing(true);
1650         slotProcessNextThumbnail();
1651     }
1652 }
1653
1654 // static
1655 QString ProjectList::getExtensions()
1656 {
1657     // Build list of mime types
1658     QStringList mimeTypes = QStringList() << "application/x-kdenlive" << "application/x-kdenlivetitle" << "video/mlt-playlist" << "text/plain";
1659
1660     // Video mimes
1661     mimeTypes <<  "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" << "video/3gpp" << "video/mp2t";
1662
1663     // Audio mimes
1664     mimeTypes << "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" << "audio/ac3";
1665
1666     // Image mimes
1667     mimeTypes << "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";
1668
1669     QString allExtensions;
1670     foreach(const QString & mimeType, mimeTypes) {
1671         KMimeType::Ptr mime(KMimeType::mimeType(mimeType));
1672         if (mime) {
1673             allExtensions.append(mime->patterns().join(" "));
1674             allExtensions.append(' ');
1675         }
1676     }
1677     return allExtensions.simplified();
1678 }
1679
1680 void ProjectList::slotAddClip(const QString &url, const QString &groupName, const QString &groupId)
1681 {
1682     kDebug()<<"// Adding clip: "<<url;
1683     QList <QUrl> list;
1684     list.append(url);
1685     slotAddClip(list, groupName, groupId);
1686 }
1687
1688 void ProjectList::slotAddClip(const QList <QUrl> &givenList, const QString &groupName, const QString &groupId)
1689 {
1690     if (!m_commandStack)
1691         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1692
1693     KUrl::List list;
1694     if (givenList.isEmpty()) {
1695         QString allExtensions = getExtensions();
1696         const QString dialogFilter = allExtensions + ' ' + QLatin1Char('|') + i18n("All Supported Files") + "\n* " + QLatin1Char('|') + i18n("All Files");
1697         QCheckBox *b = new QCheckBox(i18n("Import image sequence"));
1698         b->setChecked(KdenliveSettings::autoimagesequence());
1699         QCheckBox *c = new QCheckBox(i18n("Transparent background for images"));
1700         c->setChecked(KdenliveSettings::autoimagetransparency());
1701         QFrame *f = new QFrame;
1702         f->setFrameShape(QFrame::NoFrame);
1703         QHBoxLayout *l = new QHBoxLayout;
1704         l->addWidget(b);
1705         l->addWidget(c);
1706         l->addStretch(5);
1707         f->setLayout(l);
1708
1709         QPointer<KFileDialog> d = new KFileDialog(KUrl("kfiledialog:///clipfolder"), dialogFilter, kapp->activeWindow(), f);
1710         d->setOperationMode(KFileDialog::Opening);
1711         d->setMode(KFile::Files);
1712         if (d->exec() == QDialog::Accepted) {
1713             KdenliveSettings::setAutoimagetransparency(c->isChecked());
1714             list = d->selectedUrls();
1715             if (b->isChecked() && list.count() == 1) {
1716                 // Check for image sequence
1717                 KUrl url = list.at(0);
1718                 QString fileName = url.fileName().section('.', 0, -2);
1719                 if (fileName.at(fileName.size() - 1).isDigit()) {
1720                     KFileItem item(KFileItem::Unknown, KFileItem::Unknown, url);
1721                     if (item.mimetype().startsWith("image")) {
1722                         // import as sequence if we found more than one image in the sequence
1723                         QStringList list;
1724                         QString pattern = SlideshowClip::selectedPath(url.path(), false, QString(), &list);
1725                         int count = list.count();
1726                         if (count > 1) {
1727                             delete d;
1728                             QStringList groupInfo = getGroup();
1729
1730                             // get image sequence base name
1731                             while (fileName.at(fileName.size() - 1).isDigit()) {
1732                                 fileName.chop(1);
1733                             }
1734                             QMap <QString, QString> properties;
1735                             properties.insert("name", fileName);
1736                             properties.insert("resource", pattern);
1737                             properties.insert("in", "0");
1738                             QString duration = m_timecode.reformatSeparators(KdenliveSettings::sequence_duration());
1739                             properties.insert("out", QString::number(m_doc->getFramePos(duration) * count));
1740                             properties.insert("ttl", QString::number(m_doc->getFramePos(duration)));
1741                             properties.insert("loop", QString::number(false));
1742                             properties.insert("crop", QString::number(false));
1743                             properties.insert("fade", QString::number(false));
1744                             properties.insert("luma_duration", QString::number(m_doc->getFramePos(m_timecode.getTimecodeFromFrames(int(ceil(m_timecode.fps()))))));
1745                             m_doc->slotCreateSlideshowClipFile(properties, groupInfo.at(0), groupInfo.at(1));
1746                             return;
1747                         }
1748                     }
1749                 }
1750             }
1751         }
1752         delete d;
1753     } else {
1754         for (int i = 0; i < givenList.count(); ++i)
1755             list << givenList.at(i);
1756     }
1757     QList <KUrl::List> foldersList;
1758
1759     foreach(const KUrl & file, list) {
1760         // Check there is no folder here
1761         KMimeType::Ptr type = KMimeType::findByUrl(file);
1762         if (type->is("inode/directory")) {
1763             // user dropped a folder, import its files
1764             list.removeAll(file);
1765             QDir dir(file.path());
1766             QStringList result = dir.entryList(QDir::Files);
1767             KUrl::List folderFiles;
1768             folderFiles << file;
1769             foreach(const QString & path, result) {
1770                 KUrl newFile = file;
1771                 newFile.addPath(path);
1772                 folderFiles.append(newFile);
1773             }
1774             if (folderFiles.count() > 1) foldersList.append(folderFiles);
1775         }
1776     }
1777
1778     if (givenList.isEmpty() && !list.isEmpty()) {
1779         QStringList groupInfo = getGroup();
1780         QMap <QString, QString> data;
1781         data.insert("group", groupInfo.at(0));
1782         data.insert("groupId", groupInfo.at(1));
1783         m_doc->slotAddClipList(list, data);
1784     } else if (!list.isEmpty()) {
1785         QMap <QString, QString> data;
1786         data.insert("group", groupName);
1787         data.insert("groupId", groupId);
1788         m_doc->slotAddClipList(list, data);
1789     }
1790     
1791     if (!foldersList.isEmpty()) {
1792         // create folders
1793         for (int i = 0; i < foldersList.count(); ++i) {
1794             KUrl::List urls = foldersList.at(i);
1795             KUrl folderUrl = urls.takeFirst();
1796             QString folderName = folderUrl.fileName();
1797             FolderProjectItem *folder = NULL;
1798             if (!folderName.isEmpty()) {
1799                 folder = getFolderItemByName(folderName);
1800                 if (folder == NULL) {
1801                     slotAddFolder(folderName);
1802                     folder = getFolderItemByName(folderName);
1803                 }
1804             }
1805             if (folder) {
1806                 QMap <QString, QString> data;
1807                 data.insert("group", folder->groupName());
1808                 data.insert("groupId", folder->clipId());
1809                 m_doc->slotAddClipList(urls, data);
1810             }
1811             else m_doc->slotAddClipList(urls);
1812         }
1813     }
1814 }
1815
1816 void ProjectList::slotRemoveInvalidClip(const QString &id, bool replace)
1817 {
1818     ProjectItem *item = getItemById(id);
1819     m_thumbnailQueue.removeAll(id);
1820     if (item) {
1821         item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsDropEnabled);
1822         const QString path = item->referencedClip()->fileURL().path();
1823         if (item->referencedClip()->isPlaceHolder()) replace = false;
1824         if (!path.isEmpty()) {
1825             if (m_invalidClipDialog) {
1826                 m_invalidClipDialog->addClip(id, path);
1827                 return;
1828             }
1829             else {
1830                 if (replace)
1831                     m_invalidClipDialog = new InvalidDialog(i18n("Invalid clip"),  i18n("Clip is invalid, will be removed from project."), replace, kapp->activeWindow());
1832                 else {
1833                     m_invalidClipDialog = new InvalidDialog(i18n("Invalid clip"),  i18n("Clip is missing or invalid. Remove it from project?"), replace, kapp->activeWindow());
1834                 }
1835                 m_invalidClipDialog->addClip(id, path);
1836                 int result = m_invalidClipDialog->exec();
1837                 if (result == KDialog::Yes) replace = true;
1838             }
1839         }
1840         if (m_invalidClipDialog) {
1841             if (replace)
1842                 emit deleteProjectClips(m_invalidClipDialog->getIds(), QMap <QString, QString>());
1843             delete m_invalidClipDialog;
1844             m_invalidClipDialog = NULL;
1845         }
1846         
1847     }
1848 }
1849
1850 void ProjectList::slotRemoveInvalidProxy(const QString &id, bool durationError)
1851 {
1852     ProjectItem *item = getItemById(id);
1853     if (item) {
1854         kDebug()<<"// Proxy for clip "<<id<<" is invalid, delete";
1855         item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsDropEnabled);
1856         if (durationError) {
1857             kDebug() << "Proxy duration is wrong, try changing transcoding parameters.";
1858             emit displayMessage(i18n("Proxy clip unusable (duration is different from original)."), -2, ErrorMessage);
1859         }
1860         slotUpdateJobStatus(item, PROXYJOB, JobCrashed, i18n("Failed to create proxy for %1. check parameters", item->text(0)), "project_settings");
1861         QString path = item->referencedClip()->getProperty("proxy");
1862         KUrl proxyFolder(m_doc->projectFolder().path( KUrl::AddTrailingSlash) + "proxy/");
1863
1864         //Security check: make sure the invalid proxy file is in the proxy folder
1865         if (proxyFolder.isParentOf(KUrl(path))) {
1866             QFile::remove(path);
1867         }
1868         if (item->referencedClip()->getProducer() == NULL) {
1869             // Clip has no valid producer, request it
1870             slotProxyCurrentItem(false, item);
1871         }
1872         else {
1873             // refresh thumbs producer
1874             item->referencedClip()->reloadThumbProducer();
1875         }
1876     }
1877     m_thumbnailQueue.removeAll(id);
1878 }
1879
1880 void ProjectList::slotAddColorClip()
1881 {
1882     if (!m_commandStack)
1883         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1884
1885     QPointer<QDialog> dia = new QDialog(this);
1886     Ui::ColorClip_UI dia_ui;
1887     dia_ui.setupUi(dia);
1888     dia->setWindowTitle(i18n("Color Clip"));
1889     dia_ui.clip_name->setText(i18n("Color Clip"));
1890
1891     TimecodeDisplay *t = new TimecodeDisplay(m_timecode);
1892     t->setValue(KdenliveSettings::color_duration());
1893     dia_ui.clip_durationBox->addWidget(t);
1894     dia_ui.clip_color->setColor(KdenliveSettings::colorclipcolor());
1895
1896     if (dia->exec() == QDialog::Accepted) {
1897         QString color = dia_ui.clip_color->color().name();
1898         KdenliveSettings::setColorclipcolor(color);
1899         color = color.replace(0, 1, "0x") + "ff";
1900         QStringList groupInfo = getGroup();
1901         m_doc->slotCreateColorClip(dia_ui.clip_name->text(), color, m_timecode.getTimecode(t->gentime()), groupInfo.at(0), groupInfo.at(1));
1902     }
1903     delete t;
1904     delete dia;
1905 }
1906
1907
1908 void ProjectList::slotAddSlideshowClip()
1909 {
1910     if (!m_commandStack)
1911         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1912
1913     SlideshowClip *dia = new SlideshowClip(m_timecode, this);
1914
1915     if (dia->exec() == QDialog::Accepted) {
1916         QStringList groupInfo = getGroup();
1917         
1918         QMap <QString, QString> properties;
1919         properties.insert("name", dia->clipName());
1920         properties.insert("resource", dia->selectedPath());
1921         properties.insert("in", "0");
1922         properties.insert("out", QString::number(m_doc->getFramePos(dia->clipDuration()) * dia->imageCount()));
1923         properties.insert("ttl", QString::number(m_doc->getFramePos(dia->clipDuration())));
1924         properties.insert("loop", QString::number(dia->loop()));
1925         properties.insert("crop", QString::number(dia->crop()));
1926         properties.insert("fade", QString::number(dia->fade()));
1927         properties.insert("luma_duration", dia->lumaDuration());
1928         properties.insert("luma_file", dia->lumaFile());
1929         properties.insert("softness", QString::number(dia->softness()));
1930         properties.insert("animation", dia->animation());
1931         
1932         m_doc->slotCreateSlideshowClipFile(properties, groupInfo.at(0), groupInfo.at(1));
1933     }
1934     delete dia;
1935 }
1936
1937 void ProjectList::slotAddTitleClip()
1938 {
1939     QStringList groupInfo = getGroup();
1940     m_doc->slotCreateTextClip(groupInfo.at(0), groupInfo.at(1));
1941 }
1942
1943 void ProjectList::slotAddTitleTemplateClip()
1944 {
1945     if (!m_commandStack)
1946         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1947
1948     QStringList groupInfo = getGroup();
1949
1950     // Get the list of existing templates
1951     QStringList filter;
1952     filter << "*.kdenlivetitle";
1953     const QString path = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1954     QStringList templateFiles = QDir(path).entryList(filter, QDir::Files);
1955
1956     QPointer<QDialog> dia = new QDialog(this);
1957     Ui::TemplateClip_UI dia_ui;
1958     dia_ui.setupUi(dia);
1959     for (int i = 0; i < templateFiles.size(); ++i)
1960         dia_ui.template_list->comboBox()->addItem(templateFiles.at(i), path + templateFiles.at(i));
1961
1962     if (!templateFiles.isEmpty())
1963         dia_ui.buttonBox->button(QDialogButtonBox::Ok)->setFocus();
1964     dia_ui.template_list->fileDialog()->setFilter("application/x-kdenlivetitle");
1965     //warning: setting base directory doesn't work??
1966     KUrl startDir(path);
1967     dia_ui.template_list->fileDialog()->setUrl(startDir);
1968     dia_ui.text_box->setHidden(true);
1969     if (dia->exec() == QDialog::Accepted) {
1970         QString textTemplate = dia_ui.template_list->comboBox()->itemData(dia_ui.template_list->comboBox()->currentIndex()).toString();
1971         if (textTemplate.isEmpty()) textTemplate = dia_ui.template_list->comboBox()->currentText();
1972         // Create a cloned template clip
1973         m_doc->slotCreateTextTemplateClip(groupInfo.at(0), groupInfo.at(1), KUrl(textTemplate));
1974     }
1975     delete dia;
1976 }
1977
1978 QStringList ProjectList::getGroup() const
1979 {
1980     QStringList result;
1981     QTreeWidgetItem *item = m_listView->currentItem();
1982     while (item && item->type() != ProjectFoldeType)
1983         item = item->parent();
1984
1985     if (item) {
1986         FolderProjectItem *folder = static_cast <FolderProjectItem *>(item);
1987         result << folder->groupName() << folder->clipId();
1988     } else {
1989         result << QString() << QString();
1990     }
1991     return result;
1992 }
1993
1994 void ProjectList::setDocument(KdenliveDoc *doc)
1995 {
1996     m_listView->blockSignals(true);
1997     m_abortAllJobs = true;
1998     for (int i = 0; i < m_jobList.count(); ++i) {
1999         m_jobList.at(i)->setStatus(JobAborted);
2000     }
2001     m_closing = true;
2002     m_jobThreads.waitForFinished();
2003     m_jobThreads.clearFutures();
2004     m_thumbnailQueue.clear();
2005     m_listView->clear();
2006     
2007     m_listView->setSortingEnabled(false);
2008     emit clipSelected(NULL);
2009     m_refreshed = false;
2010     m_allClipsProcessed = false;
2011     m_fps = doc->fps();
2012     m_timecode = doc->timecode();
2013     m_commandStack = doc->commandStack();
2014     m_doc = doc;
2015     m_abortAllJobs = false;
2016     m_closing = false;
2017
2018     QMap <QString, QString> flist = doc->clipManager()->documentFolderList();
2019     QStringList openedFolders = doc->getExpandedFolders();
2020     QMapIterator<QString, QString> f(flist);
2021     while (f.hasNext()) {
2022         f.next();
2023         FolderProjectItem *folder = new FolderProjectItem(m_listView, QStringList() << f.value(), f.key());
2024         folder->setExpanded(openedFolders.contains(f.key()));
2025     }
2026
2027     QList <DocClipBase*> list = doc->clipManager()->documentClipList();
2028     if (list.isEmpty()) {
2029         // blank document
2030         m_refreshed = true;
2031         m_allClipsProcessed = true;
2032     }
2033     for (int i = 0; i < list.count(); ++i)
2034         slotAddClip(list.at(i), false);
2035
2036     m_listView->blockSignals(false);
2037     connect(m_doc->clipManager(), SIGNAL(reloadClip(QString)), this, SLOT(slotReloadClip(QString)));
2038     connect(m_doc->clipManager(), SIGNAL(modifiedClip(QString)), this, SLOT(slotModifiedClip(QString)));
2039     connect(m_doc->clipManager(), SIGNAL(missingClip(QString)), this, SLOT(slotMissingClip(QString)));
2040     connect(m_doc->clipManager(), SIGNAL(availableClip(QString)), this, SLOT(slotAvailableClip(QString)));
2041     connect(m_doc->clipManager(), SIGNAL(checkAllClips(bool,bool,QStringList)), this, SLOT(updateAllClips(bool,bool,QStringList)));
2042     connect(m_doc->clipManager(), SIGNAL(thumbReady(QString,int,QImage)), this, SLOT(slotSetThumbnail(QString,int,QImage)));
2043 }
2044
2045 void ProjectList::slotSetThumbnail(const QString &id, int framePos, QImage img)
2046 {
2047     QString fullid = id + '#' + QString::number(framePos);
2048     ProjectItem *pItem = NULL;
2049     QTreeWidgetItem *item = getAnyItemById(fullid);
2050     if (item && item->parent()) pItem = static_cast <ProjectItem *>(item->parent());
2051     if (!item && framePos == 0) pItem = getItemById(id);
2052     if (!item && !pItem) return;
2053     if (item) {
2054         if (item->type() == ProjectClipType) static_cast<ProjectItem*>(item)->setPixmap(QPixmap::fromImage(img));
2055         else item->setData(0, Qt::DecorationRole, QPixmap::fromImage(img));
2056     }
2057     else if (pItem) pItem->setPixmap(QPixmap::fromImage(img));
2058     if (pItem) {
2059         QString hash = pItem->getClipHash();
2060         if (!hash.isEmpty()) m_doc->cacheImage(hash + '#' + QString::number(framePos), img);
2061     }
2062 }
2063
2064 QList <DocClipBase*> ProjectList::documentClipList() const
2065 {
2066     if (m_doc == NULL)
2067         return QList <DocClipBase*> ();
2068
2069     return m_doc->clipManager()->documentClipList();
2070 }
2071
2072 QDomElement ProjectList::producersList()
2073 {
2074     QDomDocument doc;
2075     QDomElement prods = doc.createElement("producerlist");
2076     doc.appendChild(prods);
2077     QTreeWidgetItemIterator it(m_listView);
2078     while (*it) {
2079         if ((*it)->type() != ProjectClipType) {
2080             // subitem
2081             ++it;
2082             continue;
2083         }
2084         prods.appendChild(doc.importNode(((ProjectItem *)(*it))->toXml(), true));
2085         ++it;
2086     }
2087     return prods;
2088 }
2089
2090 void ProjectList::slotCheckForEmptyQueue()
2091 {
2092     if (m_render->processingItems() == 0 && m_thumbnailQueue.isEmpty()) {
2093         if (!m_refreshed && m_allClipsProcessed) {
2094             m_refreshed = true;
2095             m_listView->setEnabled(true);
2096             slotClipSelected();
2097             QTimer::singleShot(500, this, SIGNAL(loadingIsOver()));
2098             emit displayMessage(QString(), -1);
2099         }
2100         updateButtons();
2101     } else if (!m_refreshed) {
2102         QTimer::singleShot(300, this, SLOT(slotCheckForEmptyQueue()));
2103     }
2104 }
2105
2106
2107 void ProjectList::requestClipThumbnail(const QString &id)
2108 {
2109     if (!m_thumbnailQueue.contains(id)) m_thumbnailQueue.append(id);
2110     slotProcessNextThumbnail();
2111 }
2112
2113 void ProjectList::resetThumbsProducer(DocClipBase *clip)
2114 {
2115     if (!clip) return;
2116     clip->clearThumbProducer();
2117     QString id = clip->getId();
2118     m_thumbnailQueue.removeAll(id);
2119 }
2120
2121 void ProjectList::slotProcessNextThumbnail()
2122 {
2123     if (m_render->processingItems() > 0) {
2124         return;
2125     }
2126     if (m_thumbnailQueue.isEmpty()) {
2127         slotCheckForEmptyQueue();
2128         return;
2129     }
2130     int max = m_doc->clipManager()->clipsCount();
2131     emit displayMessage(i18n("Loading thumbnails"), (int)(100 *(max - m_thumbnailQueue.count()) / max));
2132     slotRefreshClipThumbnail(m_thumbnailQueue.takeFirst(), false);
2133 }
2134
2135 void ProjectList::slotRefreshClipThumbnail(const QString &clipId, bool update)
2136 {
2137     QTreeWidgetItem *item = getAnyItemById(clipId);
2138     if (item)
2139         slotRefreshClipThumbnail(item, update);
2140     else {
2141         slotProcessNextThumbnail();
2142     }
2143 }
2144
2145 void ProjectList::slotRefreshClipThumbnail(QTreeWidgetItem *it, bool update)
2146 {
2147     if (it == NULL) return;
2148     ProjectItem *item = NULL;
2149     bool isSubItem = false;
2150     int frame;
2151     if (it->type() == ProjectFoldeType) return;
2152     if (it->type() == ProjectSubclipType) {
2153         item = static_cast <ProjectItem *>(it->parent());
2154         frame = static_cast <SubProjectItem *>(it)->zone().x();
2155         isSubItem = true;
2156     } else {
2157         item = static_cast <ProjectItem *>(it);
2158         frame = item->referencedClip()->getClipThumbFrame();
2159     }
2160
2161     if (item) {
2162         DocClipBase *clip = item->referencedClip();
2163         if (!clip) {
2164             slotProcessNextThumbnail();
2165             return;
2166         }
2167         QImage img;
2168         int height = m_listView->iconSize().height();
2169         int swidth = (int)(height  * m_render->frameRenderWidth() / m_render->renderHeight()+ 0.5);
2170         int dwidth = (int)(height  * m_render->dar() + 0.5);
2171         if (clip->clipType() == Image) {
2172             img = KThumb::getFrame(item->referencedClip()->getProducer(), 0, swidth, dwidth, height);
2173         }
2174         else if (clip->clipType() != Audio) {
2175             img = item->referencedClip()->extractImage(frame, dwidth, height);
2176         }
2177         if (!img.isNull()) {
2178             monitorItemEditing(false);
2179             QPixmap pix = roundedPixmap(img);
2180             processThumbOverlays(item, pix);
2181             if (isSubItem) it->setData(0, Qt::DecorationRole, pix);
2182             else item->setPixmap(pix);
2183             monitorItemEditing(true);
2184             
2185             QString hash = item->getClipHash();
2186             if (!hash.isEmpty() && !img.isNull()) {
2187                 if (!isSubItem)
2188                     m_doc->cacheImage(hash, img);
2189                 else
2190                     m_doc->cacheImage(hash + '#' + QString::number(frame), img);
2191             }
2192         }
2193         if (update)
2194             emit projectModified();
2195         slotProcessNextThumbnail();
2196     }
2197 }
2198
2199 void ProjectList::extractMetadata(DocClipBase *clip)
2200 {
2201     ClipType t = clip->clipType();
2202     if (t != AV && t != Video) {
2203         // Currently, we only use exiftool on video files
2204         return;
2205     }
2206     QMap <QString, QString> props = clip->properties();
2207     if (KdenliveSettings::use_exiftool() && !props.contains("exiftool")) {
2208         QMap <QString, QString> meta;
2209         QString url = clip->fileURL().path();
2210         //Check for Canon THM file
2211         url = url.section('.', 0, -2) + ".THM";
2212         if (QFile::exists(url)) {
2213             // Read the exif metadata embeded in the THM file
2214             QProcess p;
2215             QStringList args;
2216             args << "-g" << "-args" << url;
2217             p.start("exiftool", args);
2218             p.waitForFinished();
2219             QString res = p.readAllStandardOutput();
2220             QStringList list = res.split("\n");
2221             foreach(QString tagline, list) {
2222                 if (tagline.startsWith("-File") || tagline.startsWith("-ExifTool")) continue;
2223                 QString tag = tagline.section(':', 1).simplified();
2224                 if (tag.startsWith("ImageWidth") || tag.startsWith("ImageHeight")) continue;
2225                 if (!tag.section('=', 0, 0).isEmpty() && !tag.section('=', 1).simplified().isEmpty())
2226                     meta.insert(tag.section('=', 0, 0), tag.section('=', 1).simplified());
2227             }
2228         } else {
2229             QString codecid = props.value("videocodecid").simplified();
2230             if (codecid == "h264") {
2231                 QProcess p;
2232                 QStringList args;
2233                 args << "-g" << "-args" << clip->fileURL().encodedPathAndQuery();
2234                 p.start("exiftool", args);
2235                 p.waitForFinished();
2236                 QString res = p.readAllStandardOutput();
2237                 QStringList list = res.split("\n");
2238                 foreach(QString tagline, list) {
2239                     if (!tagline.startsWith("-H264")) continue;
2240                     QString tag = tagline.section(':', 1);
2241                     if (tag.startsWith("ImageWidth") || tag.startsWith("ImageHeight")) continue;
2242                     meta.insert(tag.section('=', 0, 0), tag.section('=', 1));
2243                 }
2244             }
2245         }
2246         clip->setProperty("exiftool", "1");
2247         if (!meta.isEmpty()) {
2248             clip->setMetadata(meta, "ExifTool");
2249             //checkCamcorderFilters(clip, meta);
2250         }
2251     }
2252     if (KdenliveSettings::use_magicLantern() && !props.contains("magiclantern")) {
2253         QMap <QString, QString> meta;
2254         QString url = clip->fileURL().path();
2255         url = url.section('.', 0, -2) + ".LOG";
2256         if (QFile::exists(url)) {
2257             QFile file(url);
2258             if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
2259                 while (!file.atEnd()) {
2260                     QString line = file.readLine().simplified();
2261                     if (line.startsWith('#') || line.isEmpty() || !line.contains(':')) continue;
2262                     if (line.startsWith("CSV data")) break;
2263                     meta.insert(line.section(':', 0, 0).simplified(), line.section(':', 1).simplified());
2264                 }
2265             }
2266         }
2267
2268         if (!meta.isEmpty())
2269             clip->setMetadata(meta, "Magic Lantern");
2270         clip->setProperty("magiclantern", "1");
2271     }
2272 }
2273
2274
2275 void ProjectList::slotReplyGetFileProperties(const QString &clipId, Mlt::Producer *producer, const stringMap &properties, const stringMap &metadata, bool replace)
2276 {
2277     QMutexLocker lock(&m_processMutex);
2278     QString toReload;
2279     ProjectItem *item = getItemById(clipId);
2280     if (item && producer) {
2281         monitorItemEditing(false);
2282         DocClipBase *clip = item->referencedClip();
2283         if (producer->is_valid()) {
2284             if (clip->isPlaceHolder()) {
2285                 clip->setValid();
2286                 toReload = clipId;
2287             }
2288             item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsDropEnabled);
2289         }
2290         item->setProperties(properties, metadata);
2291         clip->setProducer(producer, replace);
2292         extractMetadata(clip);
2293         m_render->processingDone(clipId);
2294
2295         // Proxy stuff
2296         QString size = properties.value("frame_size");
2297         if (!useProxy() && clip->getProperty("proxy").isEmpty()) {
2298             item->setConditionalJobStatus(NoJob, PROXYJOB);
2299             discardJobs(clipId, PROXYJOB);
2300         }
2301         if (useProxy() && generateProxy() && clip->getProperty("proxy") == "-") {
2302             item->setConditionalJobStatus(NoJob, PROXYJOB);
2303             discardJobs(clipId, PROXYJOB);
2304         }
2305         else if (useProxy() && !item->hasProxy() && !hasPendingJob(item, PROXYJOB)) {
2306             // proxy video and image clips
2307             int maxSize;
2308             ClipType t = item->clipType();
2309             if (t == Image) maxSize = m_doc->getDocumentProperty("proxyimageminsize").toInt();
2310             else maxSize = m_doc->getDocumentProperty("proxyminsize").toInt();
2311             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)) {
2312                 if (clip->getProperty("proxy").isEmpty()) {
2313                     KUrl proxyPath = m_doc->projectFolder();
2314                     proxyPath.addPath("proxy/");
2315                     proxyPath.addPath(clip->getClipHash() + '.' + (t == Image ? "png" : m_doc->getDocumentProperty("proxyextension")));
2316                     QMap <QString, QString> newProps;
2317                     // insert required duration for proxy
2318                     if (t != Image) newProps.insert("proxy_out", clip->producerProperty("out"));
2319                     newProps.insert("proxy", proxyPath.path());
2320                     QMap <QString, QString> oldProps = clip->properties();
2321                     oldProps.insert("proxy", QString());
2322                     EditClipCommand *command = new EditClipCommand(this, clipId, oldProps, newProps, true);
2323                     m_doc->commandStack()->push(command);
2324                 }
2325             }
2326         }
2327
2328         if (!replace && m_allClipsProcessed && !item->hasPixmap()) {
2329             getCachedThumbnail(item);
2330         }
2331         if (!toReload.isEmpty())
2332             item->slotSetToolTip();
2333     } else {
2334         kDebug() << "////////  COULD NOT FIND CLIP TO UPDATE PRPS...";
2335         m_render->processingDone(clipId);
2336     }
2337     int queue = m_render->processingItems();
2338     if (queue == 0) {
2339         monitorItemEditing(true);
2340         if (item && m_thumbnailQueue.isEmpty()) {
2341             if (!item->hasProxy() || m_render->activeClipId() == item->clipId())
2342                 m_listView->setCurrentItem(item);
2343             bool updatedProfile = false;
2344             if (item->parent()) {
2345                 if (item->parent()->type() == ProjectFoldeType)
2346                     static_cast <FolderProjectItem *>(item->parent())->switchIcon();
2347             } else if (KdenliveSettings::checkfirstprojectclip() &&  m_listView->topLevelItemCount() == 1 && m_refreshed && m_allClipsProcessed) {
2348                 // this is the first clip loaded in project, check if we want to adjust project settings to the clip
2349                 updatedProfile = adjustProjectProfileToItem(item);
2350                 if (updatedProfile == false) {
2351                     emit clipSelected(item->referencedClip());
2352                 }
2353             }
2354             if (updatedProfile == false) {
2355                 //emit clipSelected(item->referencedClip());
2356             }
2357         } else {
2358             int max = m_doc->clipManager()->clipsCount();
2359             if (max > 0) emit displayMessage(i18n("Loading clips"), (int)(100 *(max - queue) / max));
2360         }
2361         if (m_allClipsProcessed) emit processNextThumbnail();
2362     }
2363     if (!item) {
2364         // no item for producer, delete it
2365         delete producer;
2366         return;
2367     }
2368     if (replace) toReload = clipId;
2369     if (!toReload.isEmpty()) {
2370         emit clipNeedsReload(toReload);
2371     }
2372 }
2373
2374 bool ProjectList::adjustProjectProfileToItem(ProjectItem *item)
2375 {
2376     if (item == NULL) {
2377         if (m_listView->currentItem() && m_listView->currentItem()->type() != ProjectFoldeType)
2378             item = static_cast <ProjectItem*>(m_listView->currentItem());
2379     }
2380     if (item == NULL || item->referencedClip() == NULL) {
2381         KMessageBox::information(kapp->activeWindow(), i18n("Cannot find profile from current clip"));
2382         return false;
2383     }
2384     bool profileUpdated = false;
2385     QString size = item->referencedClip()->getProperty("frame_size");
2386     int width = size.section('x', 0, 0).toInt();
2387     int height = size.section('x', -1).toInt();
2388     // Fix some avchd clips tht report a wrong size (1920x1088)
2389     if (height == 1088) height = 1080;
2390     double fps = item->referencedClip()->getProperty("fps").toDouble();
2391     double par = item->referencedClip()->getProperty("aspect_ratio").toDouble();
2392     if (item->clipType() == Image || item->clipType() == AV || item->clipType() == Video) {
2393         if (ProfilesDialog::matchProfile(width, height, fps, par, item->clipType() == Image, m_doc->mltProfile()) == false) {
2394             // get a list of compatible profiles
2395             QMap <QString, QString> suggestedProfiles = ProfilesDialog::getProfilesFromProperties(width, height, fps, par, item->clipType() == Image);
2396             if (!suggestedProfiles.isEmpty()) {
2397                 KDialog *dialog = new KDialog(this);
2398                 dialog->setCaption(i18n("Change project profile"));
2399                 dialog->setButtons(KDialog::Ok | KDialog::Cancel);
2400
2401                 QWidget container;
2402                 QVBoxLayout *l = new QVBoxLayout;
2403                 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));
2404                 l->addWidget(label);
2405                 QListWidget *list = new QListWidget;
2406                 list->setAlternatingRowColors(true);
2407                 QMapIterator<QString, QString> i(suggestedProfiles);
2408                 while (i.hasNext()) {
2409                     i.next();
2410                     QListWidgetItem *item = new QListWidgetItem(i.value(), list);
2411                     item->setData(Qt::UserRole, i.key());
2412                     item->setToolTip(i.key());
2413                 }
2414                 list->setCurrentRow(0);
2415                 l->addWidget(list);
2416                 container.setLayout(l);
2417                 dialog->setButtonText(KDialog::Ok, i18n("Update profile"));
2418                 dialog->setMainWidget(&container);
2419                 if (dialog->exec() == QDialog::Accepted) {
2420                     //Change project profile
2421                     profileUpdated = true;
2422                     if (list->currentItem())
2423                         emit updateProfile(list->currentItem()->data(Qt::UserRole).toString());
2424                 }
2425                 delete list;
2426                 delete label;
2427             } else if (fps > 0) {
2428                 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));
2429             }
2430         }
2431     }
2432     return profileUpdated;
2433 }
2434
2435 QString ProjectList::getDocumentProperty(const QString &key) const
2436 {
2437     return m_doc->getDocumentProperty(key);
2438 }
2439
2440 bool ProjectList::useProxy() const
2441 {
2442     return m_doc->getDocumentProperty("enableproxy").toInt();
2443 }
2444
2445 bool ProjectList::generateProxy() const
2446 {
2447     return m_doc->getDocumentProperty("generateproxy").toInt();
2448 }
2449
2450 bool ProjectList::generateImageProxy() const
2451 {
2452     return m_doc->getDocumentProperty("generateimageproxy").toInt();
2453 }
2454
2455 void ProjectList::slotReplyGetImage(const QString &clipId, const QImage &img)
2456 {
2457     ProjectItem *item = getItemById(clipId);
2458     if (item && !img.isNull()) {
2459         QPixmap pix = roundedPixmap(img);
2460         processThumbOverlays(item, pix);
2461         monitorItemEditing(false);
2462         item->setPixmap(pix);
2463         monitorItemEditing(true);
2464         QString hash = item->getClipHash();
2465         if (!hash.isEmpty()) m_doc->cacheImage(hash, img);
2466     }
2467 }
2468
2469 void ProjectList::slotReplyGetImage(const QString &clipId, const QString &name, int width, int height)
2470 {
2471     // For clips that have a generic icon (like audio clips...)
2472     ProjectItem *item = getItemById(clipId);
2473     QPixmap pix =  KIcon(name).pixmap(QSize(width, height));
2474     if (item && !pix.isNull()) {
2475         monitorItemEditing(false);
2476         item->setData(0, Qt::DecorationRole, pix);
2477         monitorItemEditing(true);
2478     }
2479 }
2480
2481 QTreeWidgetItem *ProjectList::getAnyItemById(const QString &id)
2482 {
2483     QTreeWidgetItemIterator it(m_listView);
2484     QString lookId = id;
2485     if (id.contains('#'))
2486         lookId = id.section('#', 0, 0);
2487
2488     ProjectItem *result = NULL;
2489     while (*it) {
2490         if ((*it)->type() != ProjectClipType) {
2491             // subitem
2492             ++it;
2493             continue;
2494         }
2495         ProjectItem *item = static_cast<ProjectItem *>(*it);
2496         if (item->clipId() == lookId) {
2497             result = item;
2498             break;
2499         }
2500         ++it;
2501     }
2502     if (result == NULL || !id.contains('#')) {
2503         return result;
2504     } else {
2505         for (int i = 0; i < result->childCount(); ++i) {
2506             SubProjectItem *sub = static_cast <SubProjectItem *>(result->child(i));
2507             if (sub && sub->zone().x() == id.section('#', 1, 1).toInt())
2508                 return sub;
2509         }
2510     }
2511
2512     return NULL;
2513 }
2514
2515
2516 ProjectItem *ProjectList::getItemById(const QString &id)
2517 {
2518     ProjectItem *item;
2519     QTreeWidgetItemIterator it(m_listView);
2520     while (*it) {
2521         if ((*it)->type() != ProjectClipType) {
2522             // subitem or folder
2523             ++it;
2524             continue;
2525         }
2526         item = static_cast<ProjectItem *>(*it);
2527         if (item->clipId() == id)
2528             return item;
2529         ++it;
2530     }
2531     return NULL;
2532 }
2533
2534 FolderProjectItem *ProjectList::getFolderItemByName(const QString &name)
2535 {
2536     FolderProjectItem *item = NULL;
2537     QList <QTreeWidgetItem *> hits = m_listView->findItems(name, Qt::MatchExactly, 0);
2538     for (int i = 0; i < hits.count(); ++i) {
2539         if (hits.at(i)->type() == ProjectFoldeType) {
2540             item = static_cast<FolderProjectItem *>(hits.at(i));
2541             break;
2542         }
2543     }
2544     return item;
2545 }
2546
2547 FolderProjectItem *ProjectList::getFolderItemById(const QString &id)
2548 {
2549     FolderProjectItem *item;
2550     QTreeWidgetItemIterator it(m_listView);
2551     while (*it) {
2552         if ((*it)->type() == ProjectFoldeType) {
2553             item = static_cast<FolderProjectItem *>(*it);
2554             if (item->clipId() == id)
2555                 return item;
2556         }
2557         ++it;
2558     }
2559     return NULL;
2560 }
2561
2562 void ProjectList::slotSelectClip(const QString &ix)
2563 {
2564     ProjectItem *clip = getItemById(ix);
2565     if (clip) {
2566         m_listView->setCurrentItem(clip);
2567         m_listView->scrollToItem(clip);
2568         m_editButton->defaultAction()->setEnabled(true);
2569         m_deleteButton->defaultAction()->setEnabled(true);
2570         m_reloadAction->setEnabled(true);
2571         m_extractAudioAction->setEnabled(true);
2572         m_transcodeAction->setEnabled(true);
2573         m_clipsActionsMenu->setEnabled(true);
2574         if (clip->clipType() == Image && !KdenliveSettings::defaultimageapp().isEmpty()) {
2575             m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
2576             m_openAction->setEnabled(true);
2577         } else if (clip->clipType() == Audio && !KdenliveSettings::defaultaudioapp().isEmpty()) {
2578             m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
2579             m_openAction->setEnabled(true);
2580         } else {
2581             m_openAction->setEnabled(false);
2582         }
2583     }
2584 }
2585
2586 QString ProjectList::currentClipUrl() const
2587 {
2588     ProjectItem *item;
2589     if (!m_listView->currentItem() || m_listView->currentItem()->type() == ProjectFoldeType) return QString();
2590     if (m_listView->currentItem()->type() == ProjectSubclipType) {
2591         // subitem
2592         item = static_cast <ProjectItem*>(m_listView->currentItem()->parent());
2593     } else {
2594         item = static_cast <ProjectItem*>(m_listView->currentItem());
2595     }
2596     if (item == NULL)
2597         return QString();
2598     return item->clipUrl().path();
2599 }
2600
2601 KUrl::List ProjectList::getConditionalUrls(const QString &condition) const
2602 {
2603     KUrl::List result;
2604     ProjectItem *item;
2605     QList<QTreeWidgetItem *> list = m_listView->selectedItems();
2606     for (int i = 0; i < list.count(); ++i) {
2607         if (list.at(i)->type() == ProjectFoldeType)
2608             continue;
2609         if (list.at(i)->type() == ProjectSubclipType) {
2610             // subitem
2611             item = static_cast <ProjectItem*>(list.at(i)->parent());
2612         } else {
2613             item = static_cast <ProjectItem*>(list.at(i));
2614         }
2615         if (item == NULL || item->type() == Color || item->type() == SlideShow || item->type() == Text)
2616             continue;
2617         DocClipBase *clip = item->referencedClip();
2618         if (!condition.isEmpty()) {
2619             if (condition.startsWith("vcodec") && !clip->hasVideoCodec(condition.section('=', 1, 1)))
2620                 continue;
2621             else if (condition.startsWith("acodec") && !clip->hasAudioCodec(condition.section('=', 1, 1)))
2622                 continue;
2623         }
2624         result.append(item->clipUrl());
2625     }
2626     return result;
2627 }
2628
2629 QMap <QString, QString> ProjectList::getConditionalIds(const QString &condition) const
2630 {
2631     QMap <QString, QString> result;
2632     ProjectItem *item;
2633     QList<QTreeWidgetItem *> list = m_listView->selectedItems();
2634     for (int i = 0; i < list.count(); ++i) {
2635         if (list.at(i)->type() == ProjectFoldeType)
2636             continue;
2637         if (list.at(i)->type() == ProjectSubclipType) {
2638             // subitem
2639             item = static_cast <ProjectItem*>(list.at(i)->parent());
2640         } else {
2641             item = static_cast <ProjectItem*>(list.at(i));
2642         }
2643         if (item == NULL || item->type() == Color || item->type() == SlideShow || item->type() == Text)
2644             continue;
2645         DocClipBase *clip = item->referencedClip();
2646         if (!condition.isEmpty()) {
2647             if (condition.startsWith("vcodec") && !clip->hasVideoCodec(condition.section('=', 1, 1)))
2648                 continue;
2649             else if (condition.startsWith("acodec") && !clip->hasAudioCodec(condition.section('=', 1, 1)))
2650                 continue;
2651         }
2652         result.insert(item->clipId(), item->clipUrl().path());
2653     }
2654     return result;
2655 }
2656
2657 void ProjectList::regenerateTemplate(const QString &id)
2658 {
2659     ProjectItem *clip = getItemById(id);
2660     if (clip)
2661         regenerateTemplate(clip);
2662 }
2663
2664 void ProjectList::regenerateTemplate(ProjectItem *clip)
2665 {
2666     //TODO: remove this unused method, only force_reload is necessary
2667     clip->referencedClip()->getProducer()->set("force_reload", 1);
2668 }
2669
2670 QDomDocument ProjectList::generateTemplateXml(QString path, const QString &replaceString)
2671 {
2672     QDomDocument doc;
2673     QFile file(path);
2674     if (!file.open(QIODevice::ReadOnly)) {
2675         kWarning() << "ERROR, CANNOT READ: " << path;
2676         return doc;
2677     }
2678     if (!doc.setContent(&file)) {
2679         kWarning() << "ERROR, CANNOT READ: " << path;
2680         file.close();
2681         return doc;
2682     }
2683     file.close();
2684     QDomNodeList texts = doc.elementsByTagName("content");
2685     for (int i = 0; i < texts.count(); ++i) {
2686         QString data = texts.item(i).firstChild().nodeValue();
2687         data.replace("%s", replaceString);
2688         texts.item(i).firstChild().setNodeValue(data);
2689     }
2690     return doc;
2691 }
2692
2693
2694 void ProjectList::slotAddClipCut(const QString &id, int in, int out)
2695 {
2696     ProjectItem *clip = getItemById(id);
2697     if (clip == NULL || clip->referencedClip()->hasCutZone(QPoint(in, out)))
2698         return;
2699     AddClipCutCommand *command = new AddClipCutCommand(this, id, in, out, QString(), true, false);
2700     m_commandStack->push(command);
2701 }
2702
2703 void ProjectList::addClipCut(const QString &id, int in, int out, const QString desc, bool newItem)
2704 {
2705     ProjectItem *clip = getItemById(id);
2706     if (clip) {
2707         DocClipBase *base = clip->referencedClip();
2708         base->addCutZone(in, out);
2709         monitorItemEditing(false);
2710         SubProjectItem *sub = new SubProjectItem(m_render->dar(), clip, in, out, desc);
2711         if (newItem && desc.isEmpty() && !m_listView->isColumnHidden(1)) {
2712             if (!clip->isExpanded())
2713                 clip->setExpanded(true);
2714             m_listView->scrollToItem(sub);
2715             m_listView->editItem(sub, 1);
2716         }
2717         m_doc->clipManager()->slotRequestThumbs(QString('#' + id), QList <int>() << in);
2718         monitorItemEditing(true);
2719     }
2720     emit projectModified();
2721 }
2722
2723 void ProjectList::removeClipCut(const QString &id, int in, int out)
2724 {
2725     ProjectItem *clip = getItemById(id);
2726     if (clip) {
2727         DocClipBase *base = clip->referencedClip();
2728         base->removeCutZone(in, out);
2729         SubProjectItem *sub = getSubItem(clip, QPoint(in, out));
2730         if (sub) {
2731             monitorItemEditing(false);
2732             delete sub;
2733             monitorItemEditing(true);
2734         }
2735     }
2736     emit projectModified();
2737 }
2738
2739 SubProjectItem *ProjectList::getSubItem(ProjectItem *clip, const QPoint &zone)
2740 {
2741     SubProjectItem *sub = NULL;
2742     if (clip) {
2743         for (int i = 0; i < clip->childCount(); ++i) {
2744             QTreeWidgetItem *it = clip->child(i);
2745             if (it->type() == ProjectSubclipType) {
2746                 sub = static_cast <SubProjectItem*>(it);
2747                 if (sub->zone() == zone)
2748                     break;
2749                 else
2750                     sub = NULL;
2751             }
2752         }
2753     }
2754     return sub;
2755 }
2756
2757 void ProjectList::slotUpdateClipCut(QPoint p)
2758 {
2759     if (!m_listView->currentItem() || m_listView->currentItem()->type() != ProjectSubclipType)
2760         return;
2761     SubProjectItem *sub = static_cast <SubProjectItem*>(m_listView->currentItem());
2762     ProjectItem *item = static_cast <ProjectItem *>(sub->parent());
2763     EditClipCutCommand *command = new EditClipCutCommand(this, item->clipId(), sub->zone(), p, sub->text(1), sub->text(1), true);
2764     m_commandStack->push(command);
2765 }
2766
2767 void ProjectList::doUpdateClipCut(const QString &id, const QPoint &oldzone, const QPoint &zone, const QString &comment)
2768 {
2769     ProjectItem *clip = getItemById(id);
2770     SubProjectItem *sub = getSubItem(clip, oldzone);
2771     if (sub == NULL || clip == NULL)
2772         return;
2773     DocClipBase *base = clip->referencedClip();
2774     base->updateCutZone(oldzone.x(), oldzone.y(), zone.x(), zone.y(), comment);
2775     monitorItemEditing(false);
2776     sub->setZone(zone);
2777     sub->setDescription(comment);
2778     monitorItemEditing(true);
2779     emit projectModified();
2780 }
2781
2782 void ProjectList::slotForceProcessing(const QString &id)
2783 {
2784     m_render->forceProcessing(id);
2785 }
2786
2787 void ProjectList::slotAddOrUpdateSequence(const QString &frameName)
2788 {
2789     QString fileName = KUrl(frameName).fileName().section('_', 0, -2);
2790     QStringList list;
2791     QString pattern = SlideshowClip::selectedPath(frameName, false, QString(), &list);
2792     int count = list.count();
2793     if (count > 1) {
2794         const QList <DocClipBase *> existing = m_doc->clipManager()->getClipByResource(pattern);
2795         if (!existing.isEmpty()) {
2796             // Sequence already exists, update
2797             QString id = existing.at(0)->getId();
2798             //ProjectItem *item = getItemById(id);
2799             QMap <QString, QString> oldprops;
2800             QMap <QString, QString> newprops;
2801             int ttl = existing.at(0)->getProperty("ttl").toInt();
2802             oldprops["out"] = existing.at(0)->getProperty("out");
2803             newprops["out"] = QString::number(ttl * count - 1);
2804             slotUpdateClipProperties(id, newprops);
2805             EditClipCommand *command = new EditClipCommand(this, id, oldprops, newprops, false);
2806             m_commandStack->push(command);
2807         } else {
2808             // Create sequence
2809             QStringList groupInfo = getGroup();
2810             QMap <QString, QString> properties;
2811             properties.insert("name", fileName);
2812             properties.insert("resource", pattern);
2813             properties.insert("in", "0");
2814             QString duration = m_timecode.reformatSeparators(KdenliveSettings::sequence_duration());
2815             properties.insert("out", QString::number(m_doc->getFramePos(duration) * count));
2816             properties.insert("ttl", QString::number(m_doc->getFramePos(duration)));
2817             properties.insert("loop", QString::number(false));
2818             properties.insert("crop", QString::number(false));
2819             properties.insert("fade", QString::number(false));
2820             properties.insert("luma_duration", m_timecode.getTimecodeFromFrames(int(ceil(m_timecode.fps()))));
2821
2822             m_doc->slotCreateSlideshowClipFile(properties, groupInfo.at(0), groupInfo.at(1));
2823         }
2824     } else emit displayMessage(i18n("Sequence not found"), -2, ErrorMessage);
2825 }
2826
2827 QMap <QString, QString> ProjectList::getProxies()
2828 {
2829     QMap <QString, QString> list;
2830     ProjectItem *item;
2831     QTreeWidgetItemIterator it(m_listView);
2832     while (*it) {
2833         if ((*it)->type() != ProjectClipType) {
2834             ++it;
2835             continue;
2836         }
2837         item = static_cast<ProjectItem *>(*it);
2838         if (item && item->referencedClip() != NULL) {
2839             if (item->hasProxy()) {
2840                 QString proxy = item->referencedClip()->getProperty("proxy");
2841                 list.insert(proxy, item->clipUrl().path());
2842             }
2843         }
2844         ++it;
2845     }
2846     return list;
2847 }
2848
2849 void ProjectList::slotCreateProxy(const QString &id)
2850 {
2851     ProjectItem *item = getItemById(id);
2852     if (!item || hasPendingJob(item, PROXYJOB) || item->referencedClip()->isPlaceHolder()) return;
2853     QString path = item->referencedClip()->getProperty("proxy");
2854     if (path.isEmpty()) {
2855         slotUpdateJobStatus(item, PROXYJOB, JobCrashed, i18n("Failed to create proxy, empty path."));
2856         return;
2857     }
2858     
2859     if (QFileInfo(path).size() > 0) {
2860         // Proxy already created
2861         setJobStatus(item, PROXYJOB, JobDone);
2862         slotGotProxy(path);
2863         return;
2864     }
2865     QString sourcePath = item->clipUrl().path();
2866     if (item->clipType() == Playlist) {
2867         // Special case: playlists use the special 'consumer' producer to support resizing
2868         sourcePath.prepend("consumer:");
2869     }
2870     ProxyJob *job = new ProxyJob(item->clipType(), id, QStringList() << path << sourcePath << item->referencedClip()->producerProperty("_exif_orientation") << m_doc->getDocumentProperty("proxyparams").simplified() << QString::number(m_render->frameRenderWidth()) << QString::number(m_render->renderHeight()));
2871     if (job->isExclusive() && hasPendingJob(item, job->jobType)) {
2872         delete job;
2873         return;
2874     }
2875
2876     m_jobList.append(job);
2877     setJobStatus(item, job->jobType, JobWaiting, 0, job->statusMessage());
2878     slotCheckJobProcess();
2879 }
2880
2881 void ProjectList::slotCutClipJob(const QString &id, QPoint zone)
2882 {
2883     ProjectItem *item = getItemById(id);
2884     if (!item|| item->referencedClip()->isPlaceHolder()) return;
2885     QString source = item->clipUrl().path();
2886     QString ext = source.section('.', -1);
2887     QString dest = source.section('.', 0, -2) + '_' + QString::number(zone.x()) + '.' + ext;
2888     
2889     double clipFps = item->referencedClip()->getProperty("fps").toDouble();
2890     if (clipFps == 0) clipFps = m_fps;
2891     // if clip and project have different frame rate, adjust in and out
2892     int in = zone.x();
2893     int out = zone.y();
2894     in = GenTime(in, m_timecode.fps()).frames(clipFps);
2895     out = GenTime(out, m_timecode.fps()).frames(clipFps);
2896     int max = GenTime(item->clipMaxDuration(), m_timecode.fps()).frames(clipFps);
2897     int duration = out - in + 1;
2898     QString timeIn = Timecode::getStringTimecode(in, clipFps, true);
2899     QString timeOut = Timecode::getStringTimecode(duration, clipFps, true);
2900     
2901     QPointer<QDialog> d = new QDialog(this);
2902     Ui::CutJobDialog_UI ui;
2903     ui.setupUi(d);
2904     ui.extra_params->setVisible(false);
2905     ui.add_clip->setChecked(KdenliveSettings::add_new_clip());
2906     ui.file_url->fileDialog()->setOperationMode(KFileDialog::Saving);
2907     ui.extra_params->setMaximumHeight(QFontMetrics(font()).lineSpacing() * 5);
2908     ui.file_url->setUrl(KUrl(dest));
2909     ui.button_more->setIcon(KIcon("configure"));
2910     ui.extra_params->setPlainText("-acodec copy -vcodec copy");
2911     QString mess = i18n("Extracting %1 out of %2", timeOut, Timecode::getStringTimecode(max, clipFps, true));
2912     ui.info_label->setText(mess);
2913     if (d->exec() != QDialog::Accepted) {
2914         delete d;
2915         return;
2916     }
2917     dest = ui.file_url->url().path();
2918     bool acceptPath = dest != source;
2919     if (acceptPath && QFileInfo(dest).size() > 0) {
2920         // destination file olready exists, overwrite?
2921         acceptPath = false;
2922     }
2923     while (!acceptPath) {
2924         // Do not allow to save over original clip
2925         if (dest == source) ui.info_label->setText("<b>" + i18n("You cannot overwrite original clip.") + "</b><br>" + mess);
2926         else if (KMessageBox::questionYesNo(this, i18n("Overwrite file %1", dest)) == KMessageBox::Yes) break;
2927         if (d->exec() != QDialog::Accepted) {
2928             delete d;
2929             return;
2930         }
2931         dest = ui.file_url->url().path();
2932         acceptPath = dest != source;
2933         if (acceptPath && QFileInfo(dest).size() > 0) {
2934             acceptPath = false;
2935         }
2936     }
2937     QString extraParams = ui.extra_params->toPlainText().simplified();
2938     KdenliveSettings::setAdd_new_clip(ui.add_clip->isChecked());
2939     delete d;
2940
2941     QStringList jobParams;
2942     jobParams << dest << item->clipUrl().path() << timeIn << timeOut << QString::number(duration) << QString::number(KdenliveSettings::add_new_clip());
2943     if (!extraParams.isEmpty()) jobParams << extraParams;
2944     CutClipJob *job = new CutClipJob(item->clipType(), id, jobParams);
2945     if (job->isExclusive() && hasPendingJob(item, job->jobType)) {
2946         delete job;
2947         return;
2948     }
2949     m_jobList.append(job);
2950     setJobStatus(item, job->jobType, JobWaiting, 0, job->statusMessage());
2951
2952     slotCheckJobProcess();
2953 }
2954
2955 void ProjectList::slotTranscodeClipJob(const QString &condition, QString params, QString desc)
2956 {
2957     QStringList existingFiles;
2958     QMap <QString, QString> ids = getConditionalIds(condition);
2959     QMap<QString, QString>::const_iterator i = ids.constBegin();
2960     QStringList destinations;
2961     while (i != ids.constEnd()) {
2962         QString newFile = params.section(' ', -1).replace("%1", i.value());
2963         destinations << newFile;
2964         if (QFile::exists(newFile)) existingFiles << newFile;
2965         ++i;
2966     }
2967     if (!existingFiles.isEmpty()) {
2968         if (KMessageBox::warningContinueCancelList(this, i18n("The transcoding job will overwrite the following files:"), existingFiles) ==  KMessageBox::Cancel) return;
2969     }
2970     
2971     QDialog *d = new QDialog(this);
2972     Ui::CutJobDialog_UI ui;
2973     ui.setupUi(d);
2974     d->setWindowTitle(i18n("Transcoding"));
2975     ui.extra_params->setMaximumHeight(QFontMetrics(font()).lineSpacing() * 5);
2976     if (ids.count() == 1) {
2977         ui.file_url->setUrl(KUrl(destinations.first()));
2978     }
2979     else {
2980         ui.destination_label->setVisible(false);
2981         ui.file_url->setVisible(false);
2982     }
2983     ui.extra_params->setVisible(false);
2984     d->adjustSize();
2985     ui.button_more->setIcon(KIcon("configure"));
2986     ui.add_clip->setChecked(KdenliveSettings::add_new_clip());
2987     ui.extra_params->setPlainText(params.simplified().section(' ', 0, -2));
2988     QString mess = desc;
2989     mess.append(' ' + i18np("(%1 clip)", "(%1 clips)", ids.count()));
2990     ui.info_label->setText(mess);
2991     if (d->exec() != QDialog::Accepted) {
2992         delete d;
2993         return;
2994     }
2995     params = ui.extra_params->toPlainText().simplified();
2996     KdenliveSettings::setAdd_new_clip(ui.add_clip->isChecked());
2997     int index = 0;
2998     i = ids.constBegin();
2999     while (i != ids.constEnd()) {
3000         ProjectItem *item = getItemById(i.key());
3001         if (!item || !item->referencedClip()) continue;
3002         QString src = i.value();
3003         QString dest;
3004         if (ids.count() > 1) {
3005             dest = destinations.at(index);
3006             index++;
3007         }
3008         else dest = ui.file_url->url().path();
3009         QStringList jobParams;
3010         jobParams << dest << src << QString() << QString();
3011         double clipFps = item->referencedClip()->getProperty("fps").toDouble();
3012         if (clipFps == 0) clipFps = m_fps;
3013         int max = item->clipMaxDuration();
3014         QString duration = QString::number(max);
3015         jobParams << duration;
3016         jobParams << QString::number(KdenliveSettings::add_new_clip());
3017         jobParams << params;
3018         CutClipJob *job = new CutClipJob(item->clipType(), i.key(), jobParams);
3019         if (job->isExclusive() && hasPendingJob(item, job->jobType)) {
3020             delete job;
3021             continue;
3022         }
3023         m_jobList.append(job);
3024         setJobStatus(item, job->jobType, JobWaiting, 0, job->statusMessage());
3025         ++i;
3026     }
3027     delete d;
3028     slotCheckJobProcess();
3029     
3030 }
3031
3032 void ProjectList::slotCheckJobProcess()
3033 {        
3034     if (!m_jobThreads.futures().isEmpty()) {
3035         // Remove inactive threads
3036         QList <QFuture<void> > futures = m_jobThreads.futures();
3037         m_jobThreads.clearFutures();
3038         for (int i = 0; i < futures.count(); ++i)
3039             if (!futures.at(i).isFinished()) {
3040                 m_jobThreads.addFuture(futures.at(i));
3041             }
3042     }
3043     if (m_jobList.isEmpty()) return;
3044
3045     m_jobMutex.lock();
3046     int count = 0;
3047     for (int i = 0; i < m_jobList.count(); ++i) {
3048         if (m_jobList.at(i)->status() == JobWorking || m_jobList.at(i)->status() == JobWaiting)
3049             count ++;
3050         else {
3051             // remove finished jobs
3052             AbstractClipJob *job = m_jobList.takeAt(i);
3053             job->deleteLater();
3054             --i;
3055         }
3056     }
3057     emit jobCount(count);
3058     m_jobMutex.unlock();
3059     if (m_jobThreads.futures().isEmpty() || m_jobThreads.futures().count() < KdenliveSettings::proxythreads()) m_jobThreads.addFuture(QtConcurrent::run(this, &ProjectList::slotProcessJobs));
3060 }
3061
3062 void ProjectList::slotAbortProxy(const QString &id, const QString &path)
3063 {
3064     Q_UNUSED(path)
3065
3066     ProjectItem *item = getItemById(id);
3067     if (!item) return;
3068     if (!item->isProxyRunning()) slotGotProxy(item);
3069     item->setConditionalJobStatus(NoJob, PROXYJOB);
3070     discardJobs(id, PROXYJOB);
3071 }
3072
3073 void ProjectList::slotProcessJobs()
3074 {
3075     while (!m_jobList.isEmpty() && !m_abortAllJobs) {
3076         emit projectModified();
3077         AbstractClipJob *job = NULL;
3078         int count = 0;
3079         m_jobMutex.lock();
3080         for (int i = 0; i < m_jobList.count(); ++i) {
3081             if (m_jobList.at(i)->status() == JobWaiting) {
3082                 if (job == NULL) {
3083                     m_jobList.at(i)->setStatus(JobWorking);
3084                     job = m_jobList.at(i);
3085                 }
3086                 count++;
3087             }
3088             else if (m_jobList.at(i)->status() == JobWorking)
3089                 count ++;
3090         }
3091         // Set jobs count
3092         emit jobCount(count);
3093         m_jobMutex.unlock();
3094
3095         if (job == NULL) {
3096             break;
3097         }
3098         QString destination = job->destination();
3099         // Check if the clip is still here
3100         DocClipBase *currentClip = m_doc->clipManager()->getClipById(job->clipId());
3101         //ProjectItem *processingItem = getItemById(job->clipId());
3102         if (currentClip == NULL) {
3103             job->setStatus(JobDone);
3104             continue;
3105         }
3106         // Set clip status to started
3107         emit processLog(job->clipId(), 0, job->jobType, job->statusMessage());
3108
3109         // Make sure destination path is writable
3110         if (!destination.isEmpty()) {
3111             QFile file(destination);
3112             if (!file.open(QIODevice::WriteOnly)) {
3113                 emit updateJobStatus(job->clipId(), job->jobType, JobCrashed, i18n("Cannot write to path: %1", destination));
3114                 job->setStatus(JobCrashed);
3115                 continue;
3116             }
3117             file.close();
3118             QFile::remove(destination);
3119         }
3120         connect(job, SIGNAL(jobProgress(QString,int,int)), this, SIGNAL(processLog(QString,int,int)));
3121         connect(job, SIGNAL(cancelRunningJob(QString,stringMap)), this, SIGNAL(cancelRunningJob(QString,stringMap)));
3122
3123         if (job->jobType == MLTJOB) {
3124             MeltJob *jb = static_cast<MeltJob *> (job);
3125             jb->setProducer(currentClip->getProducer(), currentClip->fileURL());
3126             if (jb->isProjectFilter())
3127                 connect(job, SIGNAL(gotFilterJobResults(QString,int,int,stringMap,stringMap)), this, SLOT(slotGotFilterJobResults(QString,int,int,stringMap,stringMap)));
3128             else
3129                 connect(job, SIGNAL(gotFilterJobResults(QString,int,int,stringMap,stringMap)), this, SIGNAL(gotFilterJobResults(QString,int,int,stringMap,stringMap)));
3130         }
3131         job->startJob();
3132         if (job->status() == JobDone) {
3133             emit updateJobStatus(job->clipId(), job->jobType, JobDone);
3134             //TODO: replace with more generic clip replacement framework
3135             if (job->jobType == PROXYJOB) emit gotProxy(job->clipId());
3136             if (job->addClipToProject()) {
3137                 emit addClip(destination, QString(), QString());
3138             }
3139         } else if (job->status() == JobCrashed || job->status() == JobAborted) {
3140             emit updateJobStatus(job->clipId(), job->jobType, job->status(), job->errorMessage(), QString(), job->logDetails());
3141         }
3142     }
3143     // Thread finished, cleanup & update count
3144     QTimer::singleShot(200, this, SIGNAL(checkJobProcess()));
3145 }
3146
3147
3148 void ProjectList::updateProxyConfig()
3149 {
3150     ProjectItem *item;
3151     QTreeWidgetItemIterator it(m_listView);
3152     QUndoCommand *command = new QUndoCommand();
3153     command->setText(i18n("Update proxy settings"));
3154     QString proxydir = m_doc->projectFolder().path( KUrl::AddTrailingSlash) + "proxy/";
3155     while (*it) {
3156         if ((*it)->type() != ProjectClipType) {
3157             ++it;
3158             continue;
3159         }
3160         item = static_cast<ProjectItem *>(*it);
3161         if (item == NULL) {
3162             ++it;
3163             continue;
3164         }
3165         ClipType t = item->clipType();
3166         if ((t == Video || t == AV || t == Unknown) && item->referencedClip() != NULL) {
3167             if  (generateProxy() && useProxy() && !hasPendingJob(item, PROXYJOB)) {
3168                 DocClipBase *clip = item->referencedClip();
3169                 if (clip->getProperty("frame_size").section('x', 0, 0).toInt() > m_doc->getDocumentProperty("proxyminsize").toInt()) {
3170                     if (clip->getProperty("proxy").isEmpty()) {
3171                         // We need to insert empty proxy in old properties so that undo will work
3172                         QMap <QString, QString> oldProps;// = clip->properties();
3173                         oldProps.insert("proxy", QString());
3174                         QMap <QString, QString> newProps;
3175                         newProps.insert("proxy", proxydir + item->referencedClip()->getClipHash() + '.' + m_doc->getDocumentProperty("proxyextension"));
3176                         new EditClipCommand(this, clip->getId(), oldProps, newProps, true, command);
3177                     }
3178                 }
3179             }
3180             else if (item->hasProxy()) {
3181                 // remove proxy
3182                 QMap <QString, QString> newProps;
3183                 newProps.insert("proxy", QString());
3184                 // insert required duration for proxy
3185                 newProps.insert("proxy_out", item->referencedClip()->producerProperty("out"));
3186                 new EditClipCommand(this, item->clipId(), item->referencedClip()->currentProperties(newProps), newProps, true, command);
3187             }
3188         }
3189         else if (t == Image && item->referencedClip() != NULL) {
3190             if  (generateImageProxy() && useProxy()) {
3191                 DocClipBase *clip = item->referencedClip();
3192                 int maxImageSize = m_doc->getDocumentProperty("proxyimageminsize").toInt();
3193                 if (clip->getProperty("frame_size").section('x', 0, 0).toInt() > maxImageSize || clip->getProperty("frame_size").section('x', 1, 1).toInt() > maxImageSize) {
3194                     if (clip->getProperty("proxy").isEmpty()) {
3195                         // We need to insert empty proxy in old properties so that undo will work
3196                         QMap <QString, QString> oldProps = clip->properties();
3197                         oldProps.insert("proxy", QString());
3198                         QMap <QString, QString> newProps;
3199                         newProps.insert("proxy", proxydir + item->referencedClip()->getClipHash() + ".png");
3200                         new EditClipCommand(this, clip->getId(), oldProps, newProps, true, command);
3201                     }
3202                 }
3203             }
3204             else if (item->hasProxy()) {
3205                 // remove proxy
3206                 QMap <QString, QString> newProps;
3207                 newProps.insert("proxy", QString());
3208                 new EditClipCommand(this, item->clipId(), item->referencedClip()->properties(), newProps, true, command);
3209             }
3210         }
3211         ++it;
3212     }
3213     if (command->childCount() > 0) m_doc->commandStack()->push(command);
3214     else delete command;
3215 }
3216
3217 void ProjectList::slotProcessLog(const QString &id, int progress, int type, const QString &message)
3218 {
3219     ProjectItem *item = getItemById(id);
3220     setJobStatus(item, (JOBTYPE) type, JobWorking, progress, message);
3221 }
3222
3223 void ProjectList::slotProxyCurrentItem(bool doProxy, ProjectItem *itemToProxy)
3224 {
3225     QList<QTreeWidgetItem *> list;
3226     if (itemToProxy == NULL) list = m_listView->selectedItems();
3227     else list << itemToProxy;
3228
3229     // expand list (folders, subclips) to get real clips
3230     QTreeWidgetItem *listItem;
3231     QList<ProjectItem *> clipList;
3232     for (int i = 0; i < list.count(); ++i) {
3233         listItem = list.at(i);
3234         if (listItem->type() == ProjectFoldeType) {
3235             for (int j = 0; j < listItem->childCount(); j++) {
3236                 QTreeWidgetItem *sub = listItem->child(j);
3237                 if (sub->type() == ProjectClipType) {
3238                     ProjectItem *item = static_cast <ProjectItem*>(sub);
3239                     if (!clipList.contains(item)) clipList.append(item);
3240                 }
3241             }
3242         }
3243         else if (listItem->type() == ProjectSubclipType) {
3244             QTreeWidgetItem *sub = listItem->parent();
3245             ProjectItem *item = static_cast <ProjectItem*>(sub);
3246             if (!clipList.contains(item)) clipList.append(item);
3247         }
3248         else if (listItem->type() == ProjectClipType) {
3249             ProjectItem *item = static_cast <ProjectItem*>(listItem);
3250             if (!clipList.contains(item)) clipList.append(item);
3251         }
3252     }
3253     
3254     QUndoCommand *command = new QUndoCommand();
3255     if (doProxy) command->setText(i18np("Add proxy clip", "Add proxy clips", clipList.count()));
3256     else command->setText(i18np("Remove proxy clip", "Remove proxy clips", clipList.count()));
3257     
3258     // Make sure the proxy folder exists
3259     QString proxydir = m_doc->projectFolder().path( KUrl::AddTrailingSlash) + "proxy/";
3260     KStandardDirs::makeDir(proxydir);
3261
3262     QMap <QString, QString> newProps;
3263     QMap <QString, QString> oldProps;
3264     if (!doProxy) newProps.insert("proxy", "-");
3265     for (int i = 0; i < clipList.count(); ++i) {
3266         ProjectItem *item = clipList.at(i);
3267         ClipType t = item->clipType();
3268         if ((t == Video || t == AV || t == Unknown || t == Image || t == Playlist) && item->referencedClip()) {
3269             if ((doProxy && item->hasProxy()) || (!doProxy && !item->hasProxy() && item->referencedClip()->getProducer() != NULL)) continue;
3270             DocClipBase *clip = item->referencedClip();
3271             if (!clip || !clip->isClean() || m_render->isProcessing(item->clipId())) {
3272                 kDebug()<<"//// TRYING TO PROXY: "<<item->clipId()<<", but it is busy";
3273                 continue;
3274             }
3275
3276             //oldProps = clip->properties();
3277             if (doProxy) {
3278                 newProps.clear();
3279                 QString path = proxydir + clip->getClipHash() + '.' + (t == Image ? "png" : m_doc->getDocumentProperty("proxyextension"));
3280                 // insert required duration for proxy
3281                 newProps.insert("proxy_out", clip->producerProperty("out"));
3282                 newProps.insert("proxy", path);
3283                 // We need to insert empty proxy so that undo will work
3284                 //oldProps.insert("proxy", QString());
3285             }
3286             else if (item->referencedClip()->getProducer() == NULL) {
3287                 // Force clip reload
3288                 kDebug()<<"// CLIP HAD NULL PROD------------";
3289                 newProps.insert("resource", item->referencedClip()->getProperty("resource"));
3290             }
3291             // We need to insert empty proxy so that undo will work
3292             oldProps = clip->currentProperties(newProps);
3293             if (doProxy) oldProps.insert("proxy", "-");
3294             new EditClipCommand(this, item->clipId(), oldProps, newProps, true, command);
3295         }
3296     }
3297     if (command->childCount() > 0) {
3298         m_doc->commandStack()->push(command);
3299     }
3300     else delete command;
3301 }
3302
3303
3304 void ProjectList::slotDeleteProxy(const QString proxyPath)
3305 {
3306     if (proxyPath.isEmpty()) return;
3307     QUndoCommand *proxyCommand = new QUndoCommand();
3308     proxyCommand->setText(i18n("Remove Proxy"));
3309     QTreeWidgetItemIterator it(m_listView);
3310     ProjectItem *item;
3311     while (*it) {
3312         if ((*it)->type() == ProjectClipType) {
3313             item = static_cast <ProjectItem *>(*it);
3314             if (item->referencedClip()->getProperty("proxy") == proxyPath) {
3315                 QMap <QString, QString> props;
3316                 props.insert("proxy", QString());
3317                 new EditClipCommand(this, item->clipId(), item->referencedClip()->currentProperties(props), props, true, proxyCommand);
3318
3319             }
3320         }
3321         ++it;
3322     }
3323     if (proxyCommand->childCount() == 0)
3324         delete proxyCommand;
3325     else
3326         m_commandStack->push(proxyCommand);
3327     QFile::remove(proxyPath);
3328 }
3329
3330 void ProjectList::setJobStatus(ProjectItem *item, JOBTYPE jobType, ClipJobStatus status, int progress, const QString &statusMessage)
3331 {
3332     if (item == NULL || (m_abortAllJobs && m_closing)) return;
3333     monitorItemEditing(false);
3334     item->setJobStatus(jobType, status, progress, statusMessage);
3335     if (status == JobCrashed) {
3336         DocClipBase *clip = item->referencedClip();
3337         if (!clip) {
3338             kDebug()<<"// PROXY CRASHED";
3339         }
3340         else if (clip->getProducer() == NULL && !clip->isPlaceHolder()) {
3341             // disable proxy and fetch real clip
3342             clip->setProperty("proxy", "-");
3343             QDomElement xml = clip->toXML();
3344             m_render->getFileProperties(xml, clip->getId(), m_listView->iconSize().height(), true);
3345         }
3346         else {
3347             // Disable proxy for this clip
3348             clip->setProperty("proxy", "-");
3349         }
3350     }
3351     monitorItemEditing(true);
3352 }
3353
3354 void ProjectList::monitorItemEditing(bool enable)
3355 {
3356     if (enable) connect(m_listView, SIGNAL(itemChanged(QTreeWidgetItem*,int)), this, SLOT(slotItemEdited(QTreeWidgetItem*,int)));
3357     else disconnect(m_listView, SIGNAL(itemChanged(QTreeWidgetItem*,int)), this, SLOT(slotItemEdited(QTreeWidgetItem*,int)));
3358 }
3359
3360 QStringList ProjectList::expandedFolders() const
3361 {
3362     QStringList result;
3363     FolderProjectItem *item;
3364     QTreeWidgetItemIterator it(m_listView);
3365     while (*it) {
3366         if ((*it)->type() != ProjectFoldeType) {
3367             ++it;
3368             continue;
3369         }
3370         if ((*it)->isExpanded()) {
3371             item = static_cast<FolderProjectItem *>(*it);
3372             result.append(item->clipId());
3373         }
3374         ++it;
3375     }
3376     return result;
3377 }
3378
3379 void ProjectList::processThumbOverlays(ProjectItem *item, QPixmap &pix)
3380 {
3381     if (item->hasProxy()) {
3382         QPainter p(&pix);
3383         QColor c(220, 220, 10, 200);
3384         QRect r(0, 0, 12, 12);
3385         p.fillRect(r, c);
3386         QFont font = p.font();
3387         font.setBold(true);
3388         p.setFont(font);
3389         p.setPen(Qt::black);
3390         p.drawText(r, Qt::AlignCenter, i18nc("The first letter of Proxy, used as abbreviation", "P"));
3391     }
3392 }
3393
3394 void ProjectList::slotCancelJobs()
3395 {
3396     m_abortAllJobs = true;
3397     for (int i = 0; i < m_jobList.count(); ++i) {
3398         m_jobList.at(i)->setStatus(JobAborted);
3399     }
3400     m_jobThreads.waitForFinished();
3401     m_jobThreads.clearFutures();
3402     QUndoCommand *command = new QUndoCommand();
3403     command->setText(i18np("Cancel job", "Cancel jobs", m_jobList.count()));
3404     m_jobMutex.lock();
3405     for (int i = 0; i < m_jobList.count(); ++i) {
3406         DocClipBase *currentClip = m_doc->clipManager()->getClipById(m_jobList.at(i)->clipId());
3407         if (!currentClip) continue;
3408         QMap <QString, QString> newProps = m_jobList.at(i)->cancelProperties();
3409         if (newProps.isEmpty()) continue;
3410         QMap <QString, QString> oldProps = currentClip->currentProperties(newProps);
3411         new EditClipCommand(this, m_jobList.at(i)->clipId(), oldProps, newProps, true, command);
3412     }
3413     m_jobMutex.unlock();
3414     if (command->childCount() > 0) {
3415         m_doc->commandStack()->push(command);
3416     }
3417     else delete command;
3418     if (!m_jobList.isEmpty()) qDeleteAll(m_jobList);
3419     m_jobList.clear();
3420     m_abortAllJobs = false;
3421     m_infoLabel->slotSetJobCount(0);
3422 }
3423
3424 void ProjectList::slotCancelRunningJob(const QString id, stringMap newProps)
3425 {
3426     if (newProps.isEmpty() || m_closing) return;
3427     DocClipBase *currentClip = m_doc->clipManager()->getClipById(id);
3428     if (!currentClip) return;
3429     QMap <QString, QString> oldProps = currentClip->currentProperties(newProps);
3430     if (newProps == oldProps) return;
3431     QMapIterator<QString, QString> i(oldProps);
3432     EditClipCommand *command = new EditClipCommand(this, id, oldProps, newProps, true);
3433     m_commandStack->push(command);
3434 }
3435
3436 bool ProjectList::hasPendingJob(ProjectItem *item, JOBTYPE type)
3437 {
3438     if (!item || !item->referencedClip() || m_abortAllJobs) return false;
3439     AbstractClipJob *job;
3440     QMutexLocker lock(&m_jobMutex);
3441     for (int i = 0; i < m_jobList.count(); ++i) {
3442         if (m_abortAllJobs) break;
3443         job = m_jobList.at(i);
3444         if (job->clipId() == item->clipId() && job->jobType == type && (job->status() == JobWaiting || job->status() == JobWorking)) return true;
3445     }
3446     
3447     return false;
3448 }
3449
3450 void ProjectList::deleteJobsForClip(const QString &clipId)
3451 {
3452     QMutexLocker lock(&m_jobMutex);
3453     for (int i = 0; i < m_jobList.count(); ++i) {
3454         if (m_jobList.at(i)->clipId() == clipId) {
3455             m_jobList.at(i)->setStatus(JobAborted);
3456         }
3457     }
3458 }
3459
3460 void ProjectList::slotUpdateJobStatus(const QString id, int type, int status, const QString label, const QString actionName, const QString details)
3461 {
3462     ProjectItem *item = getItemById(id);
3463     if (!item) return;
3464     slotUpdateJobStatus(item, type, status, label, actionName, details);
3465     
3466 }
3467
3468 void ProjectList::slotUpdateJobStatus(ProjectItem *item, int type, int status, const QString &label, const QString &actionName, const QString details)
3469 {
3470     item->setJobStatus((JOBTYPE) type, (ClipJobStatus) status);
3471     if (status != JobCrashed) return;
3472 #if KDE_IS_VERSION(4,7,0)
3473     QList<QAction *> actions = m_infoMessage->actions();
3474     if (m_infoMessage->isHidden()) {
3475         m_infoMessage->setText(label);
3476         m_infoMessage->setWordWrap(m_infoMessage->text().length() > 35);
3477         m_infoMessage->setMessageType(KMessageWidget::Warning);
3478     }
3479     
3480     if (!actionName.isEmpty()) {
3481         QAction *action = NULL;
3482         QList< KActionCollection * > collections = KActionCollection::allCollections();
3483         for (int i = 0; i < collections.count(); ++i) {
3484             KActionCollection *coll = collections.at(i);
3485             action = coll->action(actionName);
3486             if (action) break;
3487         }
3488         if (action && !actions.contains(action)) m_infoMessage->addAction(action);
3489     }
3490     if (!details.isEmpty()) {
3491         m_errorLog.append(details);
3492         if (!actions.contains(m_logAction)) m_infoMessage->addAction(m_logAction);
3493     }
3494     m_infoMessage->animatedShow();
3495 #else
3496     // warning for KDE < 4.7
3497     KPassivePopup *passivePop = new KPassivePopup( this );
3498     passivePop->setAutoDelete(true);
3499     connect(passivePop, SIGNAL(clicked()), this, SLOT(slotClosePopup()));
3500     m_errorLog.append(details);
3501     KVBox *vb = new KVBox( passivePop );
3502     KHBox *vh1 = new KHBox( vb );
3503     KIcon icon("dialog-warning");
3504     QLabel *iconLabel = new QLabel(vh1);
3505     iconLabel->setPixmap(icon.pixmap(m_listView->iconSize()));
3506     (void) new QLabel( label, vh1);
3507     KHBox *box = new KHBox( vb );
3508     QPushButton *but = new QPushButton( "Show log", box );
3509     connect(but, SIGNAL(clicked(bool)), this, SLOT(slotShowJobLog()));
3510
3511     passivePop->setView( vb );
3512     passivePop->show();
3513     
3514 #endif
3515 }
3516
3517 void ProjectList::slotShowJobLog()
3518 {
3519     KDialog d(this);
3520     d.setButtons(KDialog::Close);
3521     QTextEdit t(&d);
3522     for (int i = 0; i < m_errorLog.count(); ++i) {
3523         if (i > 0) t.insertHtml("<br><hr /><br>");
3524         t.insertPlainText(m_errorLog.at(i));
3525     }
3526     t.setReadOnly(true);
3527     d.setMainWidget(&t);
3528     d.exec();
3529 }
3530
3531 QStringList ProjectList::getPendingJobs(const QString &id)
3532 {
3533     QStringList result;
3534     QMutexLocker lock(&m_jobMutex);
3535     for (int i = 0; i < m_jobList.count(); ++i) {
3536         if (m_jobList.at(i)->clipId() == id && (m_jobList.at(i)->status() == JobWaiting || m_jobList.at(i)->status() == JobWorking)) {
3537             // discard this job
3538             result << m_jobList.at(i)->description;
3539         }
3540     }
3541     return result;
3542 }
3543
3544 void ProjectList::discardJobs(const QString &id, JOBTYPE type) {
3545     QMutexLocker lock(&m_jobMutex);
3546     for (int i = 0; i < m_jobList.count(); ++i) {
3547         if (m_jobList.at(i)->clipId() == id && (m_jobList.at(i)->jobType == type || type == NOJOBTYPE)) {
3548             // discard this job
3549             m_jobList.at(i)->setStatus(JobAborted);
3550         }
3551     }
3552 }
3553
3554 void ProjectList::slotStartFilterJob(ItemInfo info, const QString&id, const QString&filterName, const QString&filterParams, const QString&consumer, const QString&consumerParams, const QMap <QString, QString> &extraParams)
3555 {
3556     ProjectItem *item = getItemById(id);
3557     if (!item) return;
3558     QStringList jobParams;
3559     jobParams << QString::number((int) info.cropStart.frames(m_fps)) << QString::number((int) (info.cropStart + info.cropDuration).frames(m_fps));
3560     jobParams << QString() << filterName << filterParams << consumer << consumerParams << QString::number((int) info.startPos.frames(m_fps)) << QString::number(info.track);
3561     MeltJob *job = new MeltJob(item->clipType(), id, jobParams, extraParams);
3562     if (job->isExclusive() && hasPendingJob(item, job->jobType)) {
3563         delete job;
3564         return;
3565     }
3566     job->description = i18n("Filter %1", extraParams.value("finalfilter"));
3567     m_jobList.append(job);
3568     setJobStatus(item, job->jobType, JobWaiting, 0, job->statusMessage());
3569     slotCheckJobProcess();
3570 }
3571
3572 void ProjectList::startClipFilterJob(const QString &filterName, const QString &condition)
3573 {
3574     QMap <QString, QString> ids = getConditionalIds(condition);
3575     QStringList destination;
3576     QMap<QString, QString>::const_iterator first = ids.constBegin();
3577     if (first == ids.constEnd()) {
3578         emit displayMessage(i18n("Cannot find clip to process filter %1", filterName), -2, ErrorMessage);
3579         return;
3580     }
3581     ProjectItem *item = getItemById(first.key());
3582     if (!item) {
3583         emit displayMessage(i18n("Cannot find clip to process filter %1", filterName), -2, ErrorMessage);
3584         return;
3585     }
3586     if (ids.count() == 1) {
3587         destination << item->clipUrl().path();
3588     }
3589     else {
3590         destination = ids.values();
3591     }
3592     if (filterName == "framebuffer") {
3593         Mlt::Profile profile;
3594         QStringList keys = ids.keys();
3595         int ix = 0;
3596         foreach(const QString &url, destination) {
3597             QString prodstring = QString("framebuffer:" + url + "?-1");
3598             Mlt::Producer *reversed = new Mlt::Producer(profile, prodstring.toUtf8().constData());
3599             if (!reversed || !reversed->is_valid()) {
3600                 emit displayMessage(i18n("Cannot reverse clip"), -2, ErrorMessage);
3601                 continue;
3602             }
3603             QString dest = url + ".mlt";
3604             if (QFile::exists(dest)) {
3605                 if (KMessageBox::questionYesNo(this, i18n("File %1 already exists.\nDo you want to overwrite it?", dest)) == KMessageBox::No) continue;
3606             }
3607             Mlt::Consumer *cons = new Mlt::Consumer(profile, "xml", dest.toUtf8().constData());
3608             if (cons == NULL || !cons->is_valid()) {
3609                 emit displayMessage(i18n("Cannot render reversed clip"), -2, ErrorMessage);
3610                 continue;
3611             }
3612             Mlt::Playlist list;
3613             list.insert_at(0, reversed, 0);
3614             delete reversed;
3615             cons->connect(list);
3616             cons->run();
3617             delete cons;
3618             QString groupId;
3619             QString groupName;
3620             DocClipBase *base = m_doc->clipManager()->getClipById(keys.at(ix));
3621             if (base) {
3622                 groupId = base->getProperty("groupid");
3623                 groupName = base->getProperty("groupname");
3624             }
3625             emit addClip(dest, groupId, groupName);
3626             ix++;
3627         }
3628         return;
3629     }
3630     
3631     if (filterName == "motion_est") {
3632         // Show config dialog
3633         QPointer<QDialog> d = new QDialog(this);
3634         Ui::SceneCutDialog_UI ui;
3635         ui.setupUi(d);
3636         // Set  up categories
3637         for (int i = 0; i < 5; ++i) {
3638             ui.marker_type->insertItem(i, i18n("Category %1", i));
3639             ui.marker_type->setItemData(i, CommentedTime::markerColor(i), Qt::DecorationRole);
3640         }
3641         ui.marker_type->setCurrentIndex(KdenliveSettings::default_marker_type());
3642         if (d->exec() != QDialog::Accepted) {
3643             delete d;
3644             return;
3645         }
3646         // Autosplit filter
3647         QStringList jobParams;
3648         // Producer params
3649         jobParams << QString();
3650         // Filter params, use a smaller region of the image to speed up operation
3651         // In fact, it's faster to rescale whole image than using part of it (bounding=\"25%x25%:15%x15\")
3652         jobParams << filterName << "shot_change_list=0 denoise=0";
3653         // Consumer
3654         jobParams << "null" << "all=1 terminate_on_pause=1 real_time=-1 rescale=nearest deinterlace_method=onefield top_field_first=-1";
3655         QMap <QString, QString> extraParams;
3656         extraParams.insert("key", "shot_change_list");
3657         extraParams.insert("projecttreefilter", "1");
3658         QString keyword("%count");
3659         extraParams.insert("resultmessage", i18n("Found %1 scenes.", keyword));
3660         extraParams.insert("resize_profile", "160");
3661         if (ui.store_data->isChecked()) {
3662             // We want to save result as clip metadata
3663             extraParams.insert("storedata", "1");
3664         }
3665         if (ui.zone_only->isChecked()) {
3666             // We want to analyze only clip zone
3667             extraParams.insert("zoneonly", "1");
3668         }
3669         if (ui.add_markers->isChecked()) {
3670             // We want to create markers
3671             extraParams.insert("addmarkers", QString::number(ui.marker_type->currentIndex()));
3672         }
3673         if (ui.cut_scenes->isChecked()) {
3674             // We want to cut scenes
3675             extraParams.insert("cutscenes", "1");
3676         }
3677         delete d;
3678         processClipJob(ids.keys(), QString(), false, jobParams, i18n("Auto split"), extraParams);
3679     }
3680     else {
3681         QPointer<ClipStabilize> d = new ClipStabilize(destination, filterName);
3682         if (d->exec() == QDialog::Accepted) {
3683             QMap <QString, QString> extraParams;
3684             extraParams.insert("producer_profile", "1");
3685             processClipJob(ids.keys(), d->destination(), d->autoAddClip(), d->params(), d->desc(), extraParams);
3686         }
3687         delete d;
3688     }
3689 }
3690
3691 void ProjectList::processClipJob(QStringList ids, const QString&destination, bool autoAdd, QStringList jobParams, const QString &description, QMap <QString, QString> extraParams)
3692 {
3693     QStringList preParams;
3694     // in and out
3695     preParams << QString::number(0) << QString::number(-1);
3696     // producer params
3697     preParams << jobParams.takeFirst();
3698     // filter name
3699     preParams << jobParams.takeFirst();
3700     // filter params
3701     preParams << jobParams.takeFirst();
3702     // consumer
3703     QString consumer = jobParams.takeFirst();
3704     
3705     foreach(const QString&id, ids) {
3706         ProjectItem *item = getItemById(id);
3707         if (!item) continue;
3708         QStringList jobArgs;
3709         if (extraParams.contains("zoneonly")) {
3710             // Analyse clip zone only, remove in / out and replace with zone
3711             preParams.takeFirst();
3712             preParams.takeFirst();
3713             QPoint zone = item->referencedClip()->zone();
3714             jobArgs << QString::number(zone.x()) << QString::number(zone.y());
3715         }
3716         jobArgs << preParams;
3717         if (ids.count() == 1) {
3718             jobArgs << consumer + ':' + destination;
3719         }
3720         else {
3721             jobArgs << consumer + ':' + destination + item->clipUrl().fileName() + ".mlt";
3722         }
3723         jobArgs << jobParams;
3724         
3725         MeltJob *job = new MeltJob(item->clipType(), id, jobArgs, extraParams);
3726         if (autoAdd) {
3727             job->setAddClipToProject(true);
3728             kDebug()<<"// ADDING TRUE";
3729         }
3730         else kDebug()<<"// ADDING FALSE!!!";
3731
3732         if (job->isExclusive() && hasPendingJob(item, job->jobType)) {
3733             delete job;
3734             return;
3735         }
3736         job->description = description;
3737         m_jobList.append(job);
3738         setJobStatus(item, job->jobType, JobWaiting, 0, job->statusMessage());
3739         slotCheckJobProcess();
3740     }
3741 }
3742
3743
3744 void ProjectList::slotPrepareJobsMenu()
3745 {
3746     ProjectItem *item;
3747     if (!m_listView->currentItem() || m_listView->currentItem()->type() == ProjectFoldeType)
3748         return;
3749     if (m_listView->currentItem()->type() == ProjectSubclipType)
3750         item = static_cast <ProjectItem*>(m_listView->currentItem()->parent());
3751     else
3752         item = static_cast <ProjectItem*>(m_listView->currentItem());
3753     if (item && (item->flags() & Qt::ItemIsDragEnabled)) {
3754         QString id = item->clipId();
3755         m_discardCurrentClipJobs->setData(id);
3756         QStringList jobs = getPendingJobs(id);
3757         m_discardCurrentClipJobs->setEnabled(!jobs.isEmpty());
3758     } else {
3759         m_discardCurrentClipJobs->setData(QString());
3760         m_discardCurrentClipJobs->setEnabled(false);
3761     }
3762 }
3763
3764 void ProjectList::slotDiscardClipJobs()
3765 {
3766     QString id = m_discardCurrentClipJobs->data().toString();
3767     if (id.isEmpty()) return;
3768     discardJobs(id);
3769 }
3770
3771 void ProjectList::updatePalette()
3772 {
3773     m_infoLabel->setStyleSheet(SmallInfoLabel::getStyleSheet(QApplication::palette()));
3774     m_listView->updateStyleSheet();
3775 }
3776
3777 void ProjectList::slotResetInfoMessage()
3778 {
3779 #if KDE_IS_VERSION(4,7,0)
3780     m_errorLog.clear();
3781     QList<QAction *> actions = m_infoMessage->actions();
3782     for (int i = 0; i < actions.count(); ++i) {
3783         m_infoMessage->removeAction(actions.at(i));
3784     }
3785 #endif
3786 }
3787
3788 void ProjectList::slotClosePopup()
3789 {
3790     m_errorLog.clear();
3791 }
3792
3793 void ProjectList::slotGotFilterJobResults(QString id, int , int , stringMap results, stringMap filterInfo)
3794 {
3795     // Currently, only the first value of results is used
3796     //kDebug()<<"// FILTER RES:\n"<<filterInfo<<"\n--------------\n"<<results;
3797     ProjectItem *clip = getItemById(id);
3798     if (!clip) return;
3799
3800     // Check for return value
3801     int markersType = -1;
3802     if (filterInfo.contains("addmarkers")) markersType = filterInfo.value("addmarkers").toInt();
3803     if (results.isEmpty()) {
3804         emit displayMessage(i18n("No data returned from clip analysis"), 0, ErrorMessage);
3805         return;
3806     }
3807     bool dataProcessed = false;
3808     QString key = filterInfo.value("key");
3809     int offset = filterInfo.value("offset").toInt();
3810     QStringList value = results.value(key).split(';', QString::SkipEmptyParts);
3811     kDebug()<<"// RESULT; "<<key<<" = "<<value;
3812     if (filterInfo.contains("resultmessage")) {
3813         QString mess = filterInfo.value("resultmessage");
3814         mess.replace("%count", QString::number(value.count()));
3815         emit displayMessage(mess, 0, InformationMessage);
3816     }
3817     else emit displayMessage(i18n("Processing data analysis"), 0, InformationMessage);
3818     if (filterInfo.contains("cutscenes")) {
3819         // Check if we want to cut scenes from returned data
3820         dataProcessed = true;
3821         int cutPos = 0;
3822         QUndoCommand *command = new QUndoCommand();
3823         command->setText(i18n("Auto Split Clip"));
3824         foreach (QString pos, value) {
3825             if (!pos.contains("=")) continue;
3826             int newPos = pos.section("=", 0, 0).toInt();
3827             // Don't use scenes shorter than 1 second
3828             if (newPos - cutPos < 24) continue;
3829             (void) new AddClipCutCommand(this, id, cutPos + offset, newPos + offset, QString(), true, false, command);
3830             cutPos = newPos;
3831         }
3832         if (command->childCount() == 0)
3833             delete command;
3834         else m_commandStack->push(command);
3835     }
3836     if (markersType >= 0) {
3837         // Add markers from returned data
3838         dataProcessed = true;
3839         int cutPos = 0;
3840         QUndoCommand *command = new QUndoCommand();
3841         command->setText(i18n("Add Markers"));
3842         QList <CommentedTime> markersList;
3843         int index = 1;
3844         foreach (QString pos, value) {
3845             if (!pos.contains("=")) continue;
3846             int newPos = pos.section("=", 0, 0).toInt();
3847             // Don't use scenes shorter than 1 second
3848             if (newPos - cutPos < 24) continue;
3849             CommentedTime m(GenTime(newPos + offset, m_fps), QString::number(index), markersType);
3850             markersList << m;
3851             index++;
3852             cutPos = newPos;
3853         }
3854         emit addMarkers(id, markersList);
3855     }
3856     if (!dataProcessed || filterInfo.contains("storedata")) {
3857         // Store returned data as clip extra data
3858         clip->referencedClip()->setAnalysisData(filterInfo.contains("displaydataname") ? filterInfo.value("displaydataname") : key, results.value(key), filterInfo.value("offset").toInt());
3859         emit updateAnalysisData(clip->referencedClip());
3860     }
3861 }
3862
3863
3864 /*
3865 // Work in progress: apply filter based on clip's camcorder
3866 void ProjectList::checkCamcorderFilters(DocClipBase *clip, QMap <QString, QString> meta)
3867 {
3868     KConfig conf("camcorderfilters.rc", KConfig::CascadeConfig, "appdata");
3869     QStringList groups = conf.groupList();
3870     foreach(QString grp, groups) {
3871     if (!meta.contains(grp)) continue;
3872     KConfigGroup group(&conf, grp);
3873     QString value = group.readEntry(meta.value(grp));
3874     if (value.isEmpty()) continue;
3875     clip->setProperty(value.section(' ', 0, 0), value.section(' ', 1));
3876     break;
3877     }
3878 }*/
3879
3880 #include "projectlist.moc"