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