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