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