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