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