]> git.sesse.net Git - kdenlive/blob - src/projectlist.cpp
Set document modified when enabling / disabling individual proxy
[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 "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 "editclipcommand.h"
37 #include "editclipcutcommand.h"
38 #include "editfoldercommand.h"
39 #include "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
70 ProjectList::ProjectList(QWidget *parent) :
71     QWidget(parent),
72     m_render(NULL),
73     m_fps(-1),
74     m_commandStack(NULL),
75     m_openAction(NULL),
76     m_reloadAction(NULL),
77     m_transcodeAction(NULL),
78     m_doc(NULL),
79     m_refreshed(false),
80     m_infoQueue(),
81     m_thumbnailQueue()
82 {
83     QVBoxLayout *layout = new QVBoxLayout;
84     layout->setContentsMargins(0, 0, 0, 0);
85     layout->setSpacing(0);
86     qRegisterMetaType<QDomElement>("QDomElement");
87     // setup toolbar
88     QFrame *frame = new QFrame;
89     frame->setFrameStyle(QFrame::NoFrame);
90     QHBoxLayout *box = new QHBoxLayout;
91     KTreeWidgetSearchLine *searchView = new KTreeWidgetSearchLine;
92
93     box->addWidget(searchView);
94     //int s = style()->pixelMetric(QStyle::PM_SmallIconSize);
95     //m_toolbar->setIconSize(QSize(s, s));
96
97     m_addButton = new QToolButton;
98     m_addButton->setPopupMode(QToolButton::MenuButtonPopup);
99     m_addButton->setAutoRaise(true);
100     box->addWidget(m_addButton);
101
102     m_editButton = new QToolButton;
103     m_editButton->setAutoRaise(true);
104     box->addWidget(m_editButton);
105
106     m_deleteButton = new QToolButton;
107     m_deleteButton->setAutoRaise(true);
108     box->addWidget(m_deleteButton);
109     frame->setLayout(box);
110     layout->addWidget(frame);
111
112     m_listView = new ProjectListView;
113     layout->addWidget(m_listView);
114     setLayout(layout);
115     searchView->setTreeWidget(m_listView);
116
117     m_proxyAction = new QAction(i18n("Proxy clip"), this);
118     m_proxyAction->setCheckable(true);
119     m_proxyAction->setChecked(false);
120     connect(m_proxyAction, SIGNAL(toggled(bool)), this, SLOT(slotProxyCurrentItem(bool)));
121     connect(this, SIGNAL(processNextThumbnail()), this, SLOT(slotProcessNextThumbnail()));
122     connect(m_listView, SIGNAL(projectModified()), this, SIGNAL(projectModified()));
123     connect(m_listView, SIGNAL(itemSelectionChanged()), this, SLOT(slotClipSelected()));
124     connect(m_listView, SIGNAL(focusMonitor()), this, SLOT(slotClipSelected()));
125     connect(m_listView, SIGNAL(pauseMonitor()), this, SLOT(slotPauseMonitor()));
126     connect(m_listView, SIGNAL(requestMenu(const QPoint &, QTreeWidgetItem *)), this, SLOT(slotContextMenu(const QPoint &, QTreeWidgetItem *)));
127     connect(m_listView, SIGNAL(addClip()), this, SLOT(slotAddClip()));
128     connect(m_listView, SIGNAL(addClip(const QList <QUrl>, const QString &, const QString &)), this, SLOT(slotAddClip(const QList <QUrl>, const QString &, const QString &)));
129     connect(m_listView, SIGNAL(addClipCut(const QString &, int, int)), this, SLOT(slotAddClipCut(const QString &, int, int)));
130     connect(m_listView, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this, SLOT(slotItemEdited(QTreeWidgetItem *, int)));
131     connect(m_listView, SIGNAL(showProperties(DocClipBase *)), this, SIGNAL(showClipProperties(DocClipBase *)));
132
133     m_listViewDelegate = new ItemDelegate(m_listView);
134     m_listView->setItemDelegate(m_listViewDelegate);
135 #ifdef NEPOMUK
136     if (KdenliveSettings::activate_nepomuk()) {
137         Nepomuk::ResourceManager::instance()->init();
138         if (!Nepomuk::ResourceManager::instance()->initialized()) {
139             kDebug() << "Cannot communicate with Nepomuk, DISABLING it";
140             KdenliveSettings::setActivate_nepomuk(false);
141         }
142     }
143 #endif
144 }
145
146 ProjectList::~ProjectList()
147 {
148     delete m_menu;
149     m_listView->blockSignals(true);
150     m_listView->clear();
151     delete m_listViewDelegate;
152 }
153
154 void ProjectList::focusTree() const
155 {
156     m_listView->setFocus();
157 }
158
159 void ProjectList::setupMenu(QMenu *addMenu, QAction *defaultAction)
160 {
161     QList <QAction *> actions = addMenu->actions();
162     for (int i = 0; i < actions.count(); i++) {
163         if (actions.at(i)->data().toString() == "clip_properties") {
164             m_editButton->setDefaultAction(actions.at(i));
165             actions.removeAt(i);
166             i--;
167         } else if (actions.at(i)->data().toString() == "delete_clip") {
168             m_deleteButton->setDefaultAction(actions.at(i));
169             actions.removeAt(i);
170             i--;
171         } else if (actions.at(i)->data().toString() == "edit_clip") {
172             m_openAction = actions.at(i);
173             actions.removeAt(i);
174             i--;
175         } else if (actions.at(i)->data().toString() == "reload_clip") {
176             m_reloadAction = actions.at(i);
177             actions.removeAt(i);
178             i--;
179         }
180     }
181
182     QMenu *m = new QMenu();
183     m->addActions(actions);
184     m_addButton->setMenu(m);
185     m_addButton->setDefaultAction(defaultAction);
186     m_menu = new QMenu();
187     m_menu->addActions(addMenu->actions());
188 }
189
190 void ProjectList::setupGeneratorMenu(QMenu *addMenu, QMenu *transcodeMenu, QMenu *inTimelineMenu)
191 {
192     if (!addMenu)
193         return;
194     QMenu *menu = m_addButton->menu();
195     menu->addMenu(addMenu);
196     m_addButton->setMenu(menu);
197
198     m_menu->addMenu(addMenu);
199     if (addMenu->isEmpty())
200         addMenu->setEnabled(false);
201     m_menu->addMenu(transcodeMenu);
202     if (transcodeMenu->isEmpty())
203         transcodeMenu->setEnabled(false);
204     m_transcodeAction = transcodeMenu;
205     m_menu->addAction(m_reloadAction);
206     m_menu->addAction(m_proxyAction);
207     m_menu->addMenu(inTimelineMenu);
208     inTimelineMenu->setEnabled(false);
209     m_menu->addAction(m_editButton->defaultAction());
210     m_menu->addAction(m_openAction);
211     m_menu->addAction(m_deleteButton->defaultAction());
212     m_menu->insertSeparator(m_deleteButton->defaultAction());
213 }
214
215
216 QByteArray ProjectList::headerInfo() const
217 {
218     return m_listView->header()->saveState();
219 }
220
221 void ProjectList::setHeaderInfo(const QByteArray &state)
222 {
223     m_listView->header()->restoreState(state);
224 }
225
226 void ProjectList::updateProjectFormat(Timecode t)
227 {
228     m_timecode = t;
229 }
230
231 void ProjectList::slotEditClip()
232 {
233     QList<QTreeWidgetItem *> list = m_listView->selectedItems();
234     if (list.isEmpty()) return;
235     if (list.count() > 1 || list.at(0)->type() == PROJECTFOLDERTYPE) {
236         editClipSelection(list);
237         return;
238     }
239     ProjectItem *item;
240     if (!m_listView->currentItem() || m_listView->currentItem()->type() == PROJECTFOLDERTYPE)
241         return;
242     if (m_listView->currentItem()->type() == PROJECTSUBCLIPTYPE)
243         item = static_cast <ProjectItem*>(m_listView->currentItem()->parent());
244     else
245         item = static_cast <ProjectItem*>(m_listView->currentItem());
246     if (item && (item->flags() & Qt::ItemIsDragEnabled)) {
247         emit clipSelected(item->referencedClip());
248         emit showClipProperties(item->referencedClip());
249     }
250 }
251
252 void ProjectList::editClipSelection(QList<QTreeWidgetItem *> list)
253 {
254     // Gather all common properties
255     QMap <QString, QString> commonproperties;
256     QList <DocClipBase *> clipList;
257     commonproperties.insert("force_aspect_num", "-");
258     commonproperties.insert("force_aspect_den", "-");
259     commonproperties.insert("force_fps", "-");
260     commonproperties.insert("force_progressive", "-");
261     commonproperties.insert("force_tff", "-");
262     commonproperties.insert("threads", "-");
263     commonproperties.insert("video_index", "-");
264     commonproperties.insert("audio_index", "-");
265     commonproperties.insert("force_colorspace", "-");
266     commonproperties.insert("full_luma", "-");
267     QString transparency = "-";
268
269     bool allowDurationChange = true;
270     int commonDuration = -1;
271     bool hasImages = false;;
272     ProjectItem *item;
273     for (int i = 0; i < list.count(); i++) {
274         item = NULL;
275         if (list.at(i)->type() == PROJECTFOLDERTYPE) {
276             // Add folder items to the list
277             int ct = list.at(i)->childCount();
278             for (int j = 0; j < ct; j++) {
279                 list.append(list.at(i)->child(j));
280             }
281             continue;
282         }
283         else if (list.at(i)->type() == PROJECTSUBCLIPTYPE)
284             item = static_cast <ProjectItem*>(list.at(i)->parent());
285         else
286             item = static_cast <ProjectItem*>(list.at(i));
287         if (!(item->flags() & Qt::ItemIsDragEnabled))
288             continue;
289         if (item) {
290             // check properties
291             DocClipBase *clip = item->referencedClip();
292             if (clipList.contains(clip)) continue;
293             if (clip->clipType() == IMAGE) {
294                 hasImages = true;
295                 if (clip->getProperty("transparency").isEmpty() || clip->getProperty("transparency").toInt() == 0) {
296                     if (transparency == "-") {
297                         // first non transparent image
298                         transparency = "0";
299                     }
300                     else if (transparency == "1") {
301                         // we have transparent and non transparent clips
302                         transparency = "-1";
303                     }
304                 }
305                 else {
306                     if (transparency == "-") {
307                         // first transparent image
308                         transparency = "1";
309                     }
310                     else if (transparency == "0") {
311                         // we have transparent and non transparent clips
312                         transparency = "-1";
313                     }
314                 }
315             }
316             if (clip->clipType() != COLOR && clip->clipType() != IMAGE && clip->clipType() != TEXT)
317                 allowDurationChange = false;
318             if (allowDurationChange && commonDuration != 0) {
319                 if (commonDuration == -1)
320                     commonDuration = clip->duration().frames(m_fps);
321                 else if (commonDuration != clip->duration().frames(m_fps))
322                     commonDuration = 0;
323             }
324             clipList.append(clip);
325             QMap <QString, QString> clipprops = clip->properties();
326             QMapIterator<QString, QString> p(commonproperties);
327             while (p.hasNext()) {
328                 p.next();
329                 if (p.value().isEmpty()) continue;
330                 if (clipprops.contains(p.key())) {
331                     if (p.value() == "-")
332                         commonproperties.insert(p.key(), clipprops.value(p.key()));
333                     else if (p.value() != clipprops.value(p.key()))
334                         commonproperties.insert(p.key(), QString());
335                 } else {
336                     commonproperties.insert(p.key(), QString());
337                 }
338             }
339         }
340     }
341     if (allowDurationChange)
342         commonproperties.insert("out", QString::number(commonDuration));
343     if (hasImages)
344         commonproperties.insert("transparency", transparency);
345     /*QMapIterator<QString, QString> p(commonproperties);
346     while (p.hasNext()) {
347         p.next();
348         kDebug() << "Result: " << p.key() << " = " << p.value();
349     }*/
350     emit showClipProperties(clipList, commonproperties);
351 }
352
353 void ProjectList::slotOpenClip()
354 {
355     ProjectItem *item;
356     if (!m_listView->currentItem() || m_listView->currentItem()->type() == PROJECTFOLDERTYPE)
357         return;
358     if (m_listView->currentItem()->type() == QTreeWidgetItem::UserType + 1)
359         item = static_cast <ProjectItem*>(m_listView->currentItem()->parent());
360     else
361         item = static_cast <ProjectItem*>(m_listView->currentItem());
362     if (item) {
363         if (item->clipType() == IMAGE) {
364             if (KdenliveSettings::defaultimageapp().isEmpty())
365                 KMessageBox::sorry(kapp->activeWindow(), i18n("Please set a default application to open images in the Settings dialog"));
366             else
367                 QProcess::startDetached(KdenliveSettings::defaultimageapp(), QStringList() << item->clipUrl().path());
368         }
369         if (item->clipType() == AUDIO) {
370             if (KdenliveSettings::defaultaudioapp().isEmpty())
371                 KMessageBox::sorry(kapp->activeWindow(), i18n("Please set a default application to open audio files in the Settings dialog"));
372             else
373                 QProcess::startDetached(KdenliveSettings::defaultaudioapp(), QStringList() << item->clipUrl().path());
374         }
375     }
376 }
377
378 void ProjectList::cleanup()
379 {
380     m_listView->clearSelection();
381     QTreeWidgetItemIterator it(m_listView);
382     ProjectItem *item;
383     while (*it) {
384         if ((*it)->type() != PROJECTCLIPTYPE) {
385             it++;
386             continue;
387         }
388         item = static_cast <ProjectItem *>(*it);
389         if (item->numReferences() == 0)
390             item->setSelected(true);
391         it++;
392     }
393     slotRemoveClip();
394 }
395
396 void ProjectList::trashUnusedClips()
397 {
398     QTreeWidgetItemIterator it(m_listView);
399     ProjectItem *item;
400     QStringList ids;
401     QStringList urls;
402     while (*it) {
403         if ((*it)->type() != PROJECTCLIPTYPE) {
404             it++;
405             continue;
406         }
407         item = static_cast <ProjectItem *>(*it);
408         if (item->numReferences() == 0) {
409             ids << item->clipId();
410             KUrl url = item->clipUrl();
411             if (!url.isEmpty() && !urls.contains(url.path()))
412                 urls << url.path();
413         }
414         it++;
415     }
416
417     // Check that we don't use the URL in another clip
418     QTreeWidgetItemIterator it2(m_listView);
419     while (*it2) {
420         if ((*it2)->type() != PROJECTCLIPTYPE) {
421             it2++;
422             continue;
423         }
424         item = static_cast <ProjectItem *>(*it2);
425         if (item->numReferences() > 0) {
426             KUrl url = item->clipUrl();
427             if (!url.isEmpty() && urls.contains(url.path())) urls.removeAll(url.path());
428         }
429         it2++;
430     }
431
432     emit deleteProjectClips(ids, QMap <QString, QString>());
433     for (int i = 0; i < urls.count(); i++)
434         KIO::NetAccess::del(KUrl(urls.at(i)), this);
435 }
436
437 void ProjectList::slotReloadClip(const QString &id)
438 {
439     QList<QTreeWidgetItem *> selected;
440     if (id.isEmpty())
441         selected = m_listView->selectedItems();
442     else {
443         ProjectItem *itemToReLoad = getItemById(id);
444         if (itemToReLoad) selected.append(itemToReLoad);
445     }
446     ProjectItem *item;
447     for (int i = 0; i < selected.count(); i++) {
448         if (selected.at(i)->type() != PROJECTCLIPTYPE) {
449             if (selected.at(i)->type() == PROJECTFOLDERTYPE) {
450                 for (int j = 0; j < selected.at(i)->childCount(); j++)
451                     selected.append(selected.at(i)->child(j));
452             }
453             continue;
454         }
455         item = static_cast <ProjectItem *>(selected.at(i));
456         if (item) {
457             CLIPTYPE t = item->clipType();
458             if (t == TEXT) {
459                 if (!item->referencedClip()->getProperty("xmltemplate").isEmpty())
460                     regenerateTemplate(item);
461             } else if (t != COLOR && t != SLIDESHOW && item->referencedClip() &&  item->referencedClip()->checkHash() == false) {
462                 item->referencedClip()->setPlaceHolder(true);
463                 item->setProperty("file_hash", QString());
464             } else if (t == IMAGE) {
465                 item->referencedClip()->producer()->set("force_reload", 1);
466             }
467
468             QDomElement e = item->toXml();
469             // Make sure we get the correct producer length if it was adjusted in timeline
470             if (t == COLOR || t == IMAGE || t == SLIDESHOW || t == TEXT) {
471                 int length = QString(item->referencedClip()->producerProperty("length")).toInt();
472                 if (length > 0 && !e.hasAttribute("length")) {
473                     e.setAttribute("length", length);
474                 }
475             }            
476             emit getFileProperties(e, item->clipId(), m_listView->iconSize().height(), true, false);
477         }
478     }
479 }
480
481 void ProjectList::slotModifiedClip(const QString &id)
482 {
483     ProjectItem *item = getItemById(id);
484     if (item) {
485         QPixmap pixmap = qVariantValue<QPixmap>(item->data(0, Qt::DecorationRole));
486         if (!pixmap.isNull()) {
487             QPainter p(&pixmap);
488             p.fillRect(0, 0, pixmap.width(), pixmap.height(), QColor(255, 255, 255, 200));
489             p.drawPixmap(0, 0, KIcon("view-refresh").pixmap(m_listView->iconSize()));
490             p.end();
491         } else {
492             pixmap = KIcon("view-refresh").pixmap(m_listView->iconSize());
493         }
494         item->setData(0, Qt::DecorationRole, pixmap);
495     }
496 }
497
498 void ProjectList::slotMissingClip(const QString &id)
499 {
500     ProjectItem *item = getItemById(id);
501     if (item) {
502         item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsDropEnabled);
503         if (item->referencedClip()) {
504             item->referencedClip()->setPlaceHolder(true);
505             if (m_render == NULL) kDebug() << "*********  ERROR, NULL RENDR";
506             item->referencedClip()->setProducer(m_render->invalidProducer(id), true);
507             item->slotSetToolTip();
508             emit clipNeedsReload(id, true);
509         }
510     }
511     update();
512     emit displayMessage(i18n("Check missing clips"), -2);
513     emit updateRenderStatus();
514 }
515
516 void ProjectList::slotAvailableClip(const QString &id)
517 {
518     ProjectItem *item = getItemById(id);
519     if (item == NULL)
520         return;
521     item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsDropEnabled);
522     if (item->referencedClip()) { // && item->referencedClip()->checkHash() == false) {
523         item->setProperty("file_hash", QString());
524         slotReloadClip(id);
525     }
526     /*else {
527     item->referencedClip()->setValid();
528     item->slotSetToolTip();
529     }
530     update();*/
531     emit updateRenderStatus();
532 }
533
534 bool ProjectList::hasMissingClips()
535 {
536     bool missing = false;
537     QTreeWidgetItemIterator it(m_listView);
538     while (*it) {
539         if ((*it)->type() == PROJECTCLIPTYPE && !((*it)->flags() & Qt::ItemIsDragEnabled)) {
540             missing = true;
541             break;
542         }
543         it++;
544     }
545     return missing;
546 }
547
548 void ProjectList::setRenderer(Render *projectRender)
549 {
550     m_render = projectRender;
551     m_listView->setIconSize(QSize((ProjectItem::itemDefaultHeight() - 2) * m_render->dar(), ProjectItem::itemDefaultHeight() - 2));
552 }
553
554 void ProjectList::slotClipSelected()
555 {
556     if (!m_listView->isEnabled()) return;
557     if (m_listView->currentItem()) {
558         if (m_listView->currentItem()->type() == PROJECTFOLDERTYPE) {
559             emit clipSelected(NULL);
560             m_editButton->defaultAction()->setEnabled(m_listView->currentItem()->childCount() > 0);
561             m_deleteButton->defaultAction()->setEnabled(true);
562             m_openAction->setEnabled(false);
563             m_reloadAction->setEnabled(false);
564             m_transcodeAction->setEnabled(false);
565             m_proxyAction->setEnabled(false);
566         } else {
567             ProjectItem *clip;
568             if (m_listView->currentItem()->type() == PROJECTSUBCLIPTYPE) {
569                 // this is a sub item, use base clip
570                 m_deleteButton->defaultAction()->setEnabled(true);
571                 clip = static_cast <ProjectItem*>(m_listView->currentItem()->parent());
572                 if (clip == NULL) kDebug() << "-----------ERROR";
573                 SubProjectItem *sub = static_cast <SubProjectItem*>(m_listView->currentItem());
574                 emit clipSelected(clip->referencedClip(), sub->zone());
575                 m_transcodeAction->setEnabled(false);
576                 return;
577             }
578             clip = static_cast <ProjectItem*>(m_listView->currentItem());
579             if (clip && clip->referencedClip())
580                 emit clipSelected(clip->referencedClip());
581             m_editButton->defaultAction()->setEnabled(true);
582             m_deleteButton->defaultAction()->setEnabled(true);
583             m_reloadAction->setEnabled(true);
584             m_transcodeAction->setEnabled(true);
585             if (clip && clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) {
586                 m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
587                 m_openAction->setEnabled(true);
588             } else if (clip && clip->clipType() == AUDIO && !KdenliveSettings::defaultaudioapp().isEmpty()) {
589                 m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
590                 m_openAction->setEnabled(true);
591             } else {
592                 m_openAction->setEnabled(false);
593             }
594             // Display relevant transcoding actions only
595             adjustTranscodeActions(clip);
596             // Display uses in timeline
597             emit findInTimeline(clip->clipId());
598         }
599     } else {
600         emit clipSelected(NULL);
601         m_editButton->defaultAction()->setEnabled(false);
602         m_deleteButton->defaultAction()->setEnabled(false);
603         m_openAction->setEnabled(false);
604         m_reloadAction->setEnabled(false);
605         m_transcodeAction->setEnabled(false);
606     }
607 }
608
609 void ProjectList::adjustProxyActions(ProjectItem *clip) const
610 {
611     if (clip == NULL || clip->type() != PROJECTCLIPTYPE || clip->clipType() == COLOR || clip->clipType() == TEXT || clip->clipType() == PLAYLIST || clip->clipType() == SLIDESHOW || clip->clipType() == AUDIO) {
612         m_proxyAction->setEnabled(false);
613         return;
614     }
615     m_proxyAction->setEnabled(useProxy());
616     m_proxyAction->blockSignals(true);
617     m_proxyAction->setChecked(clip->hasProxy());
618     m_proxyAction->blockSignals(false);
619 }
620
621 void ProjectList::adjustTranscodeActions(ProjectItem *clip) const
622 {
623     if (clip == NULL || clip->type() != PROJECTCLIPTYPE || clip->clipType() == COLOR || clip->clipType() == TEXT || clip->clipType() == PLAYLIST || clip->clipType() == SLIDESHOW) {
624         m_transcodeAction->setEnabled(false);
625         return;
626     }
627     m_transcodeAction->setEnabled(true);
628     QList<QAction *> transcodeActions = m_transcodeAction->actions();
629     QStringList data;
630     QString condition;
631     for (int i = 0; i < transcodeActions.count(); i++) {
632         data = transcodeActions.at(i)->data().toStringList();
633         if (data.count() > 2) {
634             condition = data.at(2);
635             if (condition.startsWith("vcodec"))
636                 transcodeActions.at(i)->setEnabled(clip->referencedClip()->hasVideoCodec(condition.section('=', 1, 1)));
637             else if (condition.startsWith("acodec"))
638                 transcodeActions.at(i)->setEnabled(clip->referencedClip()->hasVideoCodec(condition.section('=', 1, 1)));
639         }
640     }
641
642 }
643
644 void ProjectList::slotPauseMonitor()
645 {
646     if (m_render)
647         m_render->pause();
648 }
649
650 void ProjectList::slotUpdateClipProperties(const QString &id, QMap <QString, QString> properties)
651 {
652     ProjectItem *item = getItemById(id);
653     if (item) {
654         slotUpdateClipProperties(item, properties);
655         if (properties.contains("out") || properties.contains("force_fps") || properties.contains("resource")) {
656             slotReloadClip(id);
657         } else if (properties.contains("colour") ||
658                    properties.contains("xmldata") ||
659                    properties.contains("force_aspect_num") ||
660                    properties.contains("force_aspect_den") ||
661                    properties.contains("templatetext")) {
662             slotRefreshClipThumbnail(item);
663             emit refreshClip(id, true);
664         } else if (properties.contains("full_luma") || properties.contains("force_colorspace") || properties.contains("loop")) {
665             emit refreshClip(id, false);
666         }
667     }
668 }
669
670 void ProjectList::slotUpdateClipProperties(ProjectItem *clip, QMap <QString, QString> properties)
671 {
672     if (!clip)
673         return;
674     clip->setProperties(properties);
675     if (properties.contains("name")) {
676         monitorItemEditing(false);
677         clip->setText(0, properties.value("name"));
678         monitorItemEditing(true);
679         emit clipNameChanged(clip->clipId(), properties.value("name"));
680     }
681     if (properties.contains("description")) {
682         CLIPTYPE type = clip->clipType();
683         monitorItemEditing(false);
684         clip->setText(1, properties.value("description"));
685         monitorItemEditing(true);
686 #ifdef NEPOMUK
687         if (KdenliveSettings::activate_nepomuk() && (type == AUDIO || type == VIDEO || type == AV || type == IMAGE || type == PLAYLIST)) {
688             // Use Nepomuk system to store clip description
689             Nepomuk::Resource f(clip->clipUrl().path());
690             f.setDescription(properties.value("description"));
691         }
692 #endif
693         emit projectModified();
694     }
695 }
696
697 void ProjectList::slotItemEdited(QTreeWidgetItem *item, int column)
698 {
699     if (item->type() == PROJECTSUBCLIPTYPE) {
700         // this is a sub-item
701         if (column == 1) {
702             // user edited description
703             SubProjectItem *sub = static_cast <SubProjectItem*>(item);
704             ProjectItem *item = static_cast <ProjectItem *>(sub->parent());
705             EditClipCutCommand *command = new EditClipCutCommand(this, item->clipId(), sub->zone(), sub->zone(), sub->description(), sub->text(1), true);
706             m_commandStack->push(command);
707             //slotUpdateCutClipProperties(sub->clipId(), sub->zone(), sub->text(1), sub->text(1));
708         }
709         return;
710     }
711     if (item->type() == PROJECTFOLDERTYPE) {
712         if (column == 0) {
713             FolderProjectItem *folder = static_cast <FolderProjectItem*>(item);
714             editFolder(item->text(0), folder->groupName(), folder->clipId());
715             folder->setGroupName(item->text(0));
716             m_doc->clipManager()->addFolder(folder->clipId(), item->text(0));
717             const int children = item->childCount();
718             for (int i = 0; i < children; i++) {
719                 ProjectItem *child = static_cast <ProjectItem *>(item->child(i));
720                 child->setProperty("groupname", item->text(0));
721             }
722         }
723         return;
724     }
725
726     ProjectItem *clip = static_cast <ProjectItem*>(item);
727     if (column == 1) {
728         if (clip->referencedClip()) {
729             QMap <QString, QString> oldprops;
730             QMap <QString, QString> newprops;
731             oldprops["description"] = clip->referencedClip()->getProperty("description");
732             newprops["description"] = item->text(1);
733
734             if (clip->clipType() == TEXT) {
735                 // This is a text template clip, update the image
736                 /*oldprops.insert("xmldata", clip->referencedClip()->getProperty("xmldata"));
737                 newprops.insert("xmldata", generateTemplateXml(clip->referencedClip()->getProperty("xmltemplate"), item->text(2)).toString());*/
738                 oldprops.insert("templatetext", clip->referencedClip()->getProperty("templatetext"));
739                 newprops.insert("templatetext", item->text(1));
740             }
741             slotUpdateClipProperties(clip->clipId(), newprops);
742             EditClipCommand *command = new EditClipCommand(this, clip->clipId(), oldprops, newprops, false);
743             m_commandStack->push(command);
744         }
745     } else if (column == 0) {
746         if (clip->referencedClip()) {
747             QMap <QString, QString> oldprops;
748             QMap <QString, QString> newprops;
749             oldprops["name"] = clip->referencedClip()->getProperty("name");
750             if (oldprops.value("name") != item->text(0)) {
751                 newprops["name"] = item->text(0);
752                 slotUpdateClipProperties(clip, newprops);
753                 emit projectModified();
754                 EditClipCommand *command = new EditClipCommand(this, clip->clipId(), oldprops, newprops, false);
755                 m_commandStack->push(command);
756             }
757         }
758     }
759 }
760
761 void ProjectList::slotContextMenu(const QPoint &pos, QTreeWidgetItem *item)
762 {
763     bool enable = item ? true : false;
764     m_editButton->defaultAction()->setEnabled(enable);
765     m_deleteButton->defaultAction()->setEnabled(enable);
766     m_reloadAction->setEnabled(enable);
767     m_transcodeAction->setEnabled(enable);
768     if (enable) {
769         ProjectItem *clip = NULL;
770         if (m_listView->currentItem()->type() == PROJECTSUBCLIPTYPE) {
771             clip = static_cast <ProjectItem*>(item->parent());
772             m_transcodeAction->setEnabled(false);
773         } else if (m_listView->currentItem()->type() == PROJECTCLIPTYPE) {
774             clip = static_cast <ProjectItem*>(item);
775             // Display relevant transcoding actions only
776             adjustTranscodeActions(clip);
777             adjustProxyActions(clip);
778             // Display uses in timeline
779             emit findInTimeline(clip->clipId());
780         } else {
781             m_transcodeAction->setEnabled(false);
782         }
783         if (clip && clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) {
784             m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
785             m_openAction->setEnabled(true);
786         } else if (clip && clip->clipType() == AUDIO && !KdenliveSettings::defaultaudioapp().isEmpty()) {
787             m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
788             m_openAction->setEnabled(true);
789         } else {
790             m_openAction->setEnabled(false);
791         }
792
793     } else {
794         m_openAction->setEnabled(false);
795     }
796     m_menu->popup(pos);
797 }
798
799 void ProjectList::slotRemoveClip()
800 {
801     if (!m_listView->currentItem())
802         return;
803     QStringList ids;
804     QMap <QString, QString> folderids;
805     QList<QTreeWidgetItem *> selected = m_listView->selectedItems();
806
807     QUndoCommand *delCommand = new QUndoCommand();
808     delCommand->setText(i18n("Delete Clip Zone"));
809     for (int i = 0; i < selected.count(); i++) {
810         if (selected.at(i)->type() == PROJECTSUBCLIPTYPE) {
811             // subitem
812             SubProjectItem *sub = static_cast <SubProjectItem *>(selected.at(i));
813             ProjectItem *item = static_cast <ProjectItem *>(sub->parent());
814             new AddClipCutCommand(this, item->clipId(), sub->zone().x(), sub->zone().y(), sub->description(), false, true, delCommand);
815         } else if (selected.at(i)->type() == PROJECTFOLDERTYPE) {
816             // folder
817             FolderProjectItem *folder = static_cast <FolderProjectItem *>(selected.at(i));
818             folderids[folder->groupName()] = folder->clipId();
819             int children = folder->childCount();
820
821             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)
822                 return;
823             for (int i = 0; i < children; ++i) {
824                 ProjectItem *child = static_cast <ProjectItem *>(folder->child(i));
825                 ids << child->clipId();
826             }
827         } else {
828             ProjectItem *item = static_cast <ProjectItem *>(selected.at(i));
829             ids << item->clipId();
830             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) {
831                 KMessageBox::enableMessage("DeleteAll");
832                 return;
833             }
834         }
835     }
836     KMessageBox::enableMessage("DeleteAll");
837     if (delCommand->childCount() == 0)
838         delete delCommand;
839     else
840         m_commandStack->push(delCommand);
841     emit deleteProjectClips(ids, folderids);
842 }
843
844 void ProjectList::updateButtons() const
845 {
846     if (m_listView->topLevelItemCount() == 0) {
847         m_deleteButton->defaultAction()->setEnabled(false);
848         m_editButton->defaultAction()->setEnabled(false);
849     } else {
850         m_deleteButton->defaultAction()->setEnabled(true);
851         if (!m_listView->currentItem())
852             m_listView->setCurrentItem(m_listView->topLevelItem(0));
853         QTreeWidgetItem *item = m_listView->currentItem();
854         if (item && item->type() == PROJECTCLIPTYPE) {
855             m_editButton->defaultAction()->setEnabled(true);
856             m_openAction->setEnabled(true);
857             m_reloadAction->setEnabled(true);
858             m_transcodeAction->setEnabled(true);
859             m_proxyAction->setEnabled(useProxy());
860             return;
861         }
862         else if (item && item->type() == PROJECTFOLDERTYPE && item->childCount() > 0) {
863             m_editButton->defaultAction()->setEnabled(true);
864         }
865         else m_editButton->defaultAction()->setEnabled(false);
866     }
867     m_openAction->setEnabled(false);
868     m_reloadAction->setEnabled(false);
869     m_transcodeAction->setEnabled(false);
870     m_proxyAction->setEnabled(false);
871 }
872
873 void ProjectList::selectItemById(const QString &clipId)
874 {
875     ProjectItem *item = getItemById(clipId);
876     if (item)
877         m_listView->setCurrentItem(item);
878 }
879
880
881 void ProjectList::slotDeleteClip(const QString &clipId)
882 {
883     ProjectItem *item = getItemById(clipId);
884     if (!item) {
885         kDebug() << "/// Cannot find clip to delete";
886         return;
887     }
888     m_listView->blockSignals(true);
889     QTreeWidgetItem *newSelectedItem = m_listView->itemAbove(item);
890     if (!newSelectedItem)
891         newSelectedItem = m_listView->itemBelow(item);
892     delete item;
893     m_doc->clipManager()->deleteClip(clipId);
894     m_listView->blockSignals(false);
895     if (newSelectedItem) {
896         m_listView->setCurrentItem(newSelectedItem);
897     } else {
898         updateButtons();
899         emit clipSelected(NULL);
900     }
901 }
902
903
904 void ProjectList::editFolder(const QString folderName, const QString oldfolderName, const QString &clipId)
905 {
906     EditFolderCommand *command = new EditFolderCommand(this, folderName, oldfolderName, clipId, false);
907     m_commandStack->push(command);
908     m_doc->setModified(true);
909 }
910
911 void ProjectList::slotAddFolder()
912 {
913     AddFolderCommand *command = new AddFolderCommand(this, i18n("Folder"), QString::number(m_doc->clipManager()->getFreeFolderId()), true);
914     m_commandStack->push(command);
915 }
916
917 void ProjectList::slotAddFolder(const QString foldername, const QString &clipId, bool remove, bool edit)
918 {
919     if (remove) {
920         FolderProjectItem *item = getFolderItemById(clipId);
921         if (item) {
922             m_doc->clipManager()->deleteFolder(clipId);
923             QTreeWidgetItem *newSelectedItem = m_listView->itemAbove(item);
924             if (!newSelectedItem)
925                 newSelectedItem = m_listView->itemBelow(item);
926             delete item;
927             if (newSelectedItem)
928                 m_listView->setCurrentItem(newSelectedItem);
929             else
930                 updateButtons();
931         }
932     } else {
933         if (edit) {
934             FolderProjectItem *item = getFolderItemById(clipId);
935             if (item) {
936                 m_listView->blockSignals(true);
937                 item->setGroupName(foldername);
938                 m_listView->blockSignals(false);
939                 m_doc->clipManager()->addFolder(clipId, foldername);
940                 const int children = item->childCount();
941                 for (int i = 0; i < children; i++) {
942                     ProjectItem *child = static_cast <ProjectItem *>(item->child(i));
943                     child->setProperty("groupname", foldername);
944                 }
945             }
946         } else {
947             m_listView->blockSignals(true);
948             m_listView->setCurrentItem(new FolderProjectItem(m_listView, QStringList() << foldername, clipId));
949             m_doc->clipManager()->addFolder(clipId, foldername);
950             m_listView->blockSignals(false);
951             m_listView->editItem(m_listView->currentItem(), 0);
952         }
953         updateButtons();
954     }
955     m_doc->setModified(true);
956 }
957
958
959
960 void ProjectList::deleteProjectFolder(QMap <QString, QString> map)
961 {
962     QMapIterator<QString, QString> i(map);
963     QUndoCommand *delCommand = new QUndoCommand();
964     delCommand->setText(i18n("Delete Folder"));
965     while (i.hasNext()) {
966         i.next();
967         new AddFolderCommand(this, i.key(), i.value(), false, delCommand);
968     }
969     if (delCommand->childCount() > 0) m_commandStack->push(delCommand);
970     else delete delCommand;
971 }
972
973 void ProjectList::slotAddClip(DocClipBase *clip, bool getProperties)
974 {
975     m_listView->setEnabled(false);
976     const QString parent = clip->getProperty("groupid");
977     ProjectItem *item = NULL;
978     monitorItemEditing(false);
979     if (!parent.isEmpty()) {
980         FolderProjectItem *parentitem = getFolderItemById(parent);
981         if (!parentitem) {
982             QStringList text;
983             QString groupName = clip->getProperty("groupname");
984             //kDebug() << "Adding clip to new group: " << groupName;
985             if (groupName.isEmpty()) groupName = i18n("Folder");
986             text << groupName;
987             parentitem = new FolderProjectItem(m_listView, text, parent);
988         }
989
990         if (parentitem)
991             item = new ProjectItem(parentitem, clip);
992     }
993     if (item == NULL) {
994         item = new ProjectItem(m_listView, clip);
995     }
996     if (item->data(0, DurationRole).isNull()) item->setData(0, DurationRole, i18n("Loading"));
997     connect(clip, SIGNAL(createProxy(const QString)), this, SLOT(slotCreateProxy(const QString)));
998     connect(clip, SIGNAL(abortProxy(const QString)), this, SLOT(slotAbortProxy(const QString)));
999     if (getProperties) {
1000         m_listView->processLayout();
1001         m_refreshed = false;
1002         QDomElement e = clip->toXML().cloneNode().toElement();
1003         e.removeAttribute("file_hash");
1004         m_infoQueue.insert(clip->getId(), e);
1005     }
1006     else if (item->hasProxy() && !item->isProxyRunning()) {
1007         slotCreateProxy(clip->getId());
1008     }
1009     clip->askForAudioThumbs();
1010     
1011     KUrl url = clip->fileURL();
1012     if (getProperties == false && !clip->getClipHash().isEmpty()) {
1013         QString cachedPixmap = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "thumbs/" + clip->getClipHash() + ".png";
1014         if (QFile::exists(cachedPixmap)) {
1015             QPixmap pix(cachedPixmap);
1016             if (pix.isNull())
1017                 KIO::NetAccess::del(KUrl(cachedPixmap), this);
1018             item->setData(0, Qt::DecorationRole, pix);
1019         }
1020     }
1021 #ifdef NEPOMUK
1022     if (!url.isEmpty() && KdenliveSettings::activate_nepomuk()) {
1023         // if file has Nepomuk comment, use it
1024         Nepomuk::Resource f(url.path());
1025         QString annotation = f.description();
1026         if (!annotation.isEmpty()) item->setText(1, annotation);
1027         item->setText(2, QString::number(f.rating()));
1028     }
1029 #endif
1030     // Add cut zones
1031     QList <CutZoneInfo> cuts = clip->cutZones();
1032     if (!cuts.isEmpty()) {
1033         for (int i = 0; i < cuts.count(); i++) {
1034             SubProjectItem *sub = new SubProjectItem(item, cuts.at(i).zone.x(), cuts.at(i).zone.y(), cuts.at(i).description);
1035             if (!clip->getClipHash().isEmpty()) {
1036                 QString cachedPixmap = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "thumbs/" + clip->getClipHash() + '#' + QString::number(cuts.at(i).zone.x()) + ".png";
1037                 if (QFile::exists(cachedPixmap)) {
1038                     QPixmap pix(cachedPixmap);
1039                     if (pix.isNull())
1040                         KIO::NetAccess::del(KUrl(cachedPixmap), this);
1041                     sub->setData(0, Qt::DecorationRole, pix);
1042                 }
1043             }
1044         }
1045     }
1046     monitorItemEditing(true);
1047     if (m_listView->isEnabled()) {
1048         updateButtons();
1049     }
1050     
1051     if (getProperties && m_processingClips.isEmpty())
1052         m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
1053 }
1054
1055 void ProjectList::slotGotProxy(const QString &id)
1056 {
1057     ProjectItem *item = getItemById(id);
1058     if (item) {
1059         // Proxy clip successfully created
1060         QDomElement e = item->referencedClip()->toXML().cloneNode().toElement();  
1061         //e.removeAttribute("file_hash");
1062         e.setAttribute("replace", 1);
1063         m_infoQueue.insert(id, e);
1064         if (!m_queueRunner.isRunning() && m_processingClips.isEmpty()) m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
1065     }
1066 }
1067
1068 void ProjectList::slotResetProjectList()
1069 {
1070     m_listView->clear();
1071     emit clipSelected(NULL);
1072     m_thumbnailQueue.clear();
1073     m_infoQueue.clear();
1074     m_refreshed = false;
1075 }
1076
1077 void ProjectList::requestClipInfo(const QDomElement xml, const QString id)
1078 {
1079     m_refreshed = false;
1080     m_infoQueue.insert(id, xml);
1081     //if (m_infoQueue.count() == 1 || ) QTimer::singleShot(300, this, SLOT(slotProcessNextClipInQueue()));
1082 }
1083
1084 void ProjectList::slotProcessNextClipInQueue()
1085 {
1086     if (m_infoQueue.isEmpty()) {
1087         emit processNextThumbnail();
1088         return;
1089     }
1090
1091     QMap<QString, QDomElement>::const_iterator j = m_infoQueue.constBegin();
1092     if (j != m_infoQueue.constEnd()) {
1093         QDomElement dom = j.value();
1094         const QString id = j.key();
1095         m_infoQueue.remove(id);
1096         m_processingClips.append(id);
1097         bool replace;
1098         if (dom.hasAttribute("replace")) {
1099             // Proxy action was enabled / disabled and we want to replace current producer
1100             dom.removeAttribute("replace");
1101             replace = true;
1102         }
1103         else replace = false;
1104         bool selectClip = !replace;
1105         if (m_infoQueue.count() > 1) selectClip = false;
1106         emit getFileProperties(dom, id, m_listView->iconSize().height(), replace, selectClip);
1107     }
1108 }
1109
1110 void ProjectList::slotUpdateClip(const QString &id)
1111 {
1112     ProjectItem *item = getItemById(id);
1113     monitorItemEditing(false);
1114     if (item) item->setData(0, UsageRole, QString::number(item->numReferences()));
1115     monitorItemEditing(true);
1116 }
1117
1118 void ProjectList::updateAllClips()
1119 {
1120     m_listView->setSortingEnabled(false);
1121     kDebug() << "// UPDATE ALL CLPY";
1122
1123     QTreeWidgetItemIterator it(m_listView);
1124     DocClipBase *clip;
1125     ProjectItem *item;
1126     monitorItemEditing(false);
1127     while (*it) {
1128         if ((*it)->type() == PROJECTSUBCLIPTYPE) {
1129             // subitem
1130             SubProjectItem *sub = static_cast <SubProjectItem *>(*it);
1131             if (sub->data(0, Qt::DecorationRole).isNull()) {
1132                 item = static_cast <ProjectItem *>((*it)->parent());
1133                 requestClipThumbnail(item->clipId() + '#' + QString::number(sub->zone().x()));
1134             }
1135             ++it;
1136             continue;
1137         } else if ((*it)->type() == PROJECTFOLDERTYPE) {
1138             // folder
1139             ++it;
1140             continue;
1141         } else {
1142             item = static_cast <ProjectItem *>(*it);
1143             clip = item->referencedClip();
1144             if (item->referencedClip()->producer() == NULL) {
1145                 if (clip->isPlaceHolder() == false)
1146                     requestClipInfo(clip->toXML(), clip->getId());
1147                 else if (!clip->isPlaceHolder())
1148                     item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsDropEnabled);
1149             } else {
1150                 if (item->data(0, Qt::DecorationRole).isNull())
1151                     requestClipThumbnail(clip->getId());
1152                 if (item->data(0, DurationRole).toString().isEmpty())
1153                     item->changeDuration(item->referencedClip()->producer()->get_playtime());
1154             }
1155             item->setData(0, UsageRole, QString::number(item->numReferences()));
1156         }
1157         //qApp->processEvents();
1158         ++it;
1159     }
1160
1161     if (!m_queueRunner.isRunning() && m_processingClips.isEmpty()) m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
1162     if (m_listView->isEnabled())
1163         monitorItemEditing(true);
1164     m_listView->setSortingEnabled(true);
1165     if (m_infoQueue.isEmpty())
1166         slotProcessNextThumbnail();
1167 }
1168
1169 // static
1170 QString ProjectList::getExtensions()
1171 {
1172     // Build list of mime types
1173     QStringList mimeTypes = QStringList() << "application/x-kdenlive" << "application/x-kdenlivetitle" << "video/mlt-playlist" << "text/plain"
1174                             << "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"
1175                             << "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"
1176                             << "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";
1177
1178     QString allExtensions;
1179     foreach(const QString & mimeType, mimeTypes) {
1180         KMimeType::Ptr mime(KMimeType::mimeType(mimeType));
1181         if (mime) {
1182             allExtensions.append(mime->patterns().join(" "));
1183             allExtensions.append(' ');
1184         }
1185     }
1186     return allExtensions.simplified();
1187 }
1188
1189 void ProjectList::slotAddClip(const QList <QUrl> givenList, const QString &groupName, const QString &groupId)
1190 {
1191     if (!m_commandStack)
1192         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1193
1194     KUrl::List list;
1195     if (givenList.isEmpty()) {
1196         QString allExtensions = getExtensions();
1197         const QString dialogFilter = allExtensions + ' ' + QLatin1Char('|') + i18n("All Supported Files") + "\n* " + QLatin1Char('|') + i18n("All Files");
1198         QCheckBox *b = new QCheckBox(i18n("Import image sequence"));
1199         b->setChecked(KdenliveSettings::autoimagesequence());
1200         QCheckBox *c = new QCheckBox(i18n("Transparent background for images"));
1201         c->setChecked(KdenliveSettings::autoimagetransparency());
1202         QFrame *f = new QFrame;
1203         f->setFrameShape(QFrame::NoFrame);
1204         QHBoxLayout *l = new QHBoxLayout;
1205         l->addWidget(b);
1206         l->addWidget(c);
1207         l->addStretch(5);
1208         f->setLayout(l);
1209         KFileDialog *d = new KFileDialog(KUrl("kfiledialog:///clipfolder"), dialogFilter, kapp->activeWindow(), f);
1210         d->setOperationMode(KFileDialog::Opening);
1211         d->setMode(KFile::Files);
1212         if (d->exec() == QDialog::Accepted) {
1213             KdenliveSettings::setAutoimagetransparency(c->isChecked());
1214         }
1215         list = d->selectedUrls();
1216         if (b->isChecked() && list.count() == 1) {
1217             // Check for image sequence
1218             KUrl url = list.at(0);
1219             QString fileName = url.fileName().section('.', 0, -2);
1220             if (fileName.at(fileName.size() - 1).isDigit()) {
1221                 KFileItem item(KFileItem::Unknown, KFileItem::Unknown, url);
1222                 if (item.mimetype().startsWith("image")) {
1223                     // import as sequence if we found more than one image in the sequence
1224                     QStringList list;
1225                     QString pattern = SlideshowClip::selectedPath(url.path(), false, QString(), &list);
1226                     int count = list.count();
1227                     if (count > 1) {
1228                         delete d;
1229                         QStringList groupInfo = getGroup();
1230
1231                         // get image sequence base name
1232                         while (fileName.at(fileName.size() - 1).isDigit()) {
1233                             fileName.chop(1);
1234                         }
1235
1236                         m_doc->slotCreateSlideshowClipFile(fileName, pattern, count, m_timecode.reformatSeparators(KdenliveSettings::sequence_duration()),
1237                                                            false, false, false,
1238                                                            m_timecode.getTimecodeFromFrames(int(ceil(m_timecode.fps()))), QString(), 0,
1239                                                            QString(), groupInfo.at(0), groupInfo.at(1));
1240                         return;
1241                     }
1242                 }
1243             }
1244         }
1245         delete d;
1246     } else {
1247         for (int i = 0; i < givenList.count(); i++)
1248             list << givenList.at(i);
1249     }
1250
1251     foreach(const KUrl & file, list) {
1252         // Check there is no folder here
1253         KMimeType::Ptr type = KMimeType::findByUrl(file);
1254         if (type->is("inode/directory")) {
1255             // user dropped a folder
1256             list.removeAll(file);
1257         }
1258     }
1259
1260     if (list.isEmpty())
1261         return;
1262
1263     if (givenList.isEmpty()) {
1264         QStringList groupInfo = getGroup();
1265         m_doc->slotAddClipList(list, groupInfo.at(0), groupInfo.at(1));
1266     } else {
1267         m_doc->slotAddClipList(list, groupName, groupId);
1268     }
1269 }
1270
1271 void ProjectList::slotRemoveInvalidClip(const QString &id, bool replace)
1272 {
1273     ProjectItem *item = getItemById(id);
1274     m_processingClips.removeAll(id);
1275     if (!m_queueRunner.isRunning() && m_processingClips.isEmpty()) m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
1276     if (item) {
1277         const QString path = item->referencedClip()->fileURL().path();
1278         if (item->referencedClip()->isPlaceHolder()) replace = false;
1279         if (!path.isEmpty()) {
1280             if (replace)
1281                 KMessageBox::sorry(kapp->activeWindow(), i18n("Clip <b>%1</b><br />is invalid, will be removed from project.", path));
1282             else if (KMessageBox::questionYesNo(kapp->activeWindow(), i18n("Clip <b>%1</b><br />is missing or invalid. Remove it from project?", path), i18n("Invalid clip")) == KMessageBox::Yes)
1283                 replace = true;
1284         }
1285         if (replace)
1286             emit deleteProjectClips(QStringList() << id, QMap <QString, QString>());
1287     }
1288 }
1289
1290 void ProjectList::slotRemoveInvalidProxy(const QString &id)
1291 {
1292     ProjectItem *item = getItemById(id);
1293     if (item) {
1294         item->setProxyStatus(PROXYCRASHED);
1295         QString path = item->referencedClip()->getProperty("proxy");
1296         KUrl proxyFolder(m_doc->projectFolder().path( KUrl::AddTrailingSlash) + "proxy/");
1297
1298         //Security check: make sure the invalid proxy file is in the proxy folder
1299         if (proxyFolder.isParentOf(KUrl(path))) {
1300             QFile::remove(path);
1301         }
1302     }
1303     m_processingClips.removeAll(id);
1304     if (!m_queueRunner.isRunning() && m_processingClips.isEmpty()) m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
1305 }
1306
1307 void ProjectList::slotAddColorClip()
1308 {
1309     if (!m_commandStack)
1310         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1311
1312     QDialog *dia = new QDialog(this);
1313     Ui::ColorClip_UI dia_ui;
1314     dia_ui.setupUi(dia);
1315     dia->setWindowTitle(i18n("Color Clip"));
1316     dia_ui.clip_name->setText(i18n("Color Clip"));
1317
1318     TimecodeDisplay *t = new TimecodeDisplay(m_timecode);
1319     t->setValue(KdenliveSettings::color_duration());
1320     t->setTimeCodeFormat(false);
1321     dia_ui.clip_durationBox->addWidget(t);
1322     dia_ui.clip_color->setColor(KdenliveSettings::colorclipcolor());
1323
1324     if (dia->exec() == QDialog::Accepted) {
1325         QString color = dia_ui.clip_color->color().name();
1326         KdenliveSettings::setColorclipcolor(color);
1327         color = color.replace(0, 1, "0x") + "ff";
1328         QStringList groupInfo = getGroup();
1329         m_doc->slotCreateColorClip(dia_ui.clip_name->text(), color, m_timecode.getTimecode(t->gentime()), groupInfo.at(0), groupInfo.at(1));
1330     }
1331     delete t;
1332     delete dia;
1333 }
1334
1335
1336 void ProjectList::slotAddSlideshowClip()
1337 {
1338     if (!m_commandStack)
1339         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1340
1341     SlideshowClip *dia = new SlideshowClip(m_timecode, this);
1342
1343     if (dia->exec() == QDialog::Accepted) {
1344         QStringList groupInfo = getGroup();
1345         m_doc->slotCreateSlideshowClipFile(dia->clipName(), dia->selectedPath(), dia->imageCount(), dia->clipDuration(),
1346                                            dia->loop(), dia->crop(), dia->fade(),
1347                                            dia->lumaDuration(), dia->lumaFile(), dia->softness(),
1348                                            dia->animation(), groupInfo.at(0), groupInfo.at(1));
1349     }
1350     delete dia;
1351 }
1352
1353 void ProjectList::slotAddTitleClip()
1354 {
1355     QStringList groupInfo = getGroup();
1356     m_doc->slotCreateTextClip(groupInfo.at(0), groupInfo.at(1));
1357 }
1358
1359 void ProjectList::slotAddTitleTemplateClip()
1360 {
1361     if (!m_commandStack)
1362         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1363
1364     QStringList groupInfo = getGroup();
1365
1366     // Get the list of existing templates
1367     QStringList filter;
1368     filter << "*.kdenlivetitle";
1369     const QString path = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1370     QStringList templateFiles = QDir(path).entryList(filter, QDir::Files);
1371
1372     QDialog *dia = new QDialog(this);
1373     Ui::TemplateClip_UI dia_ui;
1374     dia_ui.setupUi(dia);
1375     for (int i = 0; i < templateFiles.size(); ++i)
1376         dia_ui.template_list->comboBox()->addItem(templateFiles.at(i), path + templateFiles.at(i));
1377
1378     if (!templateFiles.isEmpty())
1379         dia_ui.buttonBox->button(QDialogButtonBox::Ok)->setFocus();
1380     dia_ui.template_list->fileDialog()->setFilter("application/x-kdenlivetitle");
1381     //warning: setting base directory doesn't work??
1382     KUrl startDir(path);
1383     dia_ui.template_list->fileDialog()->setUrl(startDir);
1384     dia_ui.text_box->setHidden(true);
1385     if (dia->exec() == QDialog::Accepted) {
1386         QString textTemplate = dia_ui.template_list->comboBox()->itemData(dia_ui.template_list->comboBox()->currentIndex()).toString();
1387         if (textTemplate.isEmpty()) textTemplate = dia_ui.template_list->comboBox()->currentText();
1388         // Create a cloned template clip
1389         m_doc->slotCreateTextTemplateClip(groupInfo.at(0), groupInfo.at(1), KUrl(textTemplate));
1390     }
1391     delete dia;
1392 }
1393
1394 QStringList ProjectList::getGroup() const
1395 {
1396     QStringList result;
1397     QTreeWidgetItem *item = m_listView->currentItem();
1398     while (item && item->type() != PROJECTFOLDERTYPE)
1399         item = item->parent();
1400
1401     if (item) {
1402         FolderProjectItem *folder = static_cast <FolderProjectItem *>(item);
1403         result << folder->groupName() << folder->clipId();
1404     } else {
1405         result << QString() << QString();
1406     }
1407     return result;
1408 }
1409
1410 void ProjectList::setDocument(KdenliveDoc *doc)
1411 {
1412     m_listView->blockSignals(true);
1413     m_listView->clear();
1414     m_processingClips.clear();
1415     m_listView->setSortingEnabled(false);
1416     emit clipSelected(NULL);
1417     m_thumbnailQueue.clear();
1418     m_infoQueue.clear();
1419     m_refreshed = false;
1420     m_fps = doc->fps();
1421     m_timecode = doc->timecode();
1422     m_commandStack = doc->commandStack();
1423     m_doc = doc;
1424     m_proxyList.clear();
1425
1426     QMap <QString, QString> flist = doc->clipManager()->documentFolderList();
1427     QMapIterator<QString, QString> f(flist);
1428     while (f.hasNext()) {
1429         f.next();
1430         (void) new FolderProjectItem(m_listView, QStringList() << f.value(), f.key());
1431     }
1432
1433     QList <DocClipBase*> list = doc->clipManager()->documentClipList();
1434     for (int i = 0; i < list.count(); i++)
1435         slotAddClip(list.at(i), false);
1436
1437     m_listView->blockSignals(false);
1438     connect(m_doc->clipManager(), SIGNAL(reloadClip(const QString &)), this, SLOT(slotReloadClip(const QString &)));
1439     connect(m_doc->clipManager(), SIGNAL(modifiedClip(const QString &)), this, SLOT(slotModifiedClip(const QString &)));
1440     connect(m_doc->clipManager(), SIGNAL(missingClip(const QString &)), this, SLOT(slotMissingClip(const QString &)));
1441     connect(m_doc->clipManager(), SIGNAL(availableClip(const QString &)), this, SLOT(slotAvailableClip(const QString &)));
1442     connect(m_doc->clipManager(), SIGNAL(checkAllClips()), this, SLOT(updateAllClips()));
1443 }
1444
1445 QList <DocClipBase*> ProjectList::documentClipList() const
1446 {
1447     if (m_doc == NULL)
1448         return QList <DocClipBase*> ();
1449
1450     return m_doc->clipManager()->documentClipList();
1451 }
1452
1453 QDomElement ProjectList::producersList()
1454 {
1455     QDomDocument doc;
1456     QDomElement prods = doc.createElement("producerlist");
1457     doc.appendChild(prods);
1458     kDebug() << "////////////  PRO LIST BUILD PRDSLIST ";
1459     QTreeWidgetItemIterator it(m_listView);
1460     while (*it) {
1461         if ((*it)->type() != PROJECTCLIPTYPE) {
1462             // subitem
1463             ++it;
1464             continue;
1465         }
1466         prods.appendChild(doc.importNode(((ProjectItem *)(*it))->toXml(), true));
1467         ++it;
1468     }
1469     return prods;
1470 }
1471
1472 void ProjectList::slotCheckForEmptyQueue()
1473 {
1474     if (!m_refreshed && m_thumbnailQueue.isEmpty() && m_infoQueue.isEmpty()) {
1475         m_refreshed = true;
1476         emit loadingIsOver();
1477         emit displayMessage(QString(), -1);
1478         m_listView->blockSignals(false);
1479         m_listView->setEnabled(true);
1480         updateButtons();
1481     } else if (!m_refreshed) {
1482         QTimer::singleShot(300, this, SLOT(slotCheckForEmptyQueue()));
1483     }
1484 }
1485
1486 void ProjectList::reloadClipThumbnails()
1487 {
1488     m_thumbnailQueue.clear();
1489     QTreeWidgetItemIterator it(m_listView);
1490     while (*it) {
1491         if ((*it)->type() != PROJECTCLIPTYPE) {
1492             // subitem
1493             ++it;
1494             continue;
1495         }
1496         m_thumbnailQueue << ((ProjectItem *)(*it))->clipId();
1497         ++it;
1498     }
1499     QTimer::singleShot(300, this, SLOT(slotProcessNextThumbnail()));
1500 }
1501
1502 void ProjectList::requestClipThumbnail(const QString id)
1503 {
1504     if (!m_thumbnailQueue.contains(id)) m_thumbnailQueue.append(id);
1505 }
1506
1507 void ProjectList::slotProcessNextThumbnail()
1508 {
1509     if (m_thumbnailQueue.isEmpty() && m_infoQueue.isEmpty()) {
1510         slotCheckForEmptyQueue();
1511         return;
1512     }
1513     if (!m_infoQueue.isEmpty()) {
1514         //QTimer::singleShot(300, this, SLOT(slotProcessNextThumbnail()));
1515         return;
1516     }
1517     if (m_thumbnailQueue.count() > 1) {
1518         int max = m_doc->clipManager()->clipsCount();
1519         emit displayMessage(i18n("Loading thumbnails"), (int)(100 *(max - m_thumbnailQueue.count()) / max));
1520     }
1521     slotRefreshClipThumbnail(m_thumbnailQueue.takeFirst(), false);
1522 }
1523
1524 void ProjectList::slotRefreshClipThumbnail(const QString &clipId, bool update)
1525 {
1526     QTreeWidgetItem *item = getAnyItemById(clipId);
1527     if (item)
1528         slotRefreshClipThumbnail(item, update);
1529     else
1530         slotProcessNextThumbnail();
1531 }
1532
1533 void ProjectList::slotRefreshClipThumbnail(QTreeWidgetItem *it, bool update)
1534 {
1535     if (it == NULL) return;
1536     ProjectItem *item = NULL;
1537     bool isSubItem = false;
1538     int frame;
1539     if (it->type() == PROJECTFOLDERTYPE) return;
1540     if (it->type() == PROJECTSUBCLIPTYPE) {
1541         item = static_cast <ProjectItem *>(it->parent());
1542         frame = static_cast <SubProjectItem *>(it)->zone().x();
1543         isSubItem = true;
1544     } else {
1545         item = static_cast <ProjectItem *>(it);
1546         frame = item->referencedClip()->getClipThumbFrame();
1547     }
1548
1549     if (item) {
1550         DocClipBase *clip = item->referencedClip();
1551         if (!clip) {
1552             slotProcessNextThumbnail();
1553             return;
1554         }
1555         QPixmap pix;
1556         int height = m_listView->iconSize().height();
1557         int width = (int)(height  * m_render->dar());
1558         if (clip->clipType() == AUDIO)
1559             pix = KIcon("audio-x-generic").pixmap(QSize(width, height));
1560         else if (clip->clipType() == IMAGE)
1561             pix = QPixmap::fromImage(KThumb::getFrame(item->referencedClip()->producer(), 0, width, height));
1562         else
1563             pix = item->referencedClip()->thumbProducer()->extractImage(frame, width, height);
1564
1565         if (!pix.isNull()) {
1566             monitorItemEditing(false);
1567             it->setData(0, Qt::DecorationRole, pix);
1568             monitorItemEditing(true);
1569                 
1570             if (!isSubItem)
1571                 m_doc->cachePixmap(item->getClipHash(), pix);
1572             else
1573                 m_doc->cachePixmap(item->getClipHash() + '#' + QString::number(frame), pix);
1574         }
1575         if (update)
1576             emit projectModified();
1577
1578         slotProcessNextThumbnail();
1579     }
1580 }
1581
1582 void ProjectList::slotReplyGetFileProperties(const QString &clipId, Mlt::Producer *producer, const QMap < QString, QString > &properties, const QMap < QString, QString > &metadata, bool replace, bool selectClip)
1583 {
1584     QString toReload;
1585     ProjectItem *item = getItemById(clipId);
1586     m_processingClips.removeAll(clipId);
1587     if (m_infoQueue.isEmpty() && m_processingClips.isEmpty()) m_listView->setEnabled(true);
1588     if (item && producer) {
1589         //m_listView->blockSignals(true);
1590         monitorItemEditing(false);
1591         item->setProperties(properties, metadata);
1592         if (item->referencedClip()->isPlaceHolder() && producer->is_valid()) {
1593             item->referencedClip()->setValid();
1594             item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsDropEnabled);
1595             toReload = clipId;
1596         }
1597         
1598         // Proxy stuff
1599         QString size = properties.value("frame_size");
1600         DocClipBase *clip = item->referencedClip();
1601         if (!useProxy() && item->referencedClip()->getProperty("proxy").isEmpty()) setProxyStatus(item, NOPROXY);
1602         if (useProxy() && generateProxy() && item->referencedClip()->getProperty("proxy") == "-") setProxyStatus(item, NOPROXY);
1603         else if (useProxy() && !item->isProxyRunning() && (item->clipType() == AV || item->clipType() == VIDEO) && generateProxy() && size.section('x', 0, 0).toInt() > proxyMinSize()) {
1604             if (clip->getProperty("proxy").isEmpty()) {
1605                 QString proxydir = m_doc->projectFolder().path( KUrl::AddTrailingSlash) + "proxy/";
1606                 QMap <QString, QString> newProps;
1607                 newProps.insert("proxy", proxydir + item->referencedClip()->getClipHash() + ".avi");
1608                 QMap <QString, QString> oldProps = clip->properties();
1609                 oldProps.insert("proxy", QString());
1610                 EditClipCommand *command = new EditClipCommand(this, clipId, oldProps, newProps, true);
1611                 m_doc->commandStack()->push(command);
1612             }
1613         }
1614         
1615         clip->setProducer(producer, replace);
1616         clip->askForAudioThumbs();
1617         if (!replace && item->data(0, Qt::DecorationRole).isNull())
1618             requestClipThumbnail(clipId);
1619         if (!toReload.isEmpty())
1620             item->slotSetToolTip();
1621
1622         if (m_listView->isEnabled() && replace) {
1623             // update clip in clip monitor
1624             emit clipSelected(NULL);
1625             emit clipSelected(clip);
1626             //TODO: Make sure the line below has no side effect
1627             toReload = clipId;
1628         }
1629         /*else {
1630             // Check if duration changed.
1631             emit receivedClipDuration(clipId);
1632             delete producer;
1633         }*/
1634         if (m_listView->isEnabled())
1635             monitorItemEditing(true);
1636         /*if (item->icon(0).isNull()) {
1637             requestClipThumbnail(clipId);
1638         }*/
1639     } else kDebug() << "////////  COULD NOT FIND CLIP TO UPDATE PRPS...";
1640     if (selectClip && m_infoQueue.isEmpty()) {
1641     if (item && m_infoQueue.isEmpty() && m_thumbnailQueue.isEmpty()) {
1642         m_listView->setCurrentItem(item);
1643         bool updatedProfile = false;
1644         if (item->parent()) {
1645             if (item->parent()->type() == PROJECTFOLDERTYPE)
1646                 static_cast <FolderProjectItem *>(item->parent())->switchIcon();
1647         } else if (KdenliveSettings::checkfirstprojectclip() &&  m_listView->topLevelItemCount() == 1) {
1648             // this is the first clip loaded in project, check if we want to adjust project settings to the clip
1649             updatedProfile = adjustProjectProfileToItem(item);
1650         }
1651         if (updatedProfile == false) emit clipSelected(item->referencedClip());
1652     } else {
1653         int max = m_doc->clipManager()->clipsCount();
1654         emit displayMessage(i18n("Loading clips"), (int)(100 *(max - m_infoQueue.count()) / max));
1655     }
1656     }
1657     if (!toReload.isEmpty())
1658         emit clipNeedsReload(toReload, true);
1659
1660     if (!m_queueRunner.isRunning() && m_processingClips.isEmpty()) m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
1661 }
1662
1663 bool ProjectList::adjustProjectProfileToItem(ProjectItem *item)
1664 {
1665     if (item == NULL) {
1666         if (m_listView->currentItem() && m_listView->currentItem()->type() != PROJECTFOLDERTYPE)
1667             item = static_cast <ProjectItem*>(m_listView->currentItem());
1668     }
1669     if (item == NULL || item->referencedClip() == NULL) {
1670         KMessageBox::information(kapp->activeWindow(), i18n("Cannot find profile from current clip"));
1671         return false;
1672     }
1673     bool profileUpdated = false;
1674     QString size = item->referencedClip()->getProperty("frame_size");
1675     int width = size.section('x', 0, 0).toInt();
1676     int height = size.section('x', -1).toInt();
1677     double fps = item->referencedClip()->getProperty("fps").toDouble();
1678     double par = item->referencedClip()->getProperty("aspect_ratio").toDouble();
1679     if (item->clipType() == IMAGE || item->clipType() == AV || item->clipType() == VIDEO) {
1680         if (ProfilesDialog::matchProfile(width, height, fps, par, item->clipType() == IMAGE, m_doc->mltProfile()) == false) {
1681             // get a list of compatible profiles
1682             QMap <QString, QString> suggestedProfiles = ProfilesDialog::getProfilesFromProperties(width, height, fps, par, item->clipType() == IMAGE);
1683             if (!suggestedProfiles.isEmpty()) {
1684                 KDialog *dialog = new KDialog(this);
1685                 dialog->setCaption(i18n("Change project profile"));
1686                 dialog->setButtons(KDialog::Ok | KDialog::Cancel);
1687
1688                 QWidget container;
1689                 QVBoxLayout *l = new QVBoxLayout;
1690                 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));
1691                 l->addWidget(label);
1692                 QListWidget *list = new QListWidget;
1693                 list->setAlternatingRowColors(true);
1694                 QMapIterator<QString, QString> i(suggestedProfiles);
1695                 while (i.hasNext()) {
1696                     i.next();
1697                     QListWidgetItem *item = new QListWidgetItem(i.value(), list);
1698                     item->setData(Qt::UserRole, i.key());
1699                     item->setToolTip(i.key());
1700                 }
1701                 list->setCurrentRow(0);
1702                 l->addWidget(list);
1703                 container.setLayout(l);
1704                 dialog->setButtonText(KDialog::Ok, i18n("Update profile"));
1705                 dialog->setMainWidget(&container);
1706                 if (dialog->exec() == QDialog::Accepted) {
1707                     //Change project profile
1708                     profileUpdated = true;
1709                     if (list->currentItem())
1710                         emit updateProfile(list->currentItem()->data(Qt::UserRole).toString());
1711                 }
1712                 delete list;
1713                 delete label;
1714             } else if (fps > 0) {
1715                 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));
1716             }
1717         }
1718     }
1719     return profileUpdated;
1720 }
1721
1722 bool ProjectList::useProxy() const
1723 {
1724     return m_doc->getDocumentProperty("enableproxy").toInt();
1725 }
1726
1727 bool ProjectList::generateProxy() const
1728 {
1729     return m_doc->getDocumentProperty("generateproxy").toInt();
1730 }
1731
1732 int ProjectList::proxyMinSize() const
1733 {
1734     return m_doc->getDocumentProperty("proxyminsize").toInt();
1735 }
1736
1737 QString ProjectList::proxyParams() const
1738 {
1739     return m_doc->getDocumentProperty("proxyparams").simplified();
1740 }
1741
1742 void ProjectList::slotReplyGetImage(const QString &clipId, const QPixmap &pix)
1743 {
1744     ProjectItem *item = getItemById(clipId);
1745     if (item && !pix.isNull()) {
1746         monitorItemEditing(false);
1747         item->setData(0, Qt::DecorationRole, pix);
1748         monitorItemEditing(true);
1749         m_doc->cachePixmap(item->getClipHash(), pix);
1750         if (m_listView->isEnabled())
1751             m_listView->blockSignals(false);
1752     }
1753 }
1754
1755 QTreeWidgetItem *ProjectList::getAnyItemById(const QString &id)
1756 {
1757     QTreeWidgetItemIterator it(m_listView);
1758     QString lookId = id;
1759     if (id.contains('#'))
1760         lookId = id.section('#', 0, 0);
1761
1762     ProjectItem *result = NULL;
1763     while (*it) {
1764         if ((*it)->type() != PROJECTCLIPTYPE) {
1765             // subitem
1766             ++it;
1767             continue;
1768         }
1769         ProjectItem *item = static_cast<ProjectItem *>(*it);
1770         if (item->clipId() == lookId) {
1771             result = item;
1772             break;
1773         }
1774         ++it;
1775     }
1776     if (result == NULL || !id.contains('#')) {
1777         return result;
1778     } else {
1779         for (int i = 0; i < result->childCount(); i++) {
1780             SubProjectItem *sub = static_cast <SubProjectItem *>(result->child(i));
1781             if (sub && sub->zone().x() == id.section('#', 1, 1).toInt())
1782                 return sub;
1783         }
1784     }
1785
1786     return NULL;
1787 }
1788
1789
1790 ProjectItem *ProjectList::getItemById(const QString &id)
1791 {
1792     ProjectItem *item;
1793     QTreeWidgetItemIterator it(m_listView);
1794     while (*it) {
1795         if ((*it)->type() != PROJECTCLIPTYPE) {
1796             // subitem or folder
1797             ++it;
1798             continue;
1799         }
1800         item = static_cast<ProjectItem *>(*it);
1801         if (item->clipId() == id)
1802             return item;
1803         ++it;
1804     }
1805     return NULL;
1806 }
1807
1808 FolderProjectItem *ProjectList::getFolderItemById(const QString &id)
1809 {
1810     FolderProjectItem *item;
1811     QTreeWidgetItemIterator it(m_listView);
1812     while (*it) {
1813         if ((*it)->type() == PROJECTFOLDERTYPE) {
1814             item = static_cast<FolderProjectItem *>(*it);
1815             if (item->clipId() == id)
1816                 return item;
1817         }
1818         ++it;
1819     }
1820     return NULL;
1821 }
1822
1823 void ProjectList::slotSelectClip(const QString &ix)
1824 {
1825     ProjectItem *clip = getItemById(ix);
1826     if (clip) {
1827         m_listView->setCurrentItem(clip);
1828         m_listView->scrollToItem(clip);
1829         m_editButton->defaultAction()->setEnabled(true);
1830         m_deleteButton->defaultAction()->setEnabled(true);
1831         m_reloadAction->setEnabled(true);
1832         m_transcodeAction->setEnabled(true);
1833         m_proxyAction->setEnabled(useProxy());
1834         if (clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) {
1835             m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
1836             m_openAction->setEnabled(true);
1837         } else if (clip->clipType() == AUDIO && !KdenliveSettings::defaultaudioapp().isEmpty()) {
1838             m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
1839             m_openAction->setEnabled(true);
1840         } else {
1841             m_openAction->setEnabled(false);
1842         }
1843     }
1844 }
1845
1846 QString ProjectList::currentClipUrl() const
1847 {
1848     ProjectItem *item;
1849     if (!m_listView->currentItem() || m_listView->currentItem()->type() == PROJECTFOLDERTYPE) return QString();
1850     if (m_listView->currentItem()->type() == PROJECTSUBCLIPTYPE) {
1851         // subitem
1852         item = static_cast <ProjectItem*>(m_listView->currentItem()->parent());
1853     } else {
1854         item = static_cast <ProjectItem*>(m_listView->currentItem());
1855     }
1856     if (item == NULL)
1857         return QString();
1858     return item->clipUrl().path();
1859 }
1860
1861 KUrl::List ProjectList::getConditionalUrls(const QString &condition) const
1862 {
1863     KUrl::List result;
1864     ProjectItem *item;
1865     QList<QTreeWidgetItem *> list = m_listView->selectedItems();
1866     for (int i = 0; i < list.count(); i++) {
1867         if (list.at(i)->type() == PROJECTFOLDERTYPE)
1868             continue;
1869         if (list.at(i)->type() == PROJECTSUBCLIPTYPE) {
1870             // subitem
1871             item = static_cast <ProjectItem*>(list.at(i)->parent());
1872         } else {
1873             item = static_cast <ProjectItem*>(list.at(i));
1874         }
1875         if (item == NULL || item->type() == COLOR || item->type() == SLIDESHOW || item->type() == TEXT)
1876             continue;
1877         DocClipBase *clip = item->referencedClip();
1878         if (!condition.isEmpty()) {
1879             if (condition.startsWith("vcodec") && !clip->hasVideoCodec(condition.section('=', 1, 1)))
1880                 continue;
1881             else if (condition.startsWith("acodec") && !clip->hasAudioCodec(condition.section('=', 1, 1)))
1882                 continue;
1883         }
1884         result.append(item->clipUrl());
1885     }
1886     return result;
1887 }
1888
1889 void ProjectList::regenerateTemplate(const QString &id)
1890 {
1891     ProjectItem *clip = getItemById(id);
1892     if (clip)
1893         regenerateTemplate(clip);
1894 }
1895
1896 void ProjectList::regenerateTemplate(ProjectItem *clip)
1897 {
1898     //TODO: remove this unused method, only force_reload is necessary
1899     clip->referencedClip()->producer()->set("force_reload", 1);
1900 }
1901
1902 QDomDocument ProjectList::generateTemplateXml(QString path, const QString &replaceString)
1903 {
1904     QDomDocument doc;
1905     QFile file(path);
1906     if (!file.open(QIODevice::ReadOnly)) {
1907         kWarning() << "ERROR, CANNOT READ: " << path;
1908         return doc;
1909     }
1910     if (!doc.setContent(&file)) {
1911         kWarning() << "ERROR, CANNOT READ: " << path;
1912         file.close();
1913         return doc;
1914     }
1915     file.close();
1916     QDomNodeList texts = doc.elementsByTagName("content");
1917     for (int i = 0; i < texts.count(); i++) {
1918         QString data = texts.item(i).firstChild().nodeValue();
1919         data.replace("%s", replaceString);
1920         texts.item(i).firstChild().setNodeValue(data);
1921     }
1922     return doc;
1923 }
1924
1925
1926 void ProjectList::slotAddClipCut(const QString &id, int in, int out)
1927 {
1928     ProjectItem *clip = getItemById(id);
1929     if (clip == NULL || clip->referencedClip()->hasCutZone(QPoint(in, out)))
1930         return;
1931     AddClipCutCommand *command = new AddClipCutCommand(this, id, in, out, QString(), true, false);
1932     m_commandStack->push(command);
1933 }
1934
1935 void ProjectList::addClipCut(const QString &id, int in, int out, const QString desc, bool newItem)
1936 {
1937     ProjectItem *clip = getItemById(id);
1938     if (clip) {
1939         DocClipBase *base = clip->referencedClip();
1940         base->addCutZone(in, out);
1941         monitorItemEditing(false);
1942         SubProjectItem *sub = new SubProjectItem(clip, in, out, desc);
1943         if (newItem && desc.isEmpty() && !m_listView->isColumnHidden(1)) {
1944             if (!clip->isExpanded())
1945                 clip->setExpanded(true);
1946             m_listView->scrollToItem(sub);
1947             m_listView->editItem(sub, 1);
1948         }
1949         QPixmap p = clip->referencedClip()->thumbProducer()->extractImage(in, (int)(sub->sizeHint(0).height()  * m_render->dar()), sub->sizeHint(0).height() - 2);
1950         sub->setData(0, Qt::DecorationRole, p);
1951         m_doc->cachePixmap(clip->getClipHash() + '#' + QString::number(in), p);
1952         monitorItemEditing(true);
1953     }
1954     emit projectModified();
1955 }
1956
1957 void ProjectList::removeClipCut(const QString &id, int in, int out)
1958 {
1959     ProjectItem *clip = getItemById(id);
1960     if (clip) {
1961         DocClipBase *base = clip->referencedClip();
1962         base->removeCutZone(in, out);
1963         SubProjectItem *sub = getSubItem(clip, QPoint(in, out));
1964         if (sub) {
1965             monitorItemEditing(false);
1966             delete sub;
1967             monitorItemEditing(true);
1968         }
1969     }
1970     emit projectModified();
1971 }
1972
1973 SubProjectItem *ProjectList::getSubItem(ProjectItem *clip, QPoint zone)
1974 {
1975     SubProjectItem *sub = NULL;
1976     if (clip) {
1977         for (int i = 0; i < clip->childCount(); i++) {
1978             QTreeWidgetItem *it = clip->child(i);
1979             if (it->type() == PROJECTSUBCLIPTYPE) {
1980                 sub = static_cast <SubProjectItem*>(it);
1981                 if (sub->zone() == zone)
1982                     break;
1983                 else
1984                     sub = NULL;
1985             }
1986         }
1987     }
1988     return sub;
1989 }
1990
1991 void ProjectList::slotUpdateClipCut(QPoint p)
1992 {
1993     if (!m_listView->currentItem() || m_listView->currentItem()->type() != PROJECTSUBCLIPTYPE)
1994         return;
1995     SubProjectItem *sub = static_cast <SubProjectItem*>(m_listView->currentItem());
1996     ProjectItem *item = static_cast <ProjectItem *>(sub->parent());
1997     EditClipCutCommand *command = new EditClipCutCommand(this, item->clipId(), sub->zone(), p, sub->text(1), sub->text(1), true);
1998     m_commandStack->push(command);
1999 }
2000
2001 void ProjectList::doUpdateClipCut(const QString &id, const QPoint oldzone, const QPoint zone, const QString &comment)
2002 {
2003     ProjectItem *clip = getItemById(id);
2004     SubProjectItem *sub = getSubItem(clip, oldzone);
2005     if (sub == NULL || clip == NULL)
2006         return;
2007     DocClipBase *base = clip->referencedClip();
2008     base->updateCutZone(oldzone.x(), oldzone.y(), zone.x(), zone.y(), comment);
2009     monitorItemEditing(false);
2010     sub->setZone(zone);
2011     sub->setDescription(comment);
2012     monitorItemEditing(true);
2013     emit projectModified();
2014 }
2015
2016 void ProjectList::slotForceProcessing(const QString &id)
2017 {
2018     while (m_infoQueue.contains(id)) {
2019         slotProcessNextClipInQueue();
2020     }
2021 }
2022
2023 void ProjectList::slotAddOrUpdateSequence(const QString frameName)
2024 {
2025     QString fileName = KUrl(frameName).fileName().section('_', 0, -2);
2026     QStringList list;
2027     QString pattern = SlideshowClip::selectedPath(frameName, false, QString(), &list);
2028     int count = list.count();
2029     if (count > 1) {
2030         const QList <DocClipBase *> existing = m_doc->clipManager()->getClipByResource(pattern);
2031         if (!existing.isEmpty()) {
2032             // Sequence already exists, update
2033             QString id = existing.at(0)->getId();
2034             //ProjectItem *item = getItemById(id);
2035             QMap <QString, QString> oldprops;
2036             QMap <QString, QString> newprops;
2037             int ttl = existing.at(0)->getProperty("ttl").toInt();
2038             oldprops["out"] = existing.at(0)->getProperty("out");
2039             newprops["out"] = QString::number(ttl * count - 1);
2040             slotUpdateClipProperties(id, newprops);
2041             EditClipCommand *command = new EditClipCommand(this, id, oldprops, newprops, false);
2042             m_commandStack->push(command);
2043         } else {
2044             // Create sequence
2045             QStringList groupInfo = getGroup();
2046             m_doc->slotCreateSlideshowClipFile(fileName, pattern, count, m_timecode.reformatSeparators(KdenliveSettings::sequence_duration()),
2047                                                false, false, false,
2048                                                m_timecode.getTimecodeFromFrames(int(ceil(m_timecode.fps()))), QString(), 0,
2049                                                QString(), groupInfo.at(0), groupInfo.at(1));
2050         }
2051     } else emit displayMessage(i18n("Sequence not found"), -2);
2052 }
2053
2054 QMap <QString, QString> ProjectList::getProxies()
2055 {
2056     QMap <QString, QString> list;
2057     ProjectItem *item;
2058     QTreeWidgetItemIterator it(m_listView);
2059     while (*it) {
2060         if ((*it)->type() != PROJECTCLIPTYPE) {
2061             ++it;
2062             continue;
2063         }
2064         item = static_cast<ProjectItem *>(*it);
2065         if (item && item->referencedClip() != NULL) {
2066             if (item->hasProxy()) {
2067                 QString proxy = item->referencedClip()->getProperty("proxy");
2068                 list.insert(proxy, item->clipUrl().path());
2069             }
2070         }
2071         ++it;
2072     }
2073     return list;
2074 }
2075
2076 void ProjectList::slotCreateProxy(const QString id)
2077 {
2078     ProjectItem *item = getItemById(id);
2079     if (!item || item->isProxyRunning()) return;
2080     setProxyStatus(id, PROXYWAITING);
2081     if (m_abortProxyId.contains(id)) m_abortProxyId.removeAll(id);
2082     emit projectModified();
2083     QtConcurrent::run(this, &ProjectList::slotGenerateProxy, id);
2084 }
2085
2086 void ProjectList::slotAbortProxy(const QString id)
2087 {
2088     if (m_proxyList.contains(id)) m_proxyList.removeAll(id);
2089     ProjectItem *item = getItemById(id);
2090     if (item) {
2091       emit projectModified();
2092       if (item->isProxyReady()) slotGotProxy(id);
2093       else if (item->isProxyRunning()) m_abortProxyId << id;
2094       setProxyStatus(id, NOPROXY);
2095     }
2096 }
2097
2098 void ProjectList::slotGenerateProxy(const QString id)
2099 {
2100     setProxyStatus(id, CREATINGPROXY);
2101     ProjectItem *item = getItemById(id);
2102     if (item == NULL) return;
2103     QString path = item->referencedClip()->getProperty("proxy");
2104     if (path.isEmpty()) {
2105         setProxyStatus(id, PROXYCRASHED);
2106         return;
2107     }
2108
2109     QString url = item->clipUrl().path();
2110     
2111     if (QFile::exists(path)) {
2112         setProxyStatus(id, PROXYDONE);
2113         slotGotProxy(id);
2114         return;
2115     }
2116     else {
2117         // Make sure proxy path is writable
2118         QFile file(path);
2119         if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
2120             setProxyStatus(id, PROXYCRASHED);
2121             return;
2122         }
2123         file.close();
2124         QFile::remove(path);
2125     }
2126
2127     QStringList parameters;
2128     parameters << "-i" << url;
2129     QString params = proxyParams();
2130     foreach(QString s, params.split(' '))
2131     parameters << s;
2132
2133     // Make sure we don't block when proxy file already exists
2134     parameters << "-y";
2135     parameters << path;
2136     QProcess myProcess;
2137     myProcess.start("ffmpeg", parameters);
2138     myProcess.waitForStarted();
2139     int result = -1;
2140     while (myProcess.state() != QProcess::NotRunning) {
2141         // building proxy file
2142         if (m_abortProxyId.contains(id)) {
2143             myProcess.close();
2144             myProcess.waitForFinished();
2145             m_abortProxyId.removeAll(id);
2146             QFile::remove(path);
2147             setProxyStatus(id, NOPROXY);
2148             result = -2;
2149             
2150         }
2151         myProcess.waitForFinished(500);
2152     }
2153     myProcess.waitForFinished();
2154     if (result == -1) result = myProcess.exitStatus();
2155     if (result == 0) {
2156         // proxy successfully created
2157         setProxyStatus(id, PROXYDONE);
2158         slotGotProxy(id);
2159     }
2160     else if (result == 1) {
2161         // Proxy process crashed
2162         QFile::remove(path);
2163         setProxyStatus(id, PROXYCRASHED);
2164     }
2165 }
2166
2167 void ProjectList::updateProxyConfig()
2168 {
2169     ProjectItem *item;
2170     QTreeWidgetItemIterator it(m_listView);
2171     QUndoCommand *command = new QUndoCommand();
2172     command->setText(i18n("Update proxy settings"));
2173     QString proxydir = m_doc->projectFolder().path( KUrl::AddTrailingSlash) + "proxy/";
2174     while (*it) {
2175         if ((*it)->type() != PROJECTCLIPTYPE) {
2176             ++it;
2177             continue;
2178         }
2179         item = static_cast<ProjectItem *>(*it);
2180         if (item == NULL) {
2181             ++it;
2182             continue;
2183         }
2184         CLIPTYPE t = item->clipType();
2185         if ((t == VIDEO || t == AV || t == UNKNOWN) && item->referencedClip() != NULL) {
2186             if  (generateProxy() && useProxy() && !item->isProxyRunning()) {
2187                 DocClipBase *clip = item->referencedClip();
2188                 if (clip->getProperty("frame_size").section('x', 0, 0).toInt() > proxyMinSize()) {
2189                     if (clip->getProperty("proxy").isEmpty()) {
2190                         // We need to insert empty proxy in old properties so that undo will work
2191                         QMap <QString, QString> oldProps = clip->properties();
2192                         oldProps.insert("proxy", QString());
2193                         QMap <QString, QString> newProps;
2194                         newProps.insert("proxy", proxydir + item->referencedClip()->getClipHash() + ".avi");
2195                         new EditClipCommand(this, clip->getId(), oldProps, newProps, true, command);
2196                     }
2197                 }
2198             }
2199             else if (item->hasProxy()) {
2200                 // remove proxy
2201                 QMap <QString, QString> newProps;
2202                 newProps.insert("proxy", QString());
2203                 newProps.insert("replace", "1");
2204                 new EditClipCommand(this, item->clipId(), item->referencedClip()->properties(), newProps, true, command);
2205                 /*item->referencedClip()->clearProperty("proxy");
2206                 QDomElement e = item->toXml().cloneNode().toElement();
2207                 e.removeAttribute("file_hash");
2208                 e.setAttribute("replace", 1);
2209                 m_infoQueue.insert(item->clipId(), e);*/
2210             }
2211         }
2212         ++it;
2213     }
2214     if (command->childCount() > 0) m_doc->commandStack()->push(command);
2215     else delete command;
2216     if (!m_infoQueue.isEmpty() && !m_queueRunner.isRunning() && m_processingClips.isEmpty()) m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
2217 }
2218
2219 void ProjectList::slotProxyCurrentItem(bool doProxy)
2220 {
2221     QList<QTreeWidgetItem *> list = m_listView->selectedItems();
2222     QTreeWidgetItem *listItem;
2223     QUndoCommand *command = new QUndoCommand();
2224     if (doProxy) command->setText(i18np("Add proxy clip", "Add proxy clips", list.count()));
2225     else command->setText(i18np("Remove proxy clip", "Remove proxy clips", list.count()));
2226     
2227     // Make sure the proxy folder exists
2228     QString proxydir = m_doc->projectFolder().path( KUrl::AddTrailingSlash) + "proxy/";
2229     KStandardDirs::makeDir(proxydir);
2230                 
2231     QMap <QString, QString> newProps;
2232     QMap <QString, QString> oldProps;
2233     if (!doProxy) newProps.insert("proxy", "-");
2234     for (int i = 0; i < list.count(); i++) {
2235         listItem = list.at(i);
2236         if (listItem->type() == PROJECTFOLDERTYPE) {
2237             for (int j = 0; j < listItem->childCount(); j++) {
2238                 QTreeWidgetItem *sub = listItem->child(j);
2239                 if (!list.contains(sub)) list.append(sub);
2240             }
2241         }
2242         if (listItem->type() == PROJECTCLIPTYPE) {
2243             ProjectItem *item = static_cast <ProjectItem*>(listItem);
2244             CLIPTYPE t = item->clipType();
2245             if ((t == VIDEO || t == AV || t == UNKNOWN) && item->referencedClip()) {
2246                 oldProps = item->referencedClip()->properties();
2247                 if (doProxy) {
2248                     newProps.clear();
2249                     QString path = proxydir + item->referencedClip()->getClipHash() + ".avi";                
2250                     newProps.insert("proxy", path);
2251                     // We need to insert empty proxy so that undo will work
2252                     oldProps.insert("proxy", QString());
2253                 }
2254                 new EditClipCommand(this, item->clipId(), oldProps, newProps, true, command);
2255             }
2256         }
2257     }
2258     if (command->childCount() > 0) {
2259         m_doc->commandStack()->push(command);
2260     }
2261     else delete command;
2262     //if (!m_infoQueue.isEmpty() && !m_queueRunner.isRunning() && m_processingClips.isEmpty()) m_queueRunner = QtConcurrent::run(this, &ProjectList::slotProcessNextClipInQueue);
2263 }
2264
2265 void ProjectList::setProxyStatus(const QString id, PROXYSTATUS status)
2266 {
2267     ProjectItem *item = getItemById(id);
2268     setProxyStatus(item, status);
2269 }
2270
2271 void ProjectList::setProxyStatus(ProjectItem *item, PROXYSTATUS status)
2272 {
2273     if (item == NULL) return;
2274     monitorItemEditing(false);
2275     item->setProxyStatus(status);
2276     monitorItemEditing(true);
2277 }
2278
2279 void ProjectList::monitorItemEditing(bool enable)
2280 {
2281     if (enable) connect(m_listView, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this, SLOT(slotItemEdited(QTreeWidgetItem *, int)));     
2282     else disconnect(m_listView, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this, SLOT(slotItemEdited(QTreeWidgetItem *, int)));     
2283 }
2284
2285 #include "projectlist.moc"