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