]> git.sesse.net Git - kdenlive/blob - src/projectlist.cpp
small cleanup
[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")) {
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("force_colorspace") || 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             editFolder(item->text(0), folder->groupName(), folder->clipId());
1019             folder->setGroupName(item->text(0));
1020             m_doc->clipManager()->addFolder(folder->clipId(), item->text(0));
1021             const int children = item->childCount();
1022             for (int i = 0; i < children; i++) {
1023                 ProjectItem *child = static_cast <ProjectItem *>(item->child(i));
1024                 child->setProperty("groupname", item->text(0));
1025             }
1026         }
1027         return;
1028     }
1029
1030     ProjectItem *clip = static_cast <ProjectItem*>(item);
1031     if (column == 1) {
1032         if (clip->referencedClip()) {
1033             QMap <QString, QString> oldprops;
1034             QMap <QString, QString> newprops;
1035             oldprops["description"] = clip->referencedClip()->getProperty("description");
1036             newprops["description"] = item->text(1);
1037
1038             if (clip->clipType() == TEXT) {
1039                 // This is a text template clip, update the image
1040                 /*oldprops.insert("xmldata", clip->referencedClip()->getProperty("xmldata"));
1041                 newprops.insert("xmldata", generateTemplateXml(clip->referencedClip()->getProperty("xmltemplate"), item->text(2)).toString());*/
1042                 oldprops.insert("templatetext", clip->referencedClip()->getProperty("templatetext"));
1043                 newprops.insert("templatetext", item->text(1));
1044             }
1045             slotUpdateClipProperties(clip->clipId(), newprops);
1046             EditClipCommand *command = new EditClipCommand(this, clip->clipId(), oldprops, newprops, false);
1047             m_commandStack->push(command);
1048         }
1049     } else if (column == 0) {
1050         if (clip->referencedClip()) {
1051             QMap <QString, QString> oldprops;
1052             QMap <QString, QString> newprops;
1053             oldprops["name"] = clip->referencedClip()->getProperty("name");
1054             if (oldprops.value("name") != item->text(0)) {
1055                 newprops["name"] = item->text(0);
1056                 slotUpdateClipProperties(clip, newprops);
1057                 emit projectModified();
1058                 EditClipCommand *command = new EditClipCommand(this, clip->clipId(), oldprops, newprops, false);
1059                 m_commandStack->push(command);
1060                 QTimer::singleShot(100, this, SLOT(slotCheckScrolling()));
1061             }
1062         }
1063     }
1064 }
1065
1066 void ProjectList::slotCheckScrolling()
1067 {
1068     m_listView->scrollToItem(m_listView->currentItem());
1069 }
1070
1071 void ProjectList::slotContextMenu(const QPoint &pos, QTreeWidgetItem *item)
1072 {
1073     bool enable = item ? true : false;
1074     m_editButton->defaultAction()->setEnabled(enable);
1075     m_deleteButton->defaultAction()->setEnabled(enable);
1076     m_reloadAction->setEnabled(enable);
1077     m_extractAudioAction->setEnabled(enable);
1078     m_transcodeAction->setEnabled(enable);
1079     m_clipsActionsMenu->setEnabled(enable);
1080     if (enable) {
1081         ProjectItem *clip = NULL;
1082         if (m_listView->currentItem()->type() == PROJECTSUBCLIPTYPE) {
1083             clip = static_cast <ProjectItem*>(item->parent());
1084             m_extractAudioAction->setEnabled(false);
1085             m_transcodeAction->setEnabled(false);
1086             m_clipsActionsMenu->setEnabled(false);
1087             adjustProxyActions(clip);
1088         } else if (m_listView->currentItem()->type() == PROJECTCLIPTYPE) {
1089             clip = static_cast <ProjectItem*>(item);
1090             // Display relevant transcoding actions only
1091             adjustTranscodeActions(clip);
1092             adjustStabilizeActions(clip);
1093             adjustProxyActions(clip);
1094             // Display uses in timeline
1095             emit findInTimeline(clip->clipId());
1096         } else {
1097             m_extractAudioAction->setEnabled(false);
1098             m_transcodeAction->setEnabled(false);
1099             m_clipsActionsMenu->setEnabled(false);
1100         }
1101         if (clip && clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) {
1102             m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
1103             m_openAction->setEnabled(true);
1104         } else if (clip && clip->clipType() == AUDIO && !KdenliveSettings::defaultaudioapp().isEmpty()) {
1105             m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
1106             m_openAction->setEnabled(true);
1107         } else {
1108             m_openAction->setEnabled(false);
1109         }
1110
1111     } else {
1112         m_openAction->setEnabled(false);
1113     }
1114     m_menu->popup(pos);
1115 }
1116
1117 void ProjectList::slotRemoveClip()
1118 {
1119     if (!m_listView->currentItem())
1120         return;
1121     QStringList ids;
1122     QMap <QString, QString> folderids;
1123     QList<QTreeWidgetItem *> selected = m_listView->selectedItems();
1124
1125     QUndoCommand *delCommand = new QUndoCommand();
1126     delCommand->setText(i18n("Delete Clip Zone"));
1127     for (int i = 0; i < selected.count(); i++) {
1128         if (selected.at(i)->type() == PROJECTSUBCLIPTYPE) {
1129             // subitem
1130             SubProjectItem *sub = static_cast <SubProjectItem *>(selected.at(i));
1131             ProjectItem *item = static_cast <ProjectItem *>(sub->parent());
1132             new AddClipCutCommand(this, item->clipId(), sub->zone().x(), sub->zone().y(), sub->description(), false, true, delCommand);
1133         } else if (selected.at(i)->type() == PROJECTFOLDERTYPE) {
1134             // folder
1135             FolderProjectItem *folder = static_cast <FolderProjectItem *>(selected.at(i));
1136             folderids[folder->groupName()] = folder->clipId();
1137             int children = folder->childCount();
1138
1139             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)
1140                 return;
1141             for (int i = 0; i < children; ++i) {
1142                 ProjectItem *child = static_cast <ProjectItem *>(folder->child(i));
1143                 ids << child->clipId();
1144             }
1145         } else {
1146             ProjectItem *item = static_cast <ProjectItem *>(selected.at(i));
1147             ids << item->clipId();
1148             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) {
1149                 KMessageBox::enableMessage("DeleteAll");
1150                 return;
1151             }
1152         }
1153     }
1154     KMessageBox::enableMessage("DeleteAll");
1155     if (delCommand->childCount() == 0)
1156         delete delCommand;
1157     else
1158         m_commandStack->push(delCommand);
1159     emit deleteProjectClips(ids, folderids);
1160 }
1161
1162 void ProjectList::updateButtons() const
1163 {
1164     if (m_listView->topLevelItemCount() == 0) {
1165         m_deleteButton->defaultAction()->setEnabled(false);
1166         m_editButton->defaultAction()->setEnabled(false);
1167     } else {
1168         m_deleteButton->defaultAction()->setEnabled(true);
1169         if (!m_listView->currentItem())
1170             m_listView->setCurrentItem(m_listView->topLevelItem(0));
1171         QTreeWidgetItem *item = m_listView->currentItem();
1172         if (item && item->type() == PROJECTCLIPTYPE) {
1173             m_editButton->defaultAction()->setEnabled(true);
1174             m_openAction->setEnabled(true);
1175             m_reloadAction->setEnabled(true);
1176             m_transcodeAction->setEnabled(true);
1177             m_clipsActionsMenu->setEnabled(true);
1178             return;
1179         }
1180         else if (item && item->type() == PROJECTFOLDERTYPE && item->childCount() > 0) {
1181             m_editButton->defaultAction()->setEnabled(true);
1182         }
1183         else m_editButton->defaultAction()->setEnabled(false);
1184     }
1185     m_openAction->setEnabled(false);
1186     m_reloadAction->setEnabled(false);
1187     m_transcodeAction->setEnabled(false);
1188     m_clipsActionsMenu->setEnabled(false);
1189     m_proxyAction->setEnabled(false);
1190 }
1191
1192 void ProjectList::selectItemById(const QString &clipId)
1193 {
1194     ProjectItem *item = getItemById(clipId);
1195     if (item)
1196         m_listView->setCurrentItem(item);
1197 }
1198
1199
1200 void ProjectList::slotDeleteClip(const QString &clipId)
1201 {
1202     ProjectItem *item = getItemById(clipId);
1203     if (!item) {
1204         kDebug() << "/// Cannot find clip to delete";
1205         return;
1206     }
1207     deleteJobsForClip(clipId);
1208     m_listView->blockSignals(true);
1209     QTreeWidgetItem *newSelectedItem = m_listView->itemAbove(item);
1210     if (!newSelectedItem)
1211         newSelectedItem = m_listView->itemBelow(item);
1212     delete item;
1213     // Pause playing to prevent crash while deleting clip
1214     slotPauseMonitor();
1215     m_doc->clipManager()->deleteClip(clipId);
1216     m_listView->blockSignals(false);
1217     if (newSelectedItem) {
1218         m_listView->setCurrentItem(newSelectedItem);
1219     } else {
1220         updateButtons();
1221         emit clipSelected(NULL);
1222     }
1223 }
1224
1225
1226 void ProjectList::editFolder(const QString folderName, const QString oldfolderName, const QString &clipId)
1227 {
1228     EditFolderCommand *command = new EditFolderCommand(this, folderName, oldfolderName, clipId, false);
1229     m_commandStack->push(command);
1230     m_doc->setModified(true);
1231 }
1232
1233 void ProjectList::slotAddFolder(const QString &name)
1234 {
1235     AddFolderCommand *command = new AddFolderCommand(this, name.isEmpty() ? i18n("Folder") : name, QString::number(m_doc->clipManager()->getFreeFolderId()), true);
1236     m_commandStack->push(command);
1237 }
1238
1239 void ProjectList::slotAddFolder(const QString foldername, const QString &clipId, bool remove, bool edit)
1240 {
1241     if (remove) {
1242         FolderProjectItem *item = getFolderItemById(clipId);
1243         if (item) {
1244             m_doc->clipManager()->deleteFolder(clipId);
1245             QTreeWidgetItem *newSelectedItem = m_listView->itemAbove(item);
1246             if (!newSelectedItem)
1247                 newSelectedItem = m_listView->itemBelow(item);
1248             delete item;
1249             if (newSelectedItem)
1250                 m_listView->setCurrentItem(newSelectedItem);
1251             else
1252                 updateButtons();
1253         }
1254     } else {
1255         if (edit) {
1256             FolderProjectItem *item = getFolderItemById(clipId);
1257             if (item) {
1258                 m_listView->blockSignals(true);
1259                 item->setGroupName(foldername);
1260                 m_listView->blockSignals(false);
1261                 m_doc->clipManager()->addFolder(clipId, foldername);
1262                 const int children = item->childCount();
1263                 for (int i = 0; i < children; i++) {
1264                     ProjectItem *child = static_cast <ProjectItem *>(item->child(i));
1265                     child->setProperty("groupname", foldername);
1266                 }
1267             }
1268         } else {
1269             m_listView->blockSignals(true);
1270             m_listView->setCurrentItem(new FolderProjectItem(m_listView, QStringList() << foldername, clipId));
1271             m_doc->clipManager()->addFolder(clipId, foldername);
1272             m_listView->blockSignals(false);
1273             m_listView->editItem(m_listView->currentItem(), 0);
1274         }
1275         updateButtons();
1276     }
1277     m_doc->setModified(true);
1278 }
1279
1280
1281
1282 void ProjectList::deleteProjectFolder(QMap <QString, QString> map)
1283 {
1284     QMapIterator<QString, QString> i(map);
1285     QUndoCommand *delCommand = new QUndoCommand();
1286     delCommand->setText(i18n("Delete Folder"));
1287     while (i.hasNext()) {
1288         i.next();
1289         new AddFolderCommand(this, i.key(), i.value(), false, delCommand);
1290     }
1291     if (delCommand->childCount() > 0) m_commandStack->push(delCommand);
1292     else delete delCommand;
1293 }
1294
1295 void ProjectList::slotAddClip(DocClipBase *clip, bool getProperties)
1296 {
1297     //m_listView->setEnabled(false);
1298     const QString parent = clip->getProperty("groupid");
1299     QString groupName = clip->getProperty("groupname");
1300     QSize pixelSize((int)(m_listView->iconSize().height()  * m_render->dar()), m_listView->iconSize().height());
1301     ProjectItem *item = NULL;
1302     monitorItemEditing(false);
1303     if (!parent.isEmpty()) {
1304         FolderProjectItem *parentitem = getFolderItemById(parent);
1305         if (!parentitem) {
1306             QStringList text;
1307             //kDebug() << "Adding clip to new group: " << groupName;
1308             if (groupName.isEmpty()) groupName = i18n("Folder");
1309             text << groupName;
1310             parentitem = new FolderProjectItem(m_listView, text, parent);
1311         }
1312
1313         if (parentitem)
1314             item = new ProjectItem(parentitem, clip, pixelSize);
1315     }
1316     if (item == NULL) {
1317         item = new ProjectItem(m_listView, clip, pixelSize);
1318     }
1319     if (item->data(0, DurationRole).isNull()) item->setData(0, DurationRole, i18n("Loading"));
1320     connect(clip, SIGNAL(createProxy(const QString &)), this, SLOT(slotCreateProxy(const QString &)));
1321     connect(clip, SIGNAL(abortProxy(const QString &, const QString &)), this, SLOT(slotAbortProxy(const QString, const QString)));
1322       
1323     if (getProperties) {
1324         //item->setFlags(Qt::ItemIsSelectable);
1325         m_listView->processLayout();
1326         QDomElement e = clip->toXML().cloneNode().toElement();
1327         if (!groupName.isEmpty()) {
1328             e.setAttribute("groupId", parent);
1329             e.setAttribute("group", groupName);
1330         }
1331         e.removeAttribute("file_hash");
1332         resetThumbsProducer(clip);
1333         m_render->getFileProperties(e, clip->getId(), m_listView->iconSize().height(), true);
1334     }
1335     // WARNING: code below triggers unnecessary reload of all proxy clips on document loading... is it useful in some cases?
1336     /*else if (item->hasProxy() && !item->isJobRunning()) {
1337         slotCreateProxy(clip->getId());
1338     }*/
1339     
1340     KUrl url = clip->fileURL();
1341 #ifdef USE_NEPOMUK
1342     if (!url.isEmpty() && KdenliveSettings::activate_nepomuk() && clip->getProperty("description").isEmpty()) {
1343         // if file has Nepomuk comment, use it
1344         Nepomuk::Resource f(url.path());
1345         QString annotation = f.description();
1346         if (!annotation.isEmpty()) {
1347             item->setText(1, annotation);
1348             clip->setProperty("description", annotation);
1349         }
1350         item->setText(2, QString::number(f.rating()));
1351     }
1352 #endif
1353
1354     // Add info to date column
1355     QFileInfo fileInfo(url.path());
1356     if (fileInfo.exists()) {
1357         item->setText(3, fileInfo.lastModified().toString(QString("yyyy/MM/dd hh:mm:ss")));
1358     }
1359
1360     // Add cut zones
1361     QList <CutZoneInfo> cuts = clip->cutZones();
1362     if (!cuts.isEmpty()) {
1363         for (int i = 0; i < cuts.count(); i++) {
1364             SubProjectItem *sub = new SubProjectItem(m_render->dar(), item, cuts.at(i).zone.x(), cuts.at(i).zone.y(), cuts.at(i).description);
1365             if (!clip->getClipHash().isEmpty()) {
1366                 QString cachedPixmap = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "thumbs/" + clip->getClipHash() + '#' + QString::number(cuts.at(i).zone.x()) + ".png";
1367                 if (QFile::exists(cachedPixmap)) {
1368                     QPixmap pix(cachedPixmap);
1369                     if (pix.isNull())
1370                         KIO::NetAccess::del(KUrl(cachedPixmap), this);
1371                     sub->setData(0, Qt::DecorationRole, pix);
1372                 }
1373             }
1374         }
1375     }
1376     monitorItemEditing(true);
1377     updateButtons();
1378 }
1379
1380 void ProjectList::slotGotProxy(const QString &proxyPath)
1381 {
1382     if (proxyPath.isEmpty() || m_abortAllJobs) return;
1383     QTreeWidgetItemIterator it(m_listView);
1384     ProjectItem *item;
1385
1386     while (*it && !m_closing) {
1387         if ((*it)->type() == PROJECTCLIPTYPE) {
1388             item = static_cast <ProjectItem *>(*it);
1389             if (item->referencedClip()->getProperty("proxy") == proxyPath)
1390                 slotGotProxy(item);
1391         }
1392         ++it;
1393     }
1394 }
1395
1396 void ProjectList::slotGotProxyForId(const QString id)
1397 {
1398     if (m_closing) return;
1399     ProjectItem *item = getItemById(id);
1400     slotGotProxy(item);
1401 }
1402
1403 void ProjectList::slotGotProxy(ProjectItem *item)
1404 {
1405     if (item == NULL) return;
1406     DocClipBase *clip = item->referencedClip();
1407     if (!clip || !clip->isClean() || m_render->isProcessing(item->clipId())) {
1408         // Clip is being reprocessed, abort
1409         kDebug()<<"//// TRYING TO PROXY: "<<item->clipId()<<", but it is busy";
1410         return;
1411     }
1412     
1413     // Proxy clip successfully created
1414     QDomElement e = clip->toXML().cloneNode().toElement();
1415
1416     // Make sure we get the correct producer length if it was adjusted in timeline
1417     CLIPTYPE t = item->clipType();
1418     if (t == COLOR || t == IMAGE || t == SLIDESHOW || t == TEXT) {
1419         int length = QString(clip->producerProperty("length")).toInt();
1420         if (length > 0 && !e.hasAttribute("length")) {
1421             e.setAttribute("length", length);
1422         }
1423     }
1424     resetThumbsProducer(clip);
1425     m_render->getFileProperties(e, clip->getId(), m_listView->iconSize().height(), true);
1426 }
1427
1428 void ProjectList::slotResetProjectList()
1429 {
1430     m_listView->blockSignals(true);
1431     m_abortAllJobs = true;
1432     for (int i = 0; i < m_jobList.count(); i++) {
1433         m_jobList.at(i)->setStatus(JOBABORTED);
1434     }
1435     m_closing = true;
1436     m_jobThreads.waitForFinished();
1437     m_jobThreads.clearFutures();
1438     m_thumbnailQueue.clear();
1439     if (!m_jobList.isEmpty()) qDeleteAll(m_jobList);
1440     m_jobList.clear();
1441     m_listView->clear();
1442     m_listView->setEnabled(true);
1443     emit clipSelected(NULL);
1444     m_refreshed = false;
1445     m_allClipsProcessed = false;
1446     m_abortAllJobs = false;
1447     m_closing = false;
1448     m_listView->blockSignals(false);
1449 }
1450
1451 void ProjectList::slotUpdateClip(const QString &id)
1452 {
1453     ProjectItem *item = getItemById(id);
1454     monitorItemEditing(false);
1455     if (item) item->setData(0, UsageRole, QString::number(item->numReferences()));
1456     monitorItemEditing(true);
1457 }
1458
1459 void ProjectList::getCachedThumbnail(ProjectItem *item)
1460 {
1461     if (!item) return;
1462     DocClipBase *clip = item->referencedClip();
1463     if (!clip) {
1464         return;
1465     }
1466     QString cachedPixmap = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "thumbs/" + clip->getClipHash() + ".png";
1467     if (QFile::exists(cachedPixmap)) {
1468         QPixmap pix(cachedPixmap);
1469         if (pix.isNull()) {
1470             KIO::NetAccess::del(KUrl(cachedPixmap), this);
1471             requestClipThumbnail(item->clipId());
1472         }
1473         else {
1474             QPixmap result = roundedPixmap(pix);
1475             processThumbOverlays(item, result);
1476             item->setPixmap(result);
1477         }
1478     }
1479     else {
1480         requestClipThumbnail(item->clipId());
1481     }
1482 }
1483
1484 QPixmap ProjectList::roundedPixmap(QImage img)
1485 {
1486     QPixmap pix(img.width(), img.height());
1487     pix.fill(Qt::transparent);
1488     QPainter p(&pix);
1489     p.setRenderHint(QPainter::Antialiasing, true);
1490     QPainterPath path;
1491     path.addRoundedRect(0.5, 0.5, pix.width() - 1, pix.height() - 1, 2, 2);
1492     p.setClipPath(path);
1493     p.drawImage(0, 0, img);
1494     p.end();
1495     return pix;
1496 }
1497
1498 QPixmap ProjectList::roundedPixmap(QPixmap source)
1499 {
1500     QPixmap pix(source.width(), source.height());
1501     pix.fill(Qt::transparent);
1502     QPainter p(&pix);
1503     p.setRenderHint(QPainter::Antialiasing, true);
1504     QPainterPath path;
1505     path.addRoundedRect(0.5, 0.5, pix.width() - 1, pix.height() - 1, 2, 2);
1506     p.setClipPath(path);
1507     p.drawPixmap(0, 0, source);
1508     p.end();
1509     return pix;
1510 }
1511
1512 void ProjectList::getCachedThumbnail(SubProjectItem *item)
1513 {
1514     if (!item) return;
1515     ProjectItem *parentItem = static_cast <ProjectItem *>(item->parent());
1516     if (!parentItem) return;
1517     DocClipBase *clip = parentItem->referencedClip();
1518     if (!clip) return;
1519     int pos = item->zone().x();
1520     QString cachedPixmap = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "thumbs/" + clip->getClipHash() + '#' + QString::number(pos) + ".png";
1521     if (QFile::exists(cachedPixmap)) {
1522         QPixmap pix(cachedPixmap);
1523         if (pix.isNull()) {
1524             KIO::NetAccess::del(KUrl(cachedPixmap), this);
1525             requestClipThumbnail(parentItem->clipId() + '#' + QString::number(pos));
1526         }
1527         else item->setData(0, Qt::DecorationRole, pix);
1528     }
1529     else requestClipThumbnail(parentItem->clipId() + '#' + QString::number(pos));
1530 }
1531
1532 void ProjectList::updateAllClips(bool displayRatioChanged, bool fpsChanged, QStringList brokenClips)
1533 {
1534     if (!m_allClipsProcessed) m_listView->setEnabled(false);
1535     m_listView->setSortingEnabled(false);
1536     QTreeWidgetItemIterator it(m_listView);
1537     DocClipBase *clip;
1538     ProjectItem *item;
1539     monitorItemEditing(false);
1540     int height = m_listView->iconSize().height();
1541     int width = (int)(height  * m_render->dar());
1542     QPixmap missingPixmap = QPixmap(width, height);
1543     missingPixmap.fill(Qt::transparent);
1544     KIcon icon("dialog-close");
1545     QPainter p(&missingPixmap);
1546     p.drawPixmap(3, 3, icon.pixmap(width - 6, height - 6));
1547     p.end();
1548     
1549     int max = m_doc->clipManager()->clipsCount();
1550     max = qMax(1, max);
1551     int ct = 0;
1552
1553     while (*it) {
1554         emit displayMessage(i18n("Loading thumbnails"), (int)(100 *(max - ct++) / max));
1555         if ((*it)->type() == PROJECTSUBCLIPTYPE) {
1556             // subitem
1557             SubProjectItem *sub = static_cast <SubProjectItem *>(*it);
1558             if (displayRatioChanged) {
1559                 item = static_cast <ProjectItem *>((*it)->parent());
1560                 requestClipThumbnail(item->clipId() + '#' + QString::number(sub->zone().x()));
1561             }
1562             else if (sub->data(0, Qt::DecorationRole).isNull()) {
1563                 getCachedThumbnail(sub);
1564             }
1565             ++it;
1566             continue;
1567         } else if ((*it)->type() == PROJECTFOLDERTYPE) {
1568             // folder
1569             ++it;
1570             continue;
1571         } else {
1572             item = static_cast <ProjectItem *>(*it);
1573             clip = item->referencedClip();
1574             if (clip->getProducer() == NULL) {
1575                 bool replace = false;
1576                 if (brokenClips.contains(item->clipId())) {
1577                     // if this is a proxy clip, disable proxy
1578                     item->setConditionalJobStatus(NOJOB, PROXYJOB);
1579                     discardJobs(item->clipId(), PROXYJOB);
1580                     clip->setProperty("proxy", "-");
1581                     replace = true;
1582                 }
1583                 if (clip->isPlaceHolder() == false && !hasPendingJob(item, PROXYJOB)) {
1584                     QDomElement xml = clip->toXML();
1585                     getCachedThumbnail(item);
1586                     if (fpsChanged) {
1587                         xml.removeAttribute("out");
1588                         xml.removeAttribute("file_hash");
1589                         xml.removeAttribute("proxy_out");
1590                     }
1591                     if (!replace) replace = xml.attribute("_replaceproxy") == "1";
1592                     xml.removeAttribute("_replaceproxy");
1593                     if (replace) {
1594                         resetThumbsProducer(clip);
1595                         m_render->getFileProperties(xml, clip->getId(), m_listView->iconSize().height(), replace);
1596                     }
1597                     else if (item->numReferences() > 0) {
1598                         // In some cases, like slowmotion clips, the producer is not loaded automatically be MLT
1599                         m_render->getFileProperties(xml, clip->getId(), m_listView->iconSize().height(), replace);
1600                     }
1601                 }
1602                 else if (clip->isPlaceHolder()) {
1603                     item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsDropEnabled);
1604                     if (!item->hasPixmap()) {
1605                         item->setPixmap(missingPixmap);
1606                     }
1607                     else {
1608                         QPixmap pixmap = qVariantValue<QPixmap>(item->data(0, Qt::DecorationRole));
1609                         QPainter p(&pixmap);
1610                         p.drawPixmap(3, 3, KIcon("dialog-close").pixmap(pixmap.width() - 6, pixmap.height() - 6));
1611                         p.end();
1612                         item->setPixmap(pixmap);
1613                     }
1614                 }
1615             } else {              
1616                 if (displayRatioChanged) {
1617                     requestClipThumbnail(clip->getId());
1618                 }
1619                 else if (!item->hasPixmap()) {
1620                     getCachedThumbnail(item);
1621                 }
1622                 if (item->data(0, DurationRole).toString().isEmpty()) {
1623                     item->changeDuration(clip->getProducer()->get_playtime());
1624                 }
1625                 if (clip->isPlaceHolder()) {
1626                     QPixmap pixmap = qVariantValue<QPixmap>(item->data(0, Qt::DecorationRole));
1627                     if (pixmap.isNull()) {
1628                         pixmap = QPixmap(width, height);
1629                         pixmap.fill(Qt::transparent);
1630                     }
1631                     QPainter p(&pixmap);
1632                     p.drawPixmap(3, 3, KIcon("dialog-close").pixmap(pixmap.width() - 6, pixmap.height() - 6));
1633                     p.end();
1634                     item->setPixmap(pixmap);
1635                 }
1636                 else if (clip->getProperty("_replaceproxy") == "1") {
1637                     clip->setProperty("_replaceproxy", QString());
1638                     slotCreateProxy(clip->getId());
1639                 }
1640             }
1641             item->setData(0, UsageRole, QString::number(item->numReferences()));
1642         }
1643         ++it;
1644     }
1645
1646     m_listView->setSortingEnabled(true);
1647     m_allClipsProcessed = true;
1648     if (m_render->processingItems() == 0) {
1649        monitorItemEditing(true);
1650        slotProcessNextThumbnail();
1651     }
1652 }
1653
1654 // static
1655 QString ProjectList::getExtensions()
1656 {
1657     // Build list of mime types
1658     QStringList mimeTypes = QStringList() << "application/x-kdenlive" << "application/x-kdenlivetitle" << "video/mlt-playlist" << "text/plain";
1659
1660     // Video mimes
1661     mimeTypes <<  "video/x-flv" << "application/vnd.rn-realmedia" << "video/x-dv" << "video/dv" << "video/x-msvideo" << "video/x-matroska" << "video/mpeg" << "video/ogg" << "video/x-ms-wmv" << "video/mp4" << "video/quicktime" << "video/webm" << "video/3gpp" << "video/mp2t";
1662
1663     // Audio mimes
1664     mimeTypes << "audio/x-flac" << "audio/x-matroska" << "audio/mp4" << "audio/mpeg" << "audio/x-mp3" << "audio/ogg" << "audio/x-wav" << "audio/x-aiff" << "audio/aiff" << "application/ogg" << "application/mxf" << "application/x-shockwave-flash" << "audio/ac3";
1665
1666     // Image mimes
1667     mimeTypes << "image/gif" << "image/jpeg" << "image/png" << "image/x-tga" << "image/x-bmp" << "image/svg+xml" << "image/tiff" << "image/x-xcf" << "image/x-xcf-gimp" << "image/x-vnd.adobe.photoshop" << "image/x-pcx" << "image/x-exr";
1668
1669     QString allExtensions;
1670     foreach(const QString & mimeType, mimeTypes) {
1671         KMimeType::Ptr mime(KMimeType::mimeType(mimeType));
1672         if (mime) {
1673             allExtensions.append(mime->patterns().join(" "));
1674             allExtensions.append(' ');
1675         }
1676     }
1677     return allExtensions.simplified();
1678 }
1679
1680 void ProjectList::slotAddClip(const QString url, const QString &groupName, const QString &groupId)
1681 {
1682     kDebug()<<"// Adding clip: "<<url;
1683     QList <QUrl> list;
1684     list.append(url);
1685     slotAddClip(list, groupName, groupId);
1686 }
1687
1688 void ProjectList::slotAddClip(const QList <QUrl> givenList, const QString &groupName, const QString &groupId)
1689 {
1690     if (!m_commandStack)
1691         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1692
1693     KUrl::List list;
1694     if (givenList.isEmpty()) {
1695         QString allExtensions = getExtensions();
1696         const QString dialogFilter = allExtensions + ' ' + QLatin1Char('|') + i18n("All Supported Files") + "\n* " + QLatin1Char('|') + i18n("All Files");
1697         QCheckBox *b = new QCheckBox(i18n("Import image sequence"));
1698         b->setChecked(KdenliveSettings::autoimagesequence());
1699         QCheckBox *c = new QCheckBox(i18n("Transparent background for images"));
1700         c->setChecked(KdenliveSettings::autoimagetransparency());
1701         QFrame *f = new QFrame;
1702         f->setFrameShape(QFrame::NoFrame);
1703         QHBoxLayout *l = new QHBoxLayout;
1704         l->addWidget(b);
1705         l->addWidget(c);
1706         l->addStretch(5);
1707         f->setLayout(l);
1708         QPointer<KFileDialog> d = new KFileDialog(KUrl("kfiledialog:///clipfolder"), dialogFilter, kapp->activeWindow(), f);
1709         d->setOperationMode(KFileDialog::Opening);
1710         d->setMode(KFile::Files);
1711         if (d->exec() == QDialog::Accepted) {
1712             KdenliveSettings::setAutoimagetransparency(c->isChecked());
1713         }
1714         list = d->selectedUrls();
1715         if (b->isChecked() && list.count() == 1) {
1716             // Check for image sequence
1717             KUrl url = list.at(0);
1718             QString fileName = url.fileName().section('.', 0, -2);
1719             if (fileName.at(fileName.size() - 1).isDigit()) {
1720                 KFileItem item(KFileItem::Unknown, KFileItem::Unknown, url);
1721                 if (item.mimetype().startsWith("image")) {
1722                     // import as sequence if we found more than one image in the sequence
1723                     QStringList list;
1724                     QString pattern = SlideshowClip::selectedPath(url.path(), false, QString(), &list);
1725                     int count = list.count();
1726                     if (count > 1) {
1727                         delete d;
1728                         QStringList groupInfo = getGroup();
1729
1730                         // get image sequence base name
1731                         while (fileName.at(fileName.size() - 1).isDigit()) {
1732                             fileName.chop(1);
1733                         }
1734                         QMap <QString, QString> properties;
1735                         properties.insert("name", fileName);
1736                         properties.insert("resource", pattern);
1737                         properties.insert("in", "0");
1738                         QString duration = m_timecode.reformatSeparators(KdenliveSettings::sequence_duration());
1739                         properties.insert("out", QString::number(m_doc->getFramePos(duration) * count));
1740                         properties.insert("ttl", QString::number(m_doc->getFramePos(duration)));
1741                         properties.insert("loop", QString::number(false));
1742                         properties.insert("crop", QString::number(false));
1743                         properties.insert("fade", QString::number(false));
1744                         properties.insert("luma_duration", QString::number(m_doc->getFramePos(m_timecode.getTimecodeFromFrames(int(ceil(m_timecode.fps()))))));
1745                         m_doc->slotCreateSlideshowClipFile(properties, groupInfo.at(0), groupInfo.at(1));
1746                         return;
1747                     }
1748                 }
1749             }
1750         }
1751         delete d;
1752     } else {
1753         for (int i = 0; i < givenList.count(); i++)
1754             list << givenList.at(i);
1755     }
1756     QList <KUrl::List> foldersList;
1757
1758     foreach(const KUrl & file, list) {
1759         // Check there is no folder here
1760         KMimeType::Ptr type = KMimeType::findByUrl(file);
1761         if (type->is("inode/directory")) {
1762             // user dropped a folder, import its files
1763             list.removeAll(file);
1764             QDir dir(file.path());
1765             QStringList result = dir.entryList(QDir::Files);
1766             KUrl::List folderFiles;
1767             folderFiles << file;
1768             foreach(const QString & path, result) {
1769                 KUrl newFile = file;
1770                 newFile.addPath(path);
1771                 folderFiles.append(newFile);
1772             }
1773             if (folderFiles.count() > 1) foldersList.append(folderFiles);
1774         }
1775     }
1776
1777     if (givenList.isEmpty() && !list.isEmpty()) {
1778         QStringList groupInfo = getGroup();
1779         QMap <QString, QString> data;
1780         data.insert("group", groupInfo.at(0));
1781         data.insert("groupId", groupInfo.at(1));
1782         m_doc->slotAddClipList(list, data);
1783     } else if (!list.isEmpty()) {
1784         QMap <QString, QString> data;
1785         data.insert("group", groupName);
1786         data.insert("groupId", groupId);
1787         m_doc->slotAddClipList(list, data);
1788     }
1789     
1790     if (!foldersList.isEmpty()) {
1791         // create folders 
1792         for (int i = 0; i < foldersList.count(); i++) {
1793             KUrl::List urls = foldersList.at(i);
1794             KUrl folderUrl = urls.takeFirst();
1795             QString folderName = folderUrl.fileName();
1796             FolderProjectItem *folder = NULL;
1797             if (!folderName.isEmpty()) {
1798                 folder = getFolderItemByName(folderName);
1799                 if (folder == NULL) {
1800                     slotAddFolder(folderName);
1801                     folder = getFolderItemByName(folderName);
1802                 }
1803             }
1804             if (folder) {
1805                 QMap <QString, QString> data;
1806                 data.insert("group", folder->groupName());
1807                 data.insert("groupId", folder->clipId());
1808                 m_doc->slotAddClipList(urls, data);
1809             }
1810             else m_doc->slotAddClipList(urls);
1811         }
1812     }
1813 }
1814
1815 void ProjectList::slotRemoveInvalidClip(const QString &id, bool replace)
1816 {
1817     ProjectItem *item = getItemById(id);
1818     m_thumbnailQueue.removeAll(id);
1819     if (item) {
1820         item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsDropEnabled);
1821         const QString path = item->referencedClip()->fileURL().path();
1822         if (item->referencedClip()->isPlaceHolder()) replace = false;
1823         if (!path.isEmpty()) {
1824             if (m_invalidClipDialog) {
1825                 m_invalidClipDialog->addClip(id, path);
1826                 return;
1827             }
1828             else {
1829                 if (replace)
1830                     m_invalidClipDialog = new InvalidDialog(i18n("Invalid clip"),  i18n("Clip <b>%1</b><br />is invalid, will be removed from project.", QString()), replace, kapp->activeWindow());
1831                 else {
1832                     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());
1833                 }
1834                 m_invalidClipDialog->addClip(id, path);
1835                 int result = m_invalidClipDialog->exec();
1836                 if (result == KDialog::Yes) replace = true;
1837             }
1838         }
1839         if (m_invalidClipDialog) {
1840             if (replace)
1841                 emit deleteProjectClips(m_invalidClipDialog->getIds(), QMap <QString, QString>());
1842             delete m_invalidClipDialog;
1843             m_invalidClipDialog = NULL;
1844         }
1845         
1846     }
1847 }
1848
1849 void ProjectList::slotRemoveInvalidProxy(const QString &id, bool durationError)
1850 {
1851     ProjectItem *item = getItemById(id);
1852     if (item) {
1853         kDebug()<<"// Proxy for clip "<<id<<" is invalid, delete";
1854         item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsDropEnabled);
1855         if (durationError) {
1856             kDebug() << "Proxy duration is wrong, try changing transcoding parameters.";
1857             emit displayMessage(i18n("Proxy clip unusable (duration is different from original)."), -2, ErrorMessage);
1858         }
1859         slotUpdateJobStatus(item, PROXYJOB, JOBCRASHED, i18n("Failed to create proxy for %1. check parameters", item->text(0)), "project_settings");
1860         QString path = item->referencedClip()->getProperty("proxy");
1861         KUrl proxyFolder(m_doc->projectFolder().path( KUrl::AddTrailingSlash) + "proxy/");
1862
1863         //Security check: make sure the invalid proxy file is in the proxy folder
1864         if (proxyFolder.isParentOf(KUrl(path))) {
1865             QFile::remove(path);
1866         }
1867         if (item->referencedClip()->getProducer() == NULL) {
1868             // Clip has no valid producer, request it
1869             slotProxyCurrentItem(false, item);
1870         }
1871         else {
1872             // refresh thumbs producer
1873             item->referencedClip()->reloadThumbProducer();
1874         }
1875     }
1876     m_thumbnailQueue.removeAll(id);
1877 }
1878
1879 void ProjectList::slotAddColorClip()
1880 {
1881     if (!m_commandStack)
1882         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1883
1884     QPointer<QDialog> dia = new QDialog(this);
1885     Ui::ColorClip_UI dia_ui;
1886     dia_ui.setupUi(dia);
1887     dia->setWindowTitle(i18n("Color Clip"));
1888     dia_ui.clip_name->setText(i18n("Color Clip"));
1889
1890     TimecodeDisplay *t = new TimecodeDisplay(m_timecode);
1891     t->setValue(KdenliveSettings::color_duration());
1892     dia_ui.clip_durationBox->addWidget(t);
1893     dia_ui.clip_color->setColor(KdenliveSettings::colorclipcolor());
1894
1895     if (dia->exec() == QDialog::Accepted) {
1896         QString color = dia_ui.clip_color->color().name();
1897         KdenliveSettings::setColorclipcolor(color);
1898         color = color.replace(0, 1, "0x") + "ff";
1899         QStringList groupInfo = getGroup();
1900         m_doc->slotCreateColorClip(dia_ui.clip_name->text(), color, m_timecode.getTimecode(t->gentime()), groupInfo.at(0), groupInfo.at(1));
1901     }
1902     delete t;
1903     delete dia;
1904 }
1905
1906
1907 void ProjectList::slotAddSlideshowClip()
1908 {
1909     if (!m_commandStack)
1910         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1911
1912     SlideshowClip *dia = new SlideshowClip(m_timecode, this);
1913
1914     if (dia->exec() == QDialog::Accepted) {
1915         QStringList groupInfo = getGroup();
1916         
1917         QMap <QString, QString> properties;
1918         properties.insert("name", dia->clipName());
1919         properties.insert("resource", dia->selectedPath());
1920         properties.insert("in", "0");
1921         properties.insert("out", QString::number(m_doc->getFramePos(dia->clipDuration()) * dia->imageCount()));
1922         properties.insert("ttl", QString::number(m_doc->getFramePos(dia->clipDuration())));
1923         properties.insert("loop", QString::number(dia->loop()));
1924         properties.insert("crop", QString::number(dia->crop()));
1925         properties.insert("fade", QString::number(dia->fade()));
1926         properties.insert("luma_duration", dia->lumaDuration());
1927         properties.insert("luma_file", dia->lumaFile());
1928         properties.insert("softness", QString::number(dia->softness()));
1929         properties.insert("animation", dia->animation());
1930         
1931         m_doc->slotCreateSlideshowClipFile(properties, groupInfo.at(0), groupInfo.at(1));
1932     }
1933     delete dia;
1934 }
1935
1936 void ProjectList::slotAddTitleClip()
1937 {
1938     QStringList groupInfo = getGroup();
1939     m_doc->slotCreateTextClip(groupInfo.at(0), groupInfo.at(1));
1940 }
1941
1942 void ProjectList::slotAddTitleTemplateClip()
1943 {
1944     if (!m_commandStack)
1945         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1946
1947     QStringList groupInfo = getGroup();
1948
1949     // Get the list of existing templates
1950     QStringList filter;
1951     filter << "*.kdenlivetitle";
1952     const QString path = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1953     QStringList templateFiles = QDir(path).entryList(filter, QDir::Files);
1954
1955     QPointer<QDialog> dia = new QDialog(this);
1956     Ui::TemplateClip_UI dia_ui;
1957     dia_ui.setupUi(dia);
1958     for (int i = 0; i < templateFiles.size(); ++i)
1959         dia_ui.template_list->comboBox()->addItem(templateFiles.at(i), path + templateFiles.at(i));
1960
1961     if (!templateFiles.isEmpty())
1962         dia_ui.buttonBox->button(QDialogButtonBox::Ok)->setFocus();
1963     dia_ui.template_list->fileDialog()->setFilter("application/x-kdenlivetitle");
1964     //warning: setting base directory doesn't work??
1965     KUrl startDir(path);
1966     dia_ui.template_list->fileDialog()->setUrl(startDir);
1967     dia_ui.text_box->setHidden(true);
1968     if (dia->exec() == QDialog::Accepted) {
1969         QString textTemplate = dia_ui.template_list->comboBox()->itemData(dia_ui.template_list->comboBox()->currentIndex()).toString();
1970         if (textTemplate.isEmpty()) textTemplate = dia_ui.template_list->comboBox()->currentText();
1971         // Create a cloned template clip
1972         m_doc->slotCreateTextTemplateClip(groupInfo.at(0), groupInfo.at(1), KUrl(textTemplate));
1973     }
1974     delete dia;
1975 }
1976
1977 QStringList ProjectList::getGroup() const
1978 {
1979     QStringList result;
1980     QTreeWidgetItem *item = m_listView->currentItem();
1981     while (item && item->type() != PROJECTFOLDERTYPE)
1982         item = item->parent();
1983
1984     if (item) {
1985         FolderProjectItem *folder = static_cast <FolderProjectItem *>(item);
1986         result << folder->groupName() << folder->clipId();
1987     } else {
1988         result << QString() << QString();
1989     }
1990     return result;
1991 }
1992
1993 void ProjectList::setDocument(KdenliveDoc *doc)
1994 {
1995     m_listView->blockSignals(true);
1996     m_abortAllJobs = true;
1997     for (int i = 0; i < m_jobList.count(); i++) {
1998         m_jobList.at(i)->setStatus(JOBABORTED);
1999     }
2000     m_closing = true;
2001     m_jobThreads.waitForFinished();
2002     m_jobThreads.clearFutures();
2003     m_thumbnailQueue.clear();
2004     m_listView->clear();
2005     
2006     m_listView->setSortingEnabled(false);
2007     emit clipSelected(NULL);
2008     m_refreshed = false;
2009     m_allClipsProcessed = false;
2010     m_fps = doc->fps();
2011     m_timecode = doc->timecode();
2012     m_commandStack = doc->commandStack();
2013     m_doc = doc;
2014     m_abortAllJobs = false;
2015     m_closing = false;
2016
2017     QMap <QString, QString> flist = doc->clipManager()->documentFolderList();
2018     QStringList openedFolders = doc->getExpandedFolders();
2019     QMapIterator<QString, QString> f(flist);
2020     while (f.hasNext()) {
2021         f.next();
2022         FolderProjectItem *folder = new FolderProjectItem(m_listView, QStringList() << f.value(), f.key());
2023         folder->setExpanded(openedFolders.contains(f.key()));
2024     }
2025
2026     QList <DocClipBase*> list = doc->clipManager()->documentClipList();
2027     if (list.isEmpty()) {
2028         // blank document
2029         m_refreshed = true;
2030         m_allClipsProcessed = true;
2031     }
2032     for (int i = 0; i < list.count(); i++)
2033         slotAddClip(list.at(i), false);
2034
2035     m_listView->blockSignals(false);
2036     connect(m_doc->clipManager(), SIGNAL(reloadClip(const QString &)), this, SLOT(slotReloadClip(const QString &)));
2037     connect(m_doc->clipManager(), SIGNAL(modifiedClip(const QString &)), this, SLOT(slotModifiedClip(const QString &)));
2038     connect(m_doc->clipManager(), SIGNAL(missingClip(const QString &)), this, SLOT(slotMissingClip(const QString &)));
2039     connect(m_doc->clipManager(), SIGNAL(availableClip(const QString &)), this, SLOT(slotAvailableClip(const QString &)));
2040     connect(m_doc->clipManager(), SIGNAL(checkAllClips(bool, bool, QStringList)), this, SLOT(updateAllClips(bool, bool, QStringList)));
2041     connect(m_doc->clipManager(), SIGNAL(thumbReady(const QString &, int, QImage)), this, SLOT(slotSetThumbnail(const QString &, int, QImage)));
2042 }
2043
2044 void ProjectList::slotSetThumbnail(const QString &id, int framePos, QImage img)
2045 {
2046     QString fullid = id + '#' + QString::number(framePos);
2047     ProjectItem *pItem = NULL;
2048     QTreeWidgetItem *item = getAnyItemById(fullid);
2049     if (item && item->parent()) pItem = static_cast <ProjectItem *>(item->parent());
2050     if (!item && framePos == 0) pItem = getItemById(id);
2051     if (!item && !pItem) return;
2052     if (item) {
2053         if (item->type() == PROJECTCLIPTYPE) static_cast<ProjectItem*>(item)->setPixmap(QPixmap::fromImage(img));
2054         else item->setData(0, Qt::DecorationRole, QPixmap::fromImage(img));
2055     }
2056     else if (pItem) pItem->setPixmap(QPixmap::fromImage(img));
2057     if (pItem) {
2058         QString hash = pItem->getClipHash();
2059         if (!hash.isEmpty()) m_doc->cacheImage(hash + '#' + QString::number(framePos), img);
2060     }
2061 }
2062
2063 QList <DocClipBase*> ProjectList::documentClipList() const
2064 {
2065     if (m_doc == NULL)
2066         return QList <DocClipBase*> ();
2067
2068     return m_doc->clipManager()->documentClipList();
2069 }
2070
2071 QDomElement ProjectList::producersList()
2072 {
2073     QDomDocument doc;
2074     QDomElement prods = doc.createElement("producerlist");
2075     doc.appendChild(prods);
2076     QTreeWidgetItemIterator it(m_listView);
2077     while (*it) {
2078         if ((*it)->type() != PROJECTCLIPTYPE) {
2079             // subitem
2080             ++it;
2081             continue;
2082         }
2083         prods.appendChild(doc.importNode(((ProjectItem *)(*it))->toXml(), true));
2084         ++it;
2085     }
2086     return prods;
2087 }
2088
2089 void ProjectList::slotCheckForEmptyQueue()
2090 {
2091     if (m_render->processingItems() == 0 && m_thumbnailQueue.isEmpty()) {
2092         if (!m_refreshed && m_allClipsProcessed) {
2093             m_refreshed = true;
2094             m_listView->setEnabled(true);
2095             slotClipSelected();
2096             QTimer::singleShot(500, this, SIGNAL(loadingIsOver()));
2097             emit displayMessage(QString(), -1);
2098         }
2099         updateButtons();
2100     } else if (!m_refreshed) {
2101         QTimer::singleShot(300, this, SLOT(slotCheckForEmptyQueue()));
2102     }
2103 }
2104
2105
2106 void ProjectList::requestClipThumbnail(const QString id)
2107 {
2108     if (!m_thumbnailQueue.contains(id)) m_thumbnailQueue.append(id);
2109     slotProcessNextThumbnail();
2110 }
2111
2112 void ProjectList::resetThumbsProducer(DocClipBase *clip)
2113 {
2114     if (!clip) return;
2115     clip->clearThumbProducer();
2116     QString id = clip->getId();
2117     m_thumbnailQueue.removeAll(id);
2118 }
2119
2120 void ProjectList::slotProcessNextThumbnail()
2121 {
2122     if (m_render->processingItems() > 0) {
2123         return;
2124     }
2125     if (m_thumbnailQueue.isEmpty()) {
2126         slotCheckForEmptyQueue();
2127         return;
2128     }
2129     int max = m_doc->clipManager()->clipsCount();
2130     emit displayMessage(i18n("Loading thumbnails"), (int)(100 *(max - m_thumbnailQueue.count()) / max));
2131     slotRefreshClipThumbnail(m_thumbnailQueue.takeFirst(), false);
2132 }
2133
2134 void ProjectList::slotRefreshClipThumbnail(const QString &clipId, bool update)
2135 {
2136     QTreeWidgetItem *item = getAnyItemById(clipId);
2137     if (item)
2138         slotRefreshClipThumbnail(item, update);
2139     else {
2140         slotProcessNextThumbnail();
2141     }
2142 }
2143
2144 void ProjectList::slotRefreshClipThumbnail(QTreeWidgetItem *it, bool update)
2145 {
2146     if (it == NULL) return;
2147     ProjectItem *item = NULL;
2148     bool isSubItem = false;
2149     int frame;
2150     if (it->type() == PROJECTFOLDERTYPE) return;
2151     if (it->type() == PROJECTSUBCLIPTYPE) {
2152         item = static_cast <ProjectItem *>(it->parent());
2153         frame = static_cast <SubProjectItem *>(it)->zone().x();
2154         isSubItem = true;
2155     } else {
2156         item = static_cast <ProjectItem *>(it);
2157         frame = item->referencedClip()->getClipThumbFrame();
2158     }
2159
2160     if (item) {
2161         DocClipBase *clip = item->referencedClip();
2162         if (!clip) {
2163             slotProcessNextThumbnail();
2164             return;
2165         }
2166         QImage img;
2167         int height = m_listView->iconSize().height();
2168         int swidth = (int)(height  * m_render->frameRenderWidth() / m_render->renderHeight()+ 0.5);
2169         int dwidth = (int)(height  * m_render->dar() + 0.5);
2170         if (clip->clipType() == IMAGE) {
2171             img = KThumb::getFrame(item->referencedClip()->getProducer(), 0, swidth, dwidth, height);
2172         }
2173         else if (clip->clipType() != AUDIO) {
2174             img = item->referencedClip()->extractImage(frame, dwidth, height);
2175         }
2176         if (!img.isNull()) {
2177             monitorItemEditing(false);
2178             QPixmap pix = roundedPixmap(img);
2179             processThumbOverlays(item, pix);
2180             if (isSubItem) it->setData(0, Qt::DecorationRole, pix);
2181             else item->setPixmap(pix);
2182             monitorItemEditing(true);
2183             
2184             QString hash = item->getClipHash();
2185             if (!hash.isEmpty() && !img.isNull()) {
2186                 if (!isSubItem)
2187                     m_doc->cacheImage(hash, img);
2188                 else
2189                     m_doc->cacheImage(hash + '#' + QString::number(frame), img);
2190             }
2191         }
2192         if (update)
2193             emit projectModified();
2194         slotProcessNextThumbnail();
2195     }
2196 }
2197
2198 void ProjectList::extractMetadata(DocClipBase *clip)
2199 {
2200     QMap <QString, QString> props = clip->properties();
2201     if (props.contains("exiftool")) {
2202         // metadata was already extracted
2203         return;
2204     }
2205     QString codecid = props.value("videocodecid").simplified();
2206     if (codecid == "h264") {
2207         QProcess p;
2208         QStringList args;
2209         args << "-g" << "-args" << clip->fileURL().encodedPathAndQuery();
2210         p.start("exiftool", args);
2211         p.waitForFinished();
2212         QString res = p.readAllStandardOutput();
2213         QStringList list = res.split("\n");
2214         QMap <QString, QString> meta;
2215         foreach(QString tagline, list) {
2216             if (!tagline.startsWith("-H264")) continue;
2217             QString tag = tagline.section(':', 1);
2218             if (tag.startsWith("ImageWidth") || tag.startsWith("ImageHeight")) continue;
2219             meta.insert(tag.section('=', 0, 0), tag.section('=', 1));
2220         }
2221         clip->setProperty("exiftool", "1");
2222         if (!meta.isEmpty()) {
2223             clip->setMetadata(meta);
2224             //checkCamcorderFilters(clip, meta);
2225         }
2226     }
2227 }
2228
2229
2230 void ProjectList::slotReplyGetFileProperties(const QString &clipId, Mlt::Producer *producer, const stringMap &properties, const stringMap &metadata, bool replace)
2231 {
2232     QString toReload;
2233     ProjectItem *item = getItemById(clipId);
2234     if (item && producer) {
2235         monitorItemEditing(false);
2236         DocClipBase *clip = item->referencedClip();
2237         if (producer->is_valid()) {
2238             if (clip->isPlaceHolder()) {
2239                 clip->setValid();
2240                 toReload = clipId;
2241             }
2242             item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsDropEnabled);
2243         }
2244         item->setProperties(properties, metadata);
2245         clip->setProducer(producer, replace);
2246         if (KdenliveSettings::use_exiftool()) extractMetadata(clip);
2247         m_render->processingDone(clipId);
2248
2249         // Proxy stuff
2250         QString size = properties.value("frame_size");
2251         if (!useProxy() && clip->getProperty("proxy").isEmpty()) {
2252             item->setConditionalJobStatus(NOJOB, PROXYJOB);
2253             discardJobs(clipId, PROXYJOB);
2254         }
2255         if (useProxy() && generateProxy() && clip->getProperty("proxy") == "-") {
2256             item->setConditionalJobStatus(NOJOB, PROXYJOB);
2257             discardJobs(clipId, PROXYJOB);
2258         }
2259         else if (useProxy() && !item->hasProxy() && !hasPendingJob(item, PROXYJOB)) {
2260             // proxy video and image clips
2261             int maxSize;
2262             CLIPTYPE t = item->clipType();
2263             if (t == IMAGE) maxSize = m_doc->getDocumentProperty("proxyimageminsize").toInt();
2264             else maxSize = m_doc->getDocumentProperty("proxyminsize").toInt();
2265             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)) {
2266                 if (clip->getProperty("proxy").isEmpty()) {
2267                     KUrl proxyPath = m_doc->projectFolder();
2268                     proxyPath.addPath("proxy/");
2269                     proxyPath.addPath(clip->getClipHash() + '.' + (t == IMAGE ? "png" : m_doc->getDocumentProperty("proxyextension")));
2270                     QMap <QString, QString> newProps;
2271                     // insert required duration for proxy
2272                     if (t != IMAGE) newProps.insert("proxy_out", clip->producerProperty("out"));
2273                     newProps.insert("proxy", proxyPath.path());
2274                     QMap <QString, QString> oldProps = clip->properties();
2275                     oldProps.insert("proxy", QString());
2276                     EditClipCommand *command = new EditClipCommand(this, clipId, oldProps, newProps, true);
2277                     m_doc->commandStack()->push(command);
2278                 }
2279             }
2280         }
2281
2282         if (!replace && m_allClipsProcessed && !item->hasPixmap()) {
2283             getCachedThumbnail(item);
2284         }
2285         if (!toReload.isEmpty())
2286             item->slotSetToolTip();
2287     } else {
2288         kDebug() << "////////  COULD NOT FIND CLIP TO UPDATE PRPS...";
2289         m_render->processingDone(clipId);
2290     }
2291     int queue = m_render->processingItems();
2292     if (queue == 0) {
2293         monitorItemEditing(true);
2294         if (item && m_thumbnailQueue.isEmpty()) {
2295             if (!item->hasProxy() || m_render->activeClipId() == item->clipId())
2296                 m_listView->setCurrentItem(item);
2297             bool updatedProfile = false;
2298             if (item->parent()) {
2299                 if (item->parent()->type() == PROJECTFOLDERTYPE)
2300                     static_cast <FolderProjectItem *>(item->parent())->switchIcon();
2301             } else if (KdenliveSettings::checkfirstprojectclip() &&  m_listView->topLevelItemCount() == 1 && m_refreshed && m_allClipsProcessed) {
2302                 // this is the first clip loaded in project, check if we want to adjust project settings to the clip
2303                 updatedProfile = adjustProjectProfileToItem(item);
2304                 if (updatedProfile == false) {
2305                     emit clipSelected(item->referencedClip());
2306                 }
2307             }
2308             if (updatedProfile == false) {
2309                 //emit clipSelected(item->referencedClip());
2310             }
2311         } else {
2312             int max = m_doc->clipManager()->clipsCount();
2313             if (max > 0) emit displayMessage(i18n("Loading clips"), (int)(100 *(max - queue) / max));
2314         }
2315         if (m_allClipsProcessed) emit processNextThumbnail();
2316     }
2317     if (!item) {
2318         // no item for producer, delete it
2319         delete producer;
2320         return;
2321     }
2322     if (replace) toReload = clipId;
2323     if (!toReload.isEmpty())
2324         emit clipNeedsReload(toReload);
2325 }
2326
2327 bool ProjectList::adjustProjectProfileToItem(ProjectItem *item)
2328 {
2329     if (item == NULL) {
2330         if (m_listView->currentItem() && m_listView->currentItem()->type() != PROJECTFOLDERTYPE)
2331             item = static_cast <ProjectItem*>(m_listView->currentItem());
2332     }
2333     if (item == NULL || item->referencedClip() == NULL) {
2334         KMessageBox::information(kapp->activeWindow(), i18n("Cannot find profile from current clip"));
2335         return false;
2336     }
2337     bool profileUpdated = false;
2338     QString size = item->referencedClip()->getProperty("frame_size");
2339     int width = size.section('x', 0, 0).toInt();
2340     int height = size.section('x', -1).toInt();
2341     // Fix some avchd clips tht report a wrong size (1920x1088)
2342     if (height == 1088) height = 1080;
2343     double fps = item->referencedClip()->getProperty("fps").toDouble();
2344     double par = item->referencedClip()->getProperty("aspect_ratio").toDouble();
2345     if (item->clipType() == IMAGE || item->clipType() == AV || item->clipType() == VIDEO) {
2346         if (ProfilesDialog::matchProfile(width, height, fps, par, item->clipType() == IMAGE, m_doc->mltProfile()) == false) {
2347             // get a list of compatible profiles
2348             QMap <QString, QString> suggestedProfiles = ProfilesDialog::getProfilesFromProperties(width, height, fps, par, item->clipType() == IMAGE);
2349             if (!suggestedProfiles.isEmpty()) {
2350                 KDialog *dialog = new KDialog(this);
2351                 dialog->setCaption(i18n("Change project profile"));
2352                 dialog->setButtons(KDialog::Ok | KDialog::Cancel);
2353
2354                 QWidget container;
2355                 QVBoxLayout *l = new QVBoxLayout;
2356                 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));
2357                 l->addWidget(label);
2358                 QListWidget *list = new QListWidget;
2359                 list->setAlternatingRowColors(true);
2360                 QMapIterator<QString, QString> i(suggestedProfiles);
2361                 while (i.hasNext()) {
2362                     i.next();
2363                     QListWidgetItem *item = new QListWidgetItem(i.value(), list);
2364                     item->setData(Qt::UserRole, i.key());
2365                     item->setToolTip(i.key());
2366                 }
2367                 list->setCurrentRow(0);
2368                 l->addWidget(list);
2369                 container.setLayout(l);
2370                 dialog->setButtonText(KDialog::Ok, i18n("Update profile"));
2371                 dialog->setMainWidget(&container);
2372                 if (dialog->exec() == QDialog::Accepted) {
2373                     //Change project profile
2374                     profileUpdated = true;
2375                     if (list->currentItem())
2376                         emit updateProfile(list->currentItem()->data(Qt::UserRole).toString());
2377                 }
2378                 delete list;
2379                 delete label;
2380             } else if (fps > 0) {
2381                 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));
2382             }
2383         }
2384     }
2385     return profileUpdated;
2386 }
2387
2388 QString ProjectList::getDocumentProperty(const QString &key) const
2389 {
2390     return m_doc->getDocumentProperty(key);
2391 }
2392
2393 bool ProjectList::useProxy() const
2394 {
2395     return m_doc->getDocumentProperty("enableproxy").toInt();
2396 }
2397
2398 bool ProjectList::generateProxy() const
2399 {
2400     return m_doc->getDocumentProperty("generateproxy").toInt();
2401 }
2402
2403 bool ProjectList::generateImageProxy() const
2404 {
2405     return m_doc->getDocumentProperty("generateimageproxy").toInt();
2406 }
2407
2408 void ProjectList::slotReplyGetImage(const QString &clipId, const QImage &img)
2409 {
2410     ProjectItem *item = getItemById(clipId);
2411     if (item && !img.isNull()) {
2412         QPixmap pix = roundedPixmap(img);
2413         processThumbOverlays(item, pix);
2414         monitorItemEditing(false);
2415         item->setPixmap(pix);
2416         monitorItemEditing(true);
2417         QString hash = item->getClipHash();
2418         if (!hash.isEmpty()) m_doc->cacheImage(hash, img);
2419     }
2420 }
2421
2422 void ProjectList::slotReplyGetImage(const QString &clipId, const QString &name, int width, int height)
2423 {
2424     // For clips that have a generic icon (like audio clips...)
2425     ProjectItem *item = getItemById(clipId);
2426     QPixmap pix =  KIcon(name).pixmap(QSize(width, height));
2427     if (item && !pix.isNull()) {
2428         monitorItemEditing(false);
2429         item->setData(0, Qt::DecorationRole, pix);
2430         monitorItemEditing(true);
2431     }
2432 }
2433
2434 QTreeWidgetItem *ProjectList::getAnyItemById(const QString &id)
2435 {
2436     QTreeWidgetItemIterator it(m_listView);
2437     QString lookId = id;
2438     if (id.contains('#'))
2439         lookId = id.section('#', 0, 0);
2440
2441     ProjectItem *result = NULL;
2442     while (*it) {
2443         if ((*it)->type() != PROJECTCLIPTYPE) {
2444             // subitem
2445             ++it;
2446             continue;
2447         }
2448         ProjectItem *item = static_cast<ProjectItem *>(*it);
2449         if (item->clipId() == lookId) {
2450             result = item;
2451             break;
2452         }
2453         ++it;
2454     }
2455     if (result == NULL || !id.contains('#')) {
2456         return result;
2457     } else {
2458         for (int i = 0; i < result->childCount(); i++) {
2459             SubProjectItem *sub = static_cast <SubProjectItem *>(result->child(i));
2460             if (sub && sub->zone().x() == id.section('#', 1, 1).toInt())
2461                 return sub;
2462         }
2463     }
2464
2465     return NULL;
2466 }
2467
2468
2469 ProjectItem *ProjectList::getItemById(const QString &id)
2470 {
2471     ProjectItem *item;
2472     QTreeWidgetItemIterator it(m_listView);
2473     while (*it) {
2474         if ((*it)->type() != PROJECTCLIPTYPE) {
2475             // subitem or folder
2476             ++it;
2477             continue;
2478         }
2479         item = static_cast<ProjectItem *>(*it);
2480         if (item->clipId() == id)
2481             return item;
2482         ++it;
2483     }
2484     return NULL;
2485 }
2486
2487 FolderProjectItem *ProjectList::getFolderItemByName(const QString &name)
2488 {
2489     FolderProjectItem *item = NULL;
2490     QList <QTreeWidgetItem *> hits = m_listView->findItems(name, Qt::MatchExactly, 0);
2491     for (int i = 0; i < hits.count(); i++) {
2492         if (hits.at(i)->type() == PROJECTFOLDERTYPE) {
2493             item = static_cast<FolderProjectItem *>(hits.at(i));
2494             break;
2495         }
2496     }
2497     return item;
2498 }
2499
2500 FolderProjectItem *ProjectList::getFolderItemById(const QString &id)
2501 {
2502     FolderProjectItem *item;
2503     QTreeWidgetItemIterator it(m_listView);
2504     while (*it) {
2505         if ((*it)->type() == PROJECTFOLDERTYPE) {
2506             item = static_cast<FolderProjectItem *>(*it);
2507             if (item->clipId() == id)
2508                 return item;
2509         }
2510         ++it;
2511     }
2512     return NULL;
2513 }
2514
2515 void ProjectList::slotSelectClip(const QString &ix)
2516 {
2517     ProjectItem *clip = getItemById(ix);
2518     if (clip) {
2519         m_listView->setCurrentItem(clip);
2520         m_listView->scrollToItem(clip);
2521         m_editButton->defaultAction()->setEnabled(true);
2522         m_deleteButton->defaultAction()->setEnabled(true);
2523         m_reloadAction->setEnabled(true);
2524         m_extractAudioAction->setEnabled(true);
2525         m_transcodeAction->setEnabled(true);
2526         m_clipsActionsMenu->setEnabled(true);
2527         if (clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) {
2528             m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
2529             m_openAction->setEnabled(true);
2530         } else if (clip->clipType() == AUDIO && !KdenliveSettings::defaultaudioapp().isEmpty()) {
2531             m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
2532             m_openAction->setEnabled(true);
2533         } else {
2534             m_openAction->setEnabled(false);
2535         }
2536     }
2537 }
2538
2539 QString ProjectList::currentClipUrl() const
2540 {
2541     ProjectItem *item;
2542     if (!m_listView->currentItem() || m_listView->currentItem()->type() == PROJECTFOLDERTYPE) return QString();
2543     if (m_listView->currentItem()->type() == PROJECTSUBCLIPTYPE) {
2544         // subitem
2545         item = static_cast <ProjectItem*>(m_listView->currentItem()->parent());
2546     } else {
2547         item = static_cast <ProjectItem*>(m_listView->currentItem());
2548     }
2549     if (item == NULL)
2550         return QString();
2551     return item->clipUrl().path();
2552 }
2553
2554 KUrl::List ProjectList::getConditionalUrls(const QString &condition) const
2555 {
2556     KUrl::List result;
2557     ProjectItem *item;
2558     QList<QTreeWidgetItem *> list = m_listView->selectedItems();
2559     for (int i = 0; i < list.count(); i++) {
2560         if (list.at(i)->type() == PROJECTFOLDERTYPE)
2561             continue;
2562         if (list.at(i)->type() == PROJECTSUBCLIPTYPE) {
2563             // subitem
2564             item = static_cast <ProjectItem*>(list.at(i)->parent());
2565         } else {
2566             item = static_cast <ProjectItem*>(list.at(i));
2567         }
2568         if (item == NULL || item->type() == COLOR || item->type() == SLIDESHOW || item->type() == TEXT)
2569             continue;
2570         DocClipBase *clip = item->referencedClip();
2571         if (!condition.isEmpty()) {
2572             if (condition.startsWith("vcodec") && !clip->hasVideoCodec(condition.section('=', 1, 1)))
2573                 continue;
2574             else if (condition.startsWith("acodec") && !clip->hasAudioCodec(condition.section('=', 1, 1)))
2575                 continue;
2576         }
2577         result.append(item->clipUrl());
2578     }
2579     return result;
2580 }
2581
2582 QStringList ProjectList::getConditionalIds(const QString &condition) const
2583 {
2584     QStringList result;
2585     ProjectItem *item;
2586     QList<QTreeWidgetItem *> list = m_listView->selectedItems();
2587     for (int i = 0; i < list.count(); i++) {
2588         if (list.at(i)->type() == PROJECTFOLDERTYPE)
2589             continue;
2590         if (list.at(i)->type() == PROJECTSUBCLIPTYPE) {
2591             // subitem
2592             item = static_cast <ProjectItem*>(list.at(i)->parent());
2593         } else {
2594             item = static_cast <ProjectItem*>(list.at(i));
2595         }
2596         if (item == NULL || item->type() == COLOR || item->type() == SLIDESHOW || item->type() == TEXT)
2597             continue;
2598         DocClipBase *clip = item->referencedClip();
2599         if (!condition.isEmpty()) {
2600             if (condition.startsWith("vcodec") && !clip->hasVideoCodec(condition.section('=', 1, 1)))
2601                 continue;
2602             else if (condition.startsWith("acodec") && !clip->hasAudioCodec(condition.section('=', 1, 1)))
2603                 continue;
2604         }
2605         result.append(item->clipId());
2606     }
2607     return result;
2608 }
2609
2610 void ProjectList::regenerateTemplate(const QString &id)
2611 {
2612     ProjectItem *clip = getItemById(id);
2613     if (clip)
2614         regenerateTemplate(clip);
2615 }
2616
2617 void ProjectList::regenerateTemplate(ProjectItem *clip)
2618 {
2619     //TODO: remove this unused method, only force_reload is necessary
2620     clip->referencedClip()->getProducer()->set("force_reload", 1);
2621 }
2622
2623 QDomDocument ProjectList::generateTemplateXml(QString path, const QString &replaceString)
2624 {
2625     QDomDocument doc;
2626     QFile file(path);
2627     if (!file.open(QIODevice::ReadOnly)) {
2628         kWarning() << "ERROR, CANNOT READ: " << path;
2629         return doc;
2630     }
2631     if (!doc.setContent(&file)) {
2632         kWarning() << "ERROR, CANNOT READ: " << path;
2633         file.close();
2634         return doc;
2635     }
2636     file.close();
2637     QDomNodeList texts = doc.elementsByTagName("content");
2638     for (int i = 0; i < texts.count(); i++) {
2639         QString data = texts.item(i).firstChild().nodeValue();
2640         data.replace("%s", replaceString);
2641         texts.item(i).firstChild().setNodeValue(data);
2642     }
2643     return doc;
2644 }
2645
2646
2647 void ProjectList::slotAddClipCut(const QString &id, int in, int out)
2648 {
2649     ProjectItem *clip = getItemById(id);
2650     if (clip == NULL || clip->referencedClip()->hasCutZone(QPoint(in, out)))
2651         return;
2652     AddClipCutCommand *command = new AddClipCutCommand(this, id, in, out, QString(), true, false);
2653     m_commandStack->push(command);
2654 }
2655
2656 void ProjectList::addClipCut(const QString &id, int in, int out, const QString desc, bool newItem)
2657 {
2658     ProjectItem *clip = getItemById(id);
2659     if (clip) {
2660         DocClipBase *base = clip->referencedClip();
2661         base->addCutZone(in, out);
2662         monitorItemEditing(false);
2663         SubProjectItem *sub = new SubProjectItem(m_render->dar(), clip, in, out, desc);
2664         if (newItem && desc.isEmpty() && !m_listView->isColumnHidden(1)) {
2665             if (!clip->isExpanded())
2666                 clip->setExpanded(true);
2667             m_listView->scrollToItem(sub);
2668             m_listView->editItem(sub, 1);
2669         }
2670         m_doc->clipManager()->requestThumbs(QString('#' + id), QList <int>() << in);
2671         monitorItemEditing(true);
2672     }
2673     emit projectModified();
2674 }
2675
2676 void ProjectList::removeClipCut(const QString &id, int in, int out)
2677 {
2678     ProjectItem *clip = getItemById(id);
2679     if (clip) {
2680         DocClipBase *base = clip->referencedClip();
2681         base->removeCutZone(in, out);
2682         SubProjectItem *sub = getSubItem(clip, QPoint(in, out));
2683         if (sub) {
2684             monitorItemEditing(false);
2685             delete sub;
2686             monitorItemEditing(true);
2687         }
2688     }
2689     emit projectModified();
2690 }
2691
2692 SubProjectItem *ProjectList::getSubItem(ProjectItem *clip, QPoint zone)
2693 {
2694     SubProjectItem *sub = NULL;
2695     if (clip) {
2696         for (int i = 0; i < clip->childCount(); i++) {
2697             QTreeWidgetItem *it = clip->child(i);
2698             if (it->type() == PROJECTSUBCLIPTYPE) {
2699                 sub = static_cast <SubProjectItem*>(it);
2700                 if (sub->zone() == zone)
2701                     break;
2702                 else
2703                     sub = NULL;
2704             }
2705         }
2706     }
2707     return sub;
2708 }
2709
2710 void ProjectList::slotUpdateClipCut(QPoint p)
2711 {
2712     if (!m_listView->currentItem() || m_listView->currentItem()->type() != PROJECTSUBCLIPTYPE)
2713         return;
2714     SubProjectItem *sub = static_cast <SubProjectItem*>(m_listView->currentItem());
2715     ProjectItem *item = static_cast <ProjectItem *>(sub->parent());
2716     EditClipCutCommand *command = new EditClipCutCommand(this, item->clipId(), sub->zone(), p, sub->text(1), sub->text(1), true);
2717     m_commandStack->push(command);
2718 }
2719
2720 void ProjectList::doUpdateClipCut(const QString &id, const QPoint oldzone, const QPoint zone, const QString &comment)
2721 {
2722     ProjectItem *clip = getItemById(id);
2723     SubProjectItem *sub = getSubItem(clip, oldzone);
2724     if (sub == NULL || clip == NULL)
2725         return;
2726     DocClipBase *base = clip->referencedClip();
2727     base->updateCutZone(oldzone.x(), oldzone.y(), zone.x(), zone.y(), comment);
2728     monitorItemEditing(false);
2729     sub->setZone(zone);
2730     sub->setDescription(comment);
2731     monitorItemEditing(true);
2732     emit projectModified();
2733 }
2734
2735 void ProjectList::slotForceProcessing(const QString &id)
2736 {
2737     m_render->forceProcessing(id);
2738 }
2739
2740 void ProjectList::slotAddOrUpdateSequence(const QString frameName)
2741 {
2742     QString fileName = KUrl(frameName).fileName().section('_', 0, -2);
2743     QStringList list;
2744     QString pattern = SlideshowClip::selectedPath(frameName, false, QString(), &list);
2745     int count = list.count();
2746     if (count > 1) {
2747         const QList <DocClipBase *> existing = m_doc->clipManager()->getClipByResource(pattern);
2748         if (!existing.isEmpty()) {
2749             // Sequence already exists, update
2750             QString id = existing.at(0)->getId();
2751             //ProjectItem *item = getItemById(id);
2752             QMap <QString, QString> oldprops;
2753             QMap <QString, QString> newprops;
2754             int ttl = existing.at(0)->getProperty("ttl").toInt();
2755             oldprops["out"] = existing.at(0)->getProperty("out");
2756             newprops["out"] = QString::number(ttl * count - 1);
2757             slotUpdateClipProperties(id, newprops);
2758             EditClipCommand *command = new EditClipCommand(this, id, oldprops, newprops, false);
2759             m_commandStack->push(command);
2760         } else {
2761             // Create sequence
2762             QStringList groupInfo = getGroup();
2763             QMap <QString, QString> properties;
2764             properties.insert("name", fileName);
2765             properties.insert("resource", pattern);
2766             properties.insert("in", "0");
2767             QString duration = m_timecode.reformatSeparators(KdenliveSettings::sequence_duration());
2768             properties.insert("out", QString::number(m_doc->getFramePos(duration) * count));
2769             properties.insert("ttl", QString::number(m_doc->getFramePos(duration)));
2770             properties.insert("loop", QString::number(false));
2771             properties.insert("crop", QString::number(false));
2772             properties.insert("fade", QString::number(false));
2773             properties.insert("luma_duration", m_timecode.getTimecodeFromFrames(int(ceil(m_timecode.fps()))));
2774                         
2775             m_doc->slotCreateSlideshowClipFile(properties, groupInfo.at(0), groupInfo.at(1));
2776         }
2777     } else emit displayMessage(i18n("Sequence not found"), -2, ErrorMessage);
2778 }
2779
2780 QMap <QString, QString> ProjectList::getProxies()
2781 {
2782     QMap <QString, QString> list;
2783     ProjectItem *item;
2784     QTreeWidgetItemIterator it(m_listView);
2785     while (*it) {
2786         if ((*it)->type() != PROJECTCLIPTYPE) {
2787             ++it;
2788             continue;
2789         }
2790         item = static_cast<ProjectItem *>(*it);
2791         if (item && item->referencedClip() != NULL) {
2792             if (item->hasProxy()) {
2793                 QString proxy = item->referencedClip()->getProperty("proxy");
2794                 list.insert(proxy, item->clipUrl().path());
2795             }
2796         }
2797         ++it;
2798     }
2799     return list;
2800 }
2801
2802 void ProjectList::slotCreateProxy(const QString id)
2803 {
2804     ProjectItem *item = getItemById(id);
2805     if (!item || hasPendingJob(item, PROXYJOB) || item->referencedClip()->isPlaceHolder()) return;
2806     QString path = item->referencedClip()->getProperty("proxy");
2807     if (path.isEmpty()) {
2808         slotUpdateJobStatus(item, PROXYJOB, JOBCRASHED, i18n("Failed to create proxy, empty path."));
2809         return;
2810     }
2811     
2812     if (QFileInfo(path).size() > 0) {
2813         // Proxy already created
2814         setJobStatus(item, PROXYJOB, JOBDONE);
2815         slotGotProxy(path);
2816         return;
2817     }
2818     QString sourcePath = item->clipUrl().path();
2819     if (item->clipType() == PLAYLIST) {
2820         // Special case: playlists use the special 'consumer' producer to support resizing
2821         sourcePath.prepend("consumer:");
2822     }
2823     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()));
2824     if (job->isExclusive() && hasPendingJob(item, job->jobType)) {
2825         delete job;
2826         return;
2827     }
2828
2829     m_jobList.append(job);
2830     setJobStatus(item, job->jobType, JOBWAITING, 0, job->statusMessage());
2831     slotCheckJobProcess();
2832 }
2833
2834 void ProjectList::slotCutClipJob(const QString &id, QPoint zone)
2835 {
2836     ProjectItem *item = getItemById(id);
2837     if (!item|| item->referencedClip()->isPlaceHolder()) return;
2838     QString source = item->clipUrl().path();
2839     QString ext = source.section('.', -1);
2840     QString dest = source.section('.', 0, -2) + '_' + QString::number(zone.x()) + '.' + ext;
2841     
2842     double clipFps = item->referencedClip()->getProperty("fps").toDouble();
2843     if (clipFps == 0) clipFps = m_fps;
2844     // if clip and project have different frame rate, adjust in and out
2845     int in = zone.x();
2846     int out = zone.y();
2847     in = GenTime(in, m_timecode.fps()).frames(clipFps);
2848     out = GenTime(out, m_timecode.fps()).frames(clipFps);
2849     int max = GenTime(item->clipMaxDuration(), m_timecode.fps()).frames(clipFps);
2850     int duration = out - in + 1;
2851     QString timeIn = Timecode::getStringTimecode(in, clipFps, true);
2852     QString timeOut = Timecode::getStringTimecode(duration, clipFps, true);
2853     
2854     QPointer<QDialog> d = new QDialog(this);
2855     Ui::CutJobDialog_UI ui;
2856     ui.setupUi(d);
2857     ui.extra_params->setVisible(false);
2858     ui.add_clip->setChecked(KdenliveSettings::add_new_clip());
2859     ui.file_url->fileDialog()->setOperationMode(KFileDialog::Saving);
2860     ui.extra_params->setMaximumHeight(QFontMetrics(font()).lineSpacing() * 5);
2861     ui.file_url->setUrl(KUrl(dest));
2862     ui.button_more->setIcon(KIcon("configure"));
2863     ui.extra_params->setPlainText("-acodec copy -vcodec copy");
2864     QString mess = i18n("Extracting %1 out of %2", timeOut, Timecode::getStringTimecode(max, clipFps, true));
2865     ui.info_label->setText(mess);
2866     if (d->exec() != QDialog::Accepted) {
2867         delete d;
2868         return;
2869     }
2870     dest = ui.file_url->url().path();
2871     bool acceptPath = dest != source;
2872     if (acceptPath && QFileInfo(dest).size() > 0) {
2873         // destination file olready exists, overwrite?
2874         acceptPath = false;
2875     }
2876     while (!acceptPath) {
2877         // Do not allow to save over original clip
2878         if (dest == source) ui.info_label->setText("<b>" + i18n("You cannot overwrite original clip.") + "</b><br>" + mess);
2879         else if (KMessageBox::questionYesNo(this, i18n("Overwrite file %1", dest)) == KMessageBox::Yes) break;
2880         if (d->exec() != QDialog::Accepted) {
2881             delete d;
2882             return;
2883         }
2884         dest = ui.file_url->url().path();
2885         acceptPath = dest != source;
2886         if (acceptPath && QFileInfo(dest).size() > 0) {
2887             acceptPath = false;
2888         }
2889     }
2890     QString extraParams = ui.extra_params->toPlainText().simplified();
2891     KdenliveSettings::setAdd_new_clip(ui.add_clip->isChecked());
2892     delete d;
2893
2894     QStringList jobParams;
2895     jobParams << dest << item->clipUrl().path() << timeIn << timeOut << QString::number(duration) << QString::number(KdenliveSettings::add_new_clip());
2896     if (!extraParams.isEmpty()) jobParams << extraParams;
2897     CutClipJob *job = new CutClipJob(item->clipType(), id, jobParams);
2898     if (job->isExclusive() && hasPendingJob(item, job->jobType)) {
2899         delete job;
2900         return;
2901     }
2902     m_jobList.append(job);
2903     setJobStatus(item, job->jobType, JOBWAITING, 0, job->statusMessage());
2904
2905     slotCheckJobProcess();
2906 }
2907
2908 void ProjectList::slotTranscodeClipJob(const QString &condition, QString params, QString desc)
2909 {
2910     QStringList existingFiles;
2911     QStringList ids = getConditionalIds(condition);
2912     QStringList destinations;
2913     foreach(const QString &id, ids) {
2914         ProjectItem *item = getItemById(id);
2915         if (!item) continue;
2916         QString newFile = params.section(' ', -1).replace("%1", item->clipUrl().path());
2917         destinations << newFile;
2918         if (QFile::exists(newFile)) existingFiles << newFile;
2919     }
2920     if (!existingFiles.isEmpty()) {
2921         if (KMessageBox::warningContinueCancelList(this, i18n("The transcoding job will overwrite the following files:"), existingFiles) ==  KMessageBox::Cancel) return;
2922     }
2923     
2924     QDialog *d = new QDialog(this);
2925     Ui::CutJobDialog_UI ui;
2926     ui.setupUi(d);
2927     d->setWindowTitle(i18n("Transcoding"));
2928     ui.extra_params->setMaximumHeight(QFontMetrics(font()).lineSpacing() * 5);
2929     if (ids.count() == 1) {
2930         ui.file_url->setUrl(KUrl(destinations.first()));
2931     }
2932     else {
2933         ui.destination_label->setVisible(false);
2934         ui.file_url->setVisible(false);
2935     }
2936     ui.extra_params->setVisible(false);
2937     d->adjustSize();
2938     ui.button_more->setIcon(KIcon("configure"));
2939     ui.add_clip->setChecked(KdenliveSettings::add_new_clip());
2940     ui.extra_params->setPlainText(params.simplified().section(' ', 0, -2));
2941     QString mess = desc;
2942     mess.append(' ' + i18np("(%1 clip)", "(%1 clips)", ids.count()));
2943     ui.info_label->setText(mess);
2944     if (d->exec() != QDialog::Accepted) {
2945         delete d;
2946         return;
2947     }
2948     params = ui.extra_params->toPlainText().simplified();
2949     KdenliveSettings::setAdd_new_clip(ui.add_clip->isChecked());
2950     int index = 0;
2951     foreach(const QString &id, ids) {
2952         ProjectItem *item = getItemById(id);
2953         if (!item || !item->referencedClip()) continue;
2954         QString src = item->clipUrl().path();
2955         QString dest;
2956         if (ids.count() > 1) {
2957             dest = destinations.at(index);
2958             index++;
2959         }
2960         else dest = ui.file_url->url().path();
2961         QStringList jobParams;
2962         jobParams << dest << src << QString() << QString();
2963         double clipFps = item->referencedClip()->getProperty("fps").toDouble();
2964         if (clipFps == 0) clipFps = m_fps;
2965         int max = item->clipMaxDuration();
2966         QString duration = QString::number(max);
2967         jobParams << duration;
2968         jobParams << QString::number(KdenliveSettings::add_new_clip());
2969         jobParams << params;
2970         CutClipJob *job = new CutClipJob(item->clipType(), id, jobParams);
2971         if (job->isExclusive() && hasPendingJob(item, job->jobType)) {
2972             delete job;
2973             continue;
2974         }
2975         m_jobList.append(job);
2976         setJobStatus(item, job->jobType, JOBWAITING, 0, job->statusMessage());
2977     }
2978     delete d;
2979     slotCheckJobProcess();
2980     
2981 }
2982
2983 void ProjectList::slotCheckJobProcess()
2984 {        
2985     if (!m_jobThreads.futures().isEmpty()) {
2986         // Remove inactive threads
2987         QList <QFuture<void> > futures = m_jobThreads.futures();
2988         m_jobThreads.clearFutures();
2989         for (int i = 0; i < futures.count(); i++)
2990             if (!futures.at(i).isFinished()) {
2991                 m_jobThreads.addFuture(futures.at(i));
2992             }
2993     }
2994     if (m_jobList.isEmpty()) return;
2995
2996     m_jobMutex.lock();
2997     int count = 0;
2998     for (int i = 0; i < m_jobList.count(); i++) {
2999         if (m_jobList.at(i)->status() == JOBWORKING || m_jobList.at(i)->status() == JOBWAITING)
3000             count ++;
3001         else {
3002             // remove finished jobs
3003             AbstractClipJob *job = m_jobList.takeAt(i);
3004             job->deleteLater();
3005             i--;
3006         }
3007     }
3008     emit jobCount(count);    
3009     m_jobMutex.unlock();
3010     if (m_jobThreads.futures().isEmpty() || m_jobThreads.futures().count() < KdenliveSettings::proxythreads()) m_jobThreads.addFuture(QtConcurrent::run(this, &ProjectList::slotProcessJobs));
3011 }
3012
3013 void ProjectList::slotAbortProxy(const QString id, const QString path)
3014 {
3015     Q_UNUSED(path)
3016
3017     ProjectItem *item = getItemById(id);
3018     if (!item) return;
3019     if (!item->isProxyRunning()) slotGotProxy(item);
3020     item->setConditionalJobStatus(NOJOB, PROXYJOB);
3021     discardJobs(id, PROXYJOB);
3022 }
3023
3024 void ProjectList::slotProcessJobs()
3025 {
3026     while (!m_jobList.isEmpty() && !m_abortAllJobs) {
3027         emit projectModified();
3028         AbstractClipJob *job = NULL;
3029         int count = 0;
3030         m_jobMutex.lock();
3031         for (int i = 0; i < m_jobList.count(); i++) {
3032             if (m_jobList.at(i)->status() == JOBWAITING) {
3033                 if (job == NULL) {
3034                     m_jobList.at(i)->setStatus(JOBWORKING);
3035                     job = m_jobList.at(i);
3036                 }
3037                 count++;
3038             }
3039             else if (m_jobList.at(i)->status() == JOBWORKING)
3040                 count ++;
3041         }
3042         // Set jobs count
3043         emit jobCount(count);
3044         m_jobMutex.unlock();
3045
3046         if (job == NULL) {
3047             break;
3048         }
3049         QString destination = job->destination();
3050         // Check if the clip is still here
3051         DocClipBase *currentClip = m_doc->clipManager()->getClipById(job->clipId());
3052         //ProjectItem *processingItem = getItemById(job->clipId());
3053         if (currentClip == NULL) {
3054             job->setStatus(JOBDONE);
3055             continue;
3056         }
3057         // Set clip status to started
3058         emit processLog(job->clipId(), 0, job->jobType, job->statusMessage()); 
3059
3060         // Make sure destination path is writable
3061         if (!destination.isEmpty()) {
3062             QFile file(destination);
3063             if (!file.open(QIODevice::WriteOnly)) {
3064                 emit updateJobStatus(job->clipId(), job->jobType, JOBCRASHED, i18n("Cannot write to path: %1", destination));
3065                 job->setStatus(JOBCRASHED);
3066                 continue;
3067             }
3068             file.close();
3069             QFile::remove(destination);
3070         }
3071         connect(job, SIGNAL(jobProgress(QString, int, int)), this, SIGNAL(processLog(QString, int, int)));
3072         connect(job, SIGNAL(cancelRunningJob(const QString, stringMap)), this, SIGNAL(cancelRunningJob(const QString, stringMap)));
3073
3074         if (job->jobType == MLTJOB) {
3075             MeltJob *jb = static_cast<MeltJob *> (job);
3076             jb->setProducer(currentClip->getProducer(), currentClip->fileURL());
3077             if (jb->isProjectFilter())
3078                 connect(job, SIGNAL(gotFilterJobResults(QString,int, int, stringMap,stringMap)), this, SLOT(slotGotFilterJobResults(QString,int, int,stringMap,stringMap)));
3079             else
3080                 connect(job, SIGNAL(gotFilterJobResults(QString,int, int, stringMap,stringMap)), this, SIGNAL(gotFilterJobResults(QString,int, int,stringMap,stringMap)));
3081         }
3082         job->startJob();
3083         if (job->status() == JOBDONE) {
3084             emit updateJobStatus(job->clipId(), job->jobType, JOBDONE);
3085             //TODO: replace with more generic clip replacement framework
3086             if (job->jobType == PROXYJOB) emit gotProxy(job->clipId());
3087             if (job->addClipToProject()) {
3088                 emit addClip(destination, QString(), QString());
3089             }
3090         } else if (job->status() == JOBCRASHED || job->status() == JOBABORTED) {
3091             emit updateJobStatus(job->clipId(), job->jobType, job->status(), job->errorMessage(), QString(), job->logDetails());
3092         }
3093     }
3094     // Thread finished, cleanup & update count
3095     QTimer::singleShot(200, this, SIGNAL(checkJobProcess()));
3096 }
3097
3098
3099 void ProjectList::updateProxyConfig()
3100 {
3101     ProjectItem *item;
3102     QTreeWidgetItemIterator it(m_listView);
3103     QUndoCommand *command = new QUndoCommand();
3104     command->setText(i18n("Update proxy settings"));
3105     QString proxydir = m_doc->projectFolder().path( KUrl::AddTrailingSlash) + "proxy/";
3106     while (*it) {
3107         if ((*it)->type() != PROJECTCLIPTYPE) {
3108             ++it;
3109             continue;
3110         }
3111         item = static_cast<ProjectItem *>(*it);
3112         if (item == NULL) {
3113             ++it;
3114             continue;
3115         }
3116         CLIPTYPE t = item->clipType();
3117         if ((t == VIDEO || t == AV || t == UNKNOWN) && item->referencedClip() != NULL) {
3118             if  (generateProxy() && useProxy() && !hasPendingJob(item, PROXYJOB)) {
3119                 DocClipBase *clip = item->referencedClip();
3120                 if (clip->getProperty("frame_size").section('x', 0, 0).toInt() > m_doc->getDocumentProperty("proxyminsize").toInt()) {
3121                     if (clip->getProperty("proxy").isEmpty()) {
3122                         // We need to insert empty proxy in old properties so that undo will work
3123                         QMap <QString, QString> oldProps;// = clip->properties();
3124                         oldProps.insert("proxy", QString());
3125                         QMap <QString, QString> newProps;
3126                         newProps.insert("proxy", proxydir + item->referencedClip()->getClipHash() + '.' + m_doc->getDocumentProperty("proxyextension"));
3127                         new EditClipCommand(this, clip->getId(), oldProps, newProps, true, command);
3128                     }
3129                 }
3130             }
3131             else if (item->hasProxy()) {
3132                 // remove proxy
3133                 QMap <QString, QString> newProps;
3134                 newProps.insert("proxy", QString());
3135                 // insert required duration for proxy
3136                 newProps.insert("proxy_out", item->referencedClip()->producerProperty("out"));
3137                 new EditClipCommand(this, item->clipId(), item->referencedClip()->currentProperties(newProps), newProps, true, command);
3138             }
3139         }
3140         else if (t == IMAGE && item->referencedClip() != NULL) {
3141             if  (generateImageProxy() && useProxy()) {
3142                 DocClipBase *clip = item->referencedClip();
3143                 int maxImageSize = m_doc->getDocumentProperty("proxyimageminsize").toInt();
3144                 if (clip->getProperty("frame_size").section('x', 0, 0).toInt() > maxImageSize || clip->getProperty("frame_size").section('x', 1, 1).toInt() > maxImageSize) {
3145                     if (clip->getProperty("proxy").isEmpty()) {
3146                         // We need to insert empty proxy in old properties so that undo will work
3147                         QMap <QString, QString> oldProps = clip->properties();
3148                         oldProps.insert("proxy", QString());
3149                         QMap <QString, QString> newProps;
3150                         newProps.insert("proxy", proxydir + item->referencedClip()->getClipHash() + ".png");
3151                         new EditClipCommand(this, clip->getId(), oldProps, newProps, true, command);
3152                     }
3153                 }
3154             }
3155             else if (item->hasProxy()) {
3156                 // remove proxy
3157                 QMap <QString, QString> newProps;
3158                 newProps.insert("proxy", QString());
3159                 new EditClipCommand(this, item->clipId(), item->referencedClip()->properties(), newProps, true, command);
3160             }
3161         }
3162         ++it;
3163     }
3164     if (command->childCount() > 0) m_doc->commandStack()->push(command);
3165     else delete command;
3166 }
3167
3168 void ProjectList::slotProcessLog(const QString id, int progress, int type, const QString message)
3169 {
3170     ProjectItem *item = getItemById(id);
3171     setJobStatus(item, (JOBTYPE) type, JOBWORKING, progress, message);
3172 }
3173
3174 void ProjectList::slotProxyCurrentItem(bool doProxy, ProjectItem *itemToProxy)
3175 {
3176     QList<QTreeWidgetItem *> list;
3177     if (itemToProxy == NULL) list = m_listView->selectedItems();
3178     else list << itemToProxy;
3179
3180     // expand list (folders, subclips) to get real clips
3181     QTreeWidgetItem *listItem;
3182     QList<ProjectItem *> clipList;
3183     for (int i = 0; i < list.count(); i++) {
3184         listItem = list.at(i);
3185         if (listItem->type() == PROJECTFOLDERTYPE) {
3186             for (int j = 0; j < listItem->childCount(); j++) {
3187                 QTreeWidgetItem *sub = listItem->child(j);
3188                 if (sub->type() == PROJECTCLIPTYPE) {
3189                     ProjectItem *item = static_cast <ProjectItem*>(sub);
3190                     if (!clipList.contains(item)) clipList.append(item);
3191                 }
3192             }
3193         }
3194         else if (listItem->type() == PROJECTSUBCLIPTYPE) {
3195             QTreeWidgetItem *sub = listItem->parent();
3196             ProjectItem *item = static_cast <ProjectItem*>(sub);
3197             if (!clipList.contains(item)) clipList.append(item);
3198         }
3199         else if (listItem->type() == PROJECTCLIPTYPE) {
3200             ProjectItem *item = static_cast <ProjectItem*>(listItem);
3201             if (!clipList.contains(item)) clipList.append(item);
3202         }
3203     }
3204     
3205     QUndoCommand *command = new QUndoCommand();
3206     if (doProxy) command->setText(i18np("Add proxy clip", "Add proxy clips", clipList.count()));
3207     else command->setText(i18np("Remove proxy clip", "Remove proxy clips", clipList.count()));
3208     
3209     // Make sure the proxy folder exists
3210     QString proxydir = m_doc->projectFolder().path( KUrl::AddTrailingSlash) + "proxy/";
3211     KStandardDirs::makeDir(proxydir);
3212                 
3213     QMap <QString, QString> newProps;
3214     QMap <QString, QString> oldProps;
3215     if (!doProxy) newProps.insert("proxy", "-");
3216     for (int i = 0; i < clipList.count(); i++) {
3217         ProjectItem *item = clipList.at(i);
3218         CLIPTYPE t = item->clipType();
3219         if ((t == VIDEO || t == AV || t == UNKNOWN || t == IMAGE || t == PLAYLIST) && item->referencedClip()) {
3220             if ((doProxy && item->hasProxy()) || (!doProxy && !item->hasProxy() && item->referencedClip()->getProducer() != NULL)) continue;
3221             DocClipBase *clip = item->referencedClip();
3222             if (!clip || !clip->isClean() || m_render->isProcessing(item->clipId())) {
3223                 kDebug()<<"//// TRYING TO PROXY: "<<item->clipId()<<", but it is busy";
3224                 continue;
3225             }
3226                 
3227             //oldProps = clip->properties();
3228             if (doProxy) {
3229                 newProps.clear();
3230                 QString path = proxydir + clip->getClipHash() + '.' + (t == IMAGE ? "png" : m_doc->getDocumentProperty("proxyextension"));
3231                 // insert required duration for proxy
3232                 newProps.insert("proxy_out", clip->producerProperty("out"));
3233                 newProps.insert("proxy", path);
3234                 // We need to insert empty proxy so that undo will work
3235                 //oldProps.insert("proxy", QString());
3236             }
3237             else if (item->referencedClip()->getProducer() == NULL) {
3238                 // Force clip reload
3239                 kDebug()<<"// CLIP HAD NULL PROD------------";
3240                 newProps.insert("resource", item->referencedClip()->getProperty("resource"));
3241             }
3242             // We need to insert empty proxy so that undo will work
3243             oldProps = clip->currentProperties(newProps);
3244             if (doProxy) oldProps.insert("proxy", "-");
3245             new EditClipCommand(this, item->clipId(), oldProps, newProps, true, command);
3246         }
3247     }
3248     if (command->childCount() > 0) {
3249         m_doc->commandStack()->push(command);
3250     }
3251     else delete command;
3252 }
3253
3254
3255 void ProjectList::slotDeleteProxy(const QString proxyPath)
3256 {
3257     if (proxyPath.isEmpty()) return;
3258     QUndoCommand *proxyCommand = new QUndoCommand();
3259     proxyCommand->setText(i18n("Remove Proxy"));
3260     QTreeWidgetItemIterator it(m_listView);
3261     ProjectItem *item;
3262     while (*it) {
3263         if ((*it)->type() == PROJECTCLIPTYPE) {
3264             item = static_cast <ProjectItem *>(*it);
3265             if (item->referencedClip()->getProperty("proxy") == proxyPath) {
3266                 QMap <QString, QString> props;
3267                 props.insert("proxy", QString());
3268                 new EditClipCommand(this, item->clipId(), item->referencedClip()->currentProperties(props), props, true, proxyCommand);
3269             
3270             }
3271         }
3272         ++it;
3273     }
3274     if (proxyCommand->childCount() == 0)
3275         delete proxyCommand;
3276     else
3277         m_commandStack->push(proxyCommand);
3278     QFile::remove(proxyPath);
3279 }
3280
3281 void ProjectList::setJobStatus(ProjectItem *item, JOBTYPE jobType, CLIPJOBSTATUS status, int progress, const QString &statusMessage)
3282 {
3283     if (item == NULL || (m_abortAllJobs && m_closing)) return;
3284     monitorItemEditing(false);
3285     item->setJobStatus(jobType, status, progress, statusMessage);
3286     if (status == JOBCRASHED) {
3287         DocClipBase *clip = item->referencedClip();
3288         if (!clip) {
3289             kDebug()<<"// PROXY CRASHED";
3290         }
3291         else if (clip->getProducer() == NULL && !clip->isPlaceHolder()) {
3292             // disable proxy and fetch real clip
3293             clip->setProperty("proxy", "-");
3294             QDomElement xml = clip->toXML();
3295             m_render->getFileProperties(xml, clip->getId(), m_listView->iconSize().height(), true);
3296         }
3297         else {
3298             // Disable proxy for this clip
3299             clip->setProperty("proxy", "-");
3300         }
3301     }
3302     monitorItemEditing(true);
3303 }
3304
3305 void ProjectList::monitorItemEditing(bool enable)
3306 {
3307     if (enable) connect(m_listView, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this, SLOT(slotItemEdited(QTreeWidgetItem *, int)));     
3308     else disconnect(m_listView, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this, SLOT(slotItemEdited(QTreeWidgetItem *, int)));     
3309 }
3310
3311 QStringList ProjectList::expandedFolders() const
3312 {
3313     QStringList result;
3314     FolderProjectItem *item;
3315     QTreeWidgetItemIterator it(m_listView);
3316     while (*it) {
3317         if ((*it)->type() != PROJECTFOLDERTYPE) {
3318             ++it;
3319             continue;
3320         }
3321         if ((*it)->isExpanded()) {
3322             item = static_cast<FolderProjectItem *>(*it);
3323             result.append(item->clipId());
3324         }
3325         ++it;
3326     }
3327     return result;
3328 }
3329
3330 void ProjectList::processThumbOverlays(ProjectItem *item, QPixmap &pix)
3331 {
3332     if (item->hasProxy()) {
3333         QPainter p(&pix);
3334         QColor c(220, 220, 10, 200);
3335         QRect r(0, 0, 12, 12);
3336         p.fillRect(r, c);
3337         QFont font = p.font();
3338         font.setBold(true);
3339         p.setFont(font);
3340         p.setPen(Qt::black);
3341         p.drawText(r, Qt::AlignCenter, i18nc("The first letter of Proxy, used as abbreviation", "P"));
3342     }
3343 }
3344
3345 void ProjectList::slotCancelJobs()
3346 {
3347     m_abortAllJobs = true;
3348     for (int i = 0; i < m_jobList.count(); i++) {
3349         m_jobList.at(i)->setStatus(JOBABORTED);
3350     }
3351     m_jobThreads.waitForFinished();
3352     m_jobThreads.clearFutures();
3353     QUndoCommand *command = new QUndoCommand();
3354     command->setText(i18np("Cancel job", "Cancel jobs", m_jobList.count()));
3355     m_jobMutex.lock();
3356     for (int i = 0; i < m_jobList.count(); i++) {
3357         DocClipBase *currentClip = m_doc->clipManager()->getClipById(m_jobList.at(i)->clipId());
3358         if (!currentClip) continue;
3359         QMap <QString, QString> newProps = m_jobList.at(i)->cancelProperties();
3360         if (newProps.isEmpty()) continue;
3361         QMap <QString, QString> oldProps = currentClip->currentProperties(newProps);
3362         new EditClipCommand(this, m_jobList.at(i)->clipId(), oldProps, newProps, true, command);
3363     }
3364     m_jobMutex.unlock();
3365     if (command->childCount() > 0) {
3366         m_doc->commandStack()->push(command);
3367     }
3368     else delete command;
3369     if (!m_jobList.isEmpty()) qDeleteAll(m_jobList);
3370     m_jobList.clear();
3371     m_abortAllJobs = false;
3372     m_infoLabel->slotSetJobCount(0);    
3373 }
3374
3375 void ProjectList::slotCancelRunningJob(const QString id, stringMap newProps)
3376 {
3377     if (newProps.isEmpty() || m_closing) return;
3378     DocClipBase *currentClip = m_doc->clipManager()->getClipById(id);
3379     if (!currentClip) return;
3380     QMap <QString, QString> oldProps = currentClip->currentProperties(newProps);
3381     if (newProps == oldProps) return;
3382     QMapIterator<QString, QString> i(oldProps);
3383     EditClipCommand *command = new EditClipCommand(this, id, oldProps, newProps, true);
3384     m_commandStack->push(command);    
3385 }
3386
3387 bool ProjectList::hasPendingJob(ProjectItem *item, JOBTYPE type)
3388 {
3389     if (!item || !item->referencedClip() || m_abortAllJobs) return false;
3390     AbstractClipJob *job;
3391     QMutexLocker lock(&m_jobMutex);
3392     for (int i = 0; i < m_jobList.count(); i++) {
3393         if (m_abortAllJobs) break;
3394         job = m_jobList.at(i);
3395         if (job->clipId() == item->clipId() && job->jobType == type && (job->status() == JOBWAITING || job->status() == JOBWORKING)) return true;
3396     }
3397     
3398     return false;
3399 }
3400
3401 void ProjectList::deleteJobsForClip(const QString &clipId)
3402 {
3403     QMutexLocker lock(&m_jobMutex);
3404     for (int i = 0; i < m_jobList.count(); i++) {
3405         if (m_jobList.at(i)->clipId() == clipId) {
3406             m_jobList.at(i)->setStatus(JOBABORTED);
3407         }
3408     }
3409 }
3410
3411 void ProjectList::slotUpdateJobStatus(const QString id, int type, int status, const QString label, const QString actionName, const QString details)
3412 {
3413     ProjectItem *item = getItemById(id);
3414     if (!item) return;
3415     slotUpdateJobStatus(item, type, status, label, actionName, details);
3416     
3417 }
3418
3419 void ProjectList::slotUpdateJobStatus(ProjectItem *item, int type, int status, const QString &label, const QString &actionName, const QString details)
3420 {
3421     item->setJobStatus((JOBTYPE) type, (CLIPJOBSTATUS) status);
3422     if (status != JOBCRASHED) return;
3423 #if KDE_IS_VERSION(4,7,0)
3424     QList<QAction *> actions = m_infoMessage->actions();
3425     if (m_infoMessage->isHidden()) {
3426         m_infoMessage->setText(label);
3427         m_infoMessage->setWordWrap(m_infoMessage->text().length() > 35);
3428         m_infoMessage->setMessageType(KMessageWidget::Warning);
3429     }
3430     
3431     if (!actionName.isEmpty()) {
3432         QAction *action = NULL;
3433         QList< KActionCollection * > collections = KActionCollection::allCollections();
3434         for (int i = 0; i < collections.count(); i++) {
3435             KActionCollection *coll = collections.at(i);
3436             action = coll->action(actionName);
3437             if (action) break;
3438         }
3439         if (action && !actions.contains(action)) m_infoMessage->addAction(action);
3440     }
3441     if (!details.isEmpty()) {
3442         m_errorLog.append(details);
3443         if (!actions.contains(m_logAction)) m_infoMessage->addAction(m_logAction);
3444     }
3445     m_infoMessage->animatedShow();
3446 #else
3447     // warning for KDE < 4.7
3448     KPassivePopup *passivePop = new KPassivePopup( this );
3449     passivePop->setAutoDelete(true);
3450     connect(passivePop, SIGNAL(clicked()), this, SLOT(slotClosePopup()));
3451     m_errorLog.append(details);
3452     KVBox *vb = new KVBox( passivePop );
3453     KHBox *vh1 = new KHBox( vb );
3454     KIcon icon("dialog-warning");
3455     QLabel *iconLabel = new QLabel(vh1);
3456     iconLabel->setPixmap(icon.pixmap(m_listView->iconSize()));
3457     (void) new QLabel( label, vh1);
3458     KHBox *box = new KHBox( vb );
3459     QPushButton *but = new QPushButton( "Show log", box );
3460     connect(but, SIGNAL(clicked(bool)), this, SLOT(slotShowJobLog()));
3461
3462     passivePop->setView( vb );
3463     passivePop->show();
3464     
3465 #endif
3466 }
3467
3468 void ProjectList::slotShowJobLog()
3469 {
3470     KDialog d(this);
3471     d.setButtons(KDialog::Close);
3472     QTextEdit t(&d);
3473     for (int i = 0; i < m_errorLog.count(); i++) {
3474         if (i > 0) t.insertHtml("<br><hr /><br>");
3475         t.insertPlainText(m_errorLog.at(i));
3476     }
3477     t.setReadOnly(true);
3478     d.setMainWidget(&t);
3479     d.exec();
3480 }
3481
3482 QStringList ProjectList::getPendingJobs(const QString &id)
3483 {
3484     QStringList result;
3485     QMutexLocker lock(&m_jobMutex);
3486     for (int i = 0; i < m_jobList.count(); i++) {
3487         if (m_jobList.at(i)->clipId() == id && (m_jobList.at(i)->status() == JOBWAITING || m_jobList.at(i)->status() == JOBWORKING)) {
3488             // discard this job
3489             result << m_jobList.at(i)->description;
3490         }
3491     }   
3492     return result;
3493 }
3494
3495 void ProjectList::discardJobs(const QString &id, JOBTYPE type) {
3496     QMutexLocker lock(&m_jobMutex);
3497     for (int i = 0; i < m_jobList.count(); i++) {
3498         if (m_jobList.at(i)->clipId() == id && (m_jobList.at(i)->jobType == type || type == NOJOBTYPE)) {
3499             // discard this job
3500             m_jobList.at(i)->setStatus(JOBABORTED);
3501         }
3502     }
3503 }
3504
3505 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)
3506 {
3507     ProjectItem *item = getItemById(id);
3508     if (!item) return;
3509     QStringList jobParams;
3510     jobParams << QString::number(info.cropStart.frames(m_fps)) << QString::number((info.cropStart + info.cropDuration).frames(m_fps));
3511     jobParams << QString() << filterName << filterParams << consumer << consumerParams << QString::number(info.startPos.frames(m_fps)) << QString::number(info.track);
3512     MeltJob *job = new MeltJob(item->clipType(), id, jobParams, extraParams);
3513     if (job->isExclusive() && hasPendingJob(item, job->jobType)) {
3514         delete job;
3515         return;
3516     }
3517     job->description = i18n("Filter %1", extraParams.value("finalfilter"));
3518     m_jobList.append(job);
3519     setJobStatus(item, job->jobType, JOBWAITING, 0, job->statusMessage());
3520     slotCheckJobProcess();
3521 }
3522
3523 void ProjectList::startClipFilterJob(const QString &filterName, const QString &condition)
3524 {
3525     QStringList ids = getConditionalIds(condition);
3526     QString destination;
3527     ProjectItem *item = getItemById(ids.at(0));
3528     if (!item) {
3529         emit displayMessage(i18n("Cannot find clip to process filter %1", filterName), -2, ErrorMessage);
3530         return;
3531     }
3532     if (ids.count() == 1) {
3533         destination = item->clipUrl().path();
3534     }
3535     else {
3536         destination = item->clipUrl().directory();
3537     }
3538     if (filterName == "motion_est") {
3539         // Show config dialog
3540         QPointer<QDialog> d = new QDialog(this);
3541         Ui::SceneCutDialog_UI ui;
3542         ui.setupUi(d);
3543         // Set  up categories
3544         for (int i = 0; i < 5; ++i) {
3545             ui.marker_type->insertItem(i, i18n("Category %1", i));
3546             ui.marker_type->setItemData(i, CommentedTime::markerColor(i), Qt::DecorationRole);
3547         }
3548         ui.marker_type->setCurrentIndex(KdenliveSettings::default_marker_type());
3549         if (d->exec() != QDialog::Accepted) {
3550             delete d;
3551             return;
3552         }
3553         // Autosplit filter
3554         QStringList jobParams;
3555         // Producer params
3556         jobParams << QString();
3557         // Filter params, use a smaller region of the image to speed up operation
3558         // In fact, it's faster to rescale whole image than using part of it (bounding=\"25%x25%:15%x15\")
3559         jobParams << filterName << "shot_change_list=0 denoise=0";
3560         // Consumer
3561         jobParams << "null" << "all=1 terminate_on_pause=1 real_time=-1 rescale=nearest deinterlace_method=onefield top_field_first=-1";
3562         QMap <QString, QString> extraParams;
3563         extraParams.insert("key", "shot_change_list");
3564         extraParams.insert("projecttreefilter", "1");
3565         QString keyword("%count");
3566         extraParams.insert("resultmessage", i18n("Found %1 scenes.", keyword));
3567         extraParams.insert("resize_profile", "160");
3568         if (ui.store_data->isChecked()) {
3569             // We want to save result as clip metadata
3570             extraParams.insert("storedata", "1");
3571         }
3572         if (ui.zone_only->isChecked()) {
3573             // We want to analyze only clip zone
3574             extraParams.insert("zoneonly", "1");
3575         }
3576         if (ui.add_markers->isChecked()) {
3577             // We want to create markers
3578             extraParams.insert("addmarkers", QString::number(ui.marker_type->currentIndex()));
3579         }
3580         if (ui.cut_scenes->isChecked()) {
3581             // We want to cut scenes
3582             extraParams.insert("cutscenes", "1");
3583         }
3584         delete d;
3585         processClipJob(ids, QString(), false, jobParams, i18n("Auto split"), extraParams);
3586     }
3587     else {
3588         QPointer<ClipStabilize> d = new ClipStabilize(destination, ids.count(), filterName);
3589         if (d->exec() == QDialog::Accepted) {
3590             QMap <QString, QString> extraParams;
3591             extraParams.insert("producer_profile", "1");
3592             processClipJob(ids, d->destination(), d->autoAddClip(), d->params(), d->desc(), extraParams);
3593         }
3594         delete d;
3595     }
3596 }
3597
3598 void ProjectList::processClipJob(QStringList ids, const QString&destination, bool autoAdd, QStringList jobParams, const QString &description, QMap <QString, QString> extraParams)
3599 {
3600     QStringList preParams;
3601     // in and out
3602     preParams << QString::number(0) << QString::number(-1);
3603     // producer params
3604     preParams << jobParams.takeFirst();
3605     // filter name
3606     preParams << jobParams.takeFirst();
3607     // filter params
3608     preParams << jobParams.takeFirst();
3609     // consumer
3610     QString consumer = jobParams.takeFirst();
3611     
3612     foreach(const QString&id, ids) {
3613         ProjectItem *item = getItemById(id);
3614         if (!item) continue;
3615         QStringList jobArgs;
3616         if (extraParams.contains("zoneonly")) {
3617             // Analyse clip zone only, remove in / out and replace with zone
3618             preParams.takeFirst();
3619             preParams.takeFirst();
3620             QPoint zone = item->referencedClip()->zone();
3621             jobArgs << QString::number(zone.x()) << QString::number(zone.y());
3622         }
3623         jobArgs << preParams;
3624         if (ids.count() == 1) {
3625             jobArgs << consumer + ':' + destination;
3626         }
3627         else {
3628             jobArgs << consumer + ':' + destination + item->clipUrl().fileName() + ".mlt";
3629         }
3630         jobArgs << jobParams;
3631         
3632         MeltJob *job = new MeltJob(item->clipType(), id, jobArgs, extraParams);
3633         if (autoAdd) {
3634             job->setAddClipToProject(true);
3635             kDebug()<<"// ADDING TRUE";
3636         }
3637         else kDebug()<<"// ADDING FALSE!!!";
3638           
3639         if (job->isExclusive() && hasPendingJob(item, job->jobType)) {
3640             delete job;
3641             return;
3642         }
3643         job->description = description;
3644         m_jobList.append(job);
3645         setJobStatus(item, job->jobType, JOBWAITING, 0, job->statusMessage());
3646         slotCheckJobProcess();
3647     }
3648 }
3649    
3650
3651 void ProjectList::slotPrepareJobsMenu()
3652 {
3653     ProjectItem *item;
3654     if (!m_listView->currentItem() || m_listView->currentItem()->type() == PROJECTFOLDERTYPE)
3655         return;
3656     if (m_listView->currentItem()->type() == PROJECTSUBCLIPTYPE)
3657         item = static_cast <ProjectItem*>(m_listView->currentItem()->parent());
3658     else
3659         item = static_cast <ProjectItem*>(m_listView->currentItem());
3660     if (item && (item->flags() & Qt::ItemIsDragEnabled)) {
3661         QString id = item->clipId();
3662         m_discardCurrentClipJobs->setData(id);
3663         QStringList jobs = getPendingJobs(id);
3664         m_discardCurrentClipJobs->setEnabled(!jobs.isEmpty());
3665     } else {
3666         m_discardCurrentClipJobs->setData(QString());
3667         m_discardCurrentClipJobs->setEnabled(false);
3668     }
3669 }
3670
3671 void ProjectList::slotDiscardClipJobs()
3672 {
3673     QString id = m_discardCurrentClipJobs->data().toString();
3674     if (id.isEmpty()) return;
3675     discardJobs(id);
3676 }
3677
3678 void ProjectList::updatePalette()
3679 {
3680     m_infoLabel->setStyleSheet(SmallInfoLabel::getStyleSheet(QApplication::palette()));
3681     m_listView->updateStyleSheet();
3682 }
3683
3684 void ProjectList::slotResetInfoMessage()
3685 {
3686 #if KDE_IS_VERSION(4,7,0)
3687     m_errorLog.clear();
3688     QList<QAction *> actions = m_infoMessage->actions();
3689     for (int i = 0; i < actions.count(); i++) {
3690         m_infoMessage->removeAction(actions.at(i));
3691     }
3692 #endif
3693 }
3694
3695 void ProjectList::slotClosePopup()
3696 {
3697     m_errorLog.clear();
3698 }
3699
3700 void ProjectList::slotGotFilterJobResults(QString id, int , int , stringMap results, stringMap filterInfo)
3701 {
3702     // Currently, only the first value of results is used
3703     //kDebug()<<"// FILTER RES:\n"<<filterInfo<<"\n--------------\n"<<results;
3704     ProjectItem *clip = getItemById(id);
3705     if (!clip) return;
3706
3707     // Check for return value
3708     int markersType = -1;
3709     if (filterInfo.contains("addmarkers")) markersType = filterInfo.value("addmarkers").toInt();
3710     if (results.isEmpty()) {
3711         emit displayMessage(i18n("No data returned from clip analysis"), 0, ErrorMessage);
3712         return;
3713     }
3714     bool dataProcessed = false;
3715     QString key = filterInfo.value("key");
3716     int offset = filterInfo.value("offset").toInt();
3717     QStringList value = results.value(key).split(';', QString::SkipEmptyParts);
3718     kDebug()<<"// RESULT; "<<key<<" = "<<value;
3719     if (filterInfo.contains("resultmessage")) {
3720         QString mess = filterInfo.value("resultmessage");
3721         mess.replace("%count", QString::number(value.count()));
3722         emit displayMessage(mess, 0, InformationMessage);
3723     }
3724     else emit displayMessage(i18n("Processing data analysis"), 0, InformationMessage);
3725     if (filterInfo.contains("cutscenes")) {
3726         // Check if we want to cut scenes from returned data
3727         dataProcessed = true;
3728         int cutPos = 0;
3729         QUndoCommand *command = new QUndoCommand();
3730         command->setText(i18n("Auto Split Clip"));
3731         foreach (QString pos, value) {
3732             if (!pos.contains("=")) continue;
3733             int newPos = pos.section("=", 0, 0).toInt();
3734             // Don't use scenes shorter than 1 second
3735             if (newPos - cutPos < 24) continue;
3736             (void) new AddClipCutCommand(this, id, cutPos + offset, newPos + offset, QString(), true, false, command);
3737             cutPos = newPos;
3738         }
3739         if (command->childCount() == 0)
3740             delete command;
3741         else m_commandStack->push(command);
3742     }
3743     if (markersType >= 0) {
3744         // Add markers from returned data
3745         dataProcessed = true;
3746         int cutPos = 0;
3747         QUndoCommand *command = new QUndoCommand();
3748         command->setText(i18n("Add Markers"));
3749         QList <CommentedTime> markersList;
3750         int index = 1;
3751         foreach (QString pos, value) {
3752             if (!pos.contains("=")) continue;
3753             int newPos = pos.section("=", 0, 0).toInt();
3754             // Don't use scenes shorter than 1 second
3755             if (newPos - cutPos < 24) continue;
3756             CommentedTime m(GenTime(newPos + offset, m_fps), QString::number(index), markersType);
3757             markersList << m;
3758             index++;
3759             cutPos = newPos;
3760         }
3761         emit addMarkers(id, markersList);
3762     }
3763     if (!dataProcessed || filterInfo.contains("storedata")) {
3764         // Store returned data as clip extra data
3765         clip->referencedClip()->setAnalysisData(filterInfo.contains("displaydataname") ? filterInfo.value("displaydataname") : key, results.value(key), filterInfo.value("offset").toInt());
3766         emit updateAnalysisData(clip->referencedClip());
3767     }
3768 }
3769
3770
3771 /*
3772 // Work in progress: apply filter based on clip's camcorder
3773 void ProjectList::checkCamcorderFilters(DocClipBase *clip, QMap <QString, QString> meta)
3774 {
3775     KConfig conf("camcorderfilters.rc", KConfig::CascadeConfig, "appdata");
3776     QStringList groups = conf.groupList();
3777     foreach(QString grp, groups) {
3778         if (!meta.contains(grp)) continue;
3779         KConfigGroup group(&conf, grp);
3780         QString value = group.readEntry(meta.value(grp));
3781         if (value.isEmpty()) continue;
3782         clip->setProperty(value.section(' ', 0, 0), value.section(' ', 1));
3783         break;
3784     }
3785 }*/
3786
3787 #include "projectlist.moc"