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