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