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