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