]> git.sesse.net Git - kdenlive/blob - src/projectlist.cpp
52e4287113b88ce571d6eeb87d17693543c68600
[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 "editclipcommand.h"
35 #include "editfoldercommand.h"
36 #include "ui_templateclip_ui.h"
37
38 #include <KDebug>
39 #include <KAction>
40 #include <KLocale>
41 #include <KFileDialog>
42 #include <KInputDialog>
43 #include <KMessageBox>
44
45 #include <nepomuk/global.h>
46 #include <nepomuk/resourcemanager.h>
47 //#include <nepomuk/tag.h>
48
49 #include <QMouseEvent>
50 #include <QStylePainter>
51 #include <QPixmap>
52 #include <QIcon>
53 #include <QMenu>
54 #include <QProcess>
55 #include <QHeaderView>
56
57 ProjectList::ProjectList(QWidget *parent) :
58         QWidget(parent),
59         m_render(NULL),
60         m_fps(-1),
61         m_commandStack(NULL),
62         m_editAction(NULL),
63         m_deleteAction(NULL),
64         m_openAction(NULL),
65         m_reloadAction(NULL),
66         m_transcodeAction(NULL),
67         m_selectedItem(NULL),
68         m_refreshed(false),
69         m_infoQueue(),
70         m_thumbnailQueue()
71 {
72
73     m_listView = new ProjectListView(this);;
74     QVBoxLayout *layout = new QVBoxLayout;
75     layout->setContentsMargins(0, 0, 0, 0);
76
77     // setup toolbar
78     KTreeWidgetSearchLine *searchView = new KTreeWidgetSearchLine(this);
79     m_toolbar = new QToolBar("projectToolBar", this);
80     m_toolbar->addWidget(searchView);
81     searchView->setTreeWidget(m_listView);
82
83     m_addButton = new QToolButton(m_toolbar);
84     m_addButton->setPopupMode(QToolButton::MenuButtonPopup);
85     m_toolbar->addWidget(m_addButton);
86
87     layout->addWidget(m_toolbar);
88     layout->addWidget(m_listView);
89     setLayout(layout);
90
91     m_queueTimer.setInterval(100);
92     connect(&m_queueTimer, SIGNAL(timeout()), this, SLOT(slotProcessNextClipInQueue()));
93     m_queueTimer.setSingleShot(true);
94
95
96
97     connect(m_listView, SIGNAL(itemSelectionChanged()), this, SLOT(slotClipSelected()));
98     connect(m_listView, SIGNAL(focusMonitor()), this, SLOT(slotClipSelected()));
99     connect(m_listView, SIGNAL(pauseMonitor()), this, SLOT(slotPauseMonitor()));
100     connect(m_listView, SIGNAL(requestMenu(const QPoint &, QTreeWidgetItem *)), this, SLOT(slotContextMenu(const QPoint &, QTreeWidgetItem *)));
101     connect(m_listView, SIGNAL(addClip()), this, SLOT(slotAddClip()));
102     connect(m_listView, SIGNAL(addClip(const QList <QUrl>, const QString &, const QString &)), this, SLOT(slotAddClip(const QList <QUrl>, const QString &, const QString &)));
103     connect(m_listView, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this, SLOT(slotItemEdited(QTreeWidgetItem *, int)));
104     connect(m_listView, SIGNAL(showProperties(DocClipBase *)), this, SIGNAL(showClipProperties(DocClipBase *)));
105
106     m_listViewDelegate = new ItemDelegate(m_listView);
107     m_listView->setItemDelegate(m_listViewDelegate);
108
109     if (KdenliveSettings::activate_nepomuk()) {
110         Nepomuk::ResourceManager::instance()->init();
111         if (!Nepomuk::ResourceManager::instance()->initialized()) {
112             kDebug() << "Cannot communicate with Nepomuk, DISABLING it";
113             KdenliveSettings::setActivate_nepomuk(false);
114         }
115     }
116 }
117
118 ProjectList::~ProjectList()
119 {
120     delete m_menu;
121     delete m_toolbar;
122     m_listView->blockSignals(true);
123     m_listView->clear();
124     delete m_listViewDelegate;
125 }
126
127 void ProjectList::setupMenu(QMenu *addMenu, QAction *defaultAction)
128 {
129     QList <QAction *> actions = addMenu->actions();
130     for (int i = 0; i < actions.count(); i++) {
131         if (actions.at(i)->data().toString() == "clip_properties") {
132             m_editAction = actions.at(i);
133             m_toolbar->addAction(m_editAction);
134             actions.removeAt(i);
135             i--;
136         } else if (actions.at(i)->data().toString() == "delete_clip") {
137             m_deleteAction = actions.at(i);
138             m_toolbar->addAction(m_deleteAction);
139             actions.removeAt(i);
140             i--;
141         } else if (actions.at(i)->data().toString() == "edit_clip") {
142             m_openAction = actions.at(i);
143             actions.removeAt(i);
144             i--;
145         } else if (actions.at(i)->data().toString() == "reload_clip") {
146             m_reloadAction = actions.at(i);
147             actions.removeAt(i);
148             i--;
149         }
150     }
151
152     QMenu *m = new QMenu();
153     m->addActions(actions);
154     m_addButton->setMenu(m);
155     m_addButton->setDefaultAction(defaultAction);
156     m_menu = new QMenu();
157     m_menu->addActions(addMenu->actions());
158 }
159
160 void ProjectList::setupGeneratorMenu(QMenu *addMenu, QMenu *transcodeMenu)
161 {
162     if (!addMenu) return;
163     QMenu *menu = m_addButton->menu();
164     menu->addMenu(addMenu);
165     m_addButton->setMenu(menu);
166
167     m_menu->addMenu(addMenu);
168     if (addMenu->isEmpty()) addMenu->setEnabled(false);
169     m_menu->addMenu(transcodeMenu);
170     if (transcodeMenu->isEmpty()) transcodeMenu->setEnabled(false);
171     m_transcodeAction = transcodeMenu;
172     m_menu->addAction(m_reloadAction);
173     m_menu->addAction(m_editAction);
174     m_menu->addAction(m_openAction);
175     m_menu->addAction(m_deleteAction);
176     m_menu->insertSeparator(m_deleteAction);
177 }
178
179
180 QByteArray ProjectList::headerInfo() const
181 {
182     return m_listView->header()->saveState();
183 }
184
185 void ProjectList::setHeaderInfo(const QByteArray &state)
186 {
187     m_listView->header()->restoreState(state);
188 }
189
190 void ProjectList::slotEditClip()
191 {
192     ProjectItem *item = static_cast <ProjectItem*>(m_listView->currentItem());
193     if (!(item->flags() & Qt::ItemIsDragEnabled)) return;
194     if (item && !item->isGroup()) {
195         emit clipSelected(item->referencedClip());
196         emit showClipProperties(item->referencedClip());
197     }
198 }
199
200 void ProjectList::slotOpenClip()
201 {
202     ProjectItem *item = static_cast <ProjectItem*>(m_listView->currentItem());
203     if (item && !item->isGroup()) {
204         if (item->clipType() == IMAGE) {
205             if (KdenliveSettings::defaultimageapp().isEmpty()) KMessageBox::sorry(this, i18n("Please set a default application to open images in the Settings dialog"));
206             else QProcess::startDetached(KdenliveSettings::defaultimageapp(), QStringList() << item->clipUrl().path());
207         }
208         if (item->clipType() == AUDIO) {
209             if (KdenliveSettings::defaultaudioapp().isEmpty()) KMessageBox::sorry(this, i18n("Please set a default application to open audio files in the Settings dialog"));
210             else QProcess::startDetached(KdenliveSettings::defaultaudioapp(), QStringList() << item->clipUrl().path());
211         }
212     }
213 }
214
215 void ProjectList::slotReloadClip(const QString &id)
216 {
217     QList<QTreeWidgetItem *> selected;
218     if (id.isEmpty()) selected = m_listView->selectedItems();
219     else selected.append(getItemById(id));
220     ProjectItem *item;
221     for (int i = 0; i < selected.count(); i++) {
222         item = static_cast <ProjectItem *>(selected.at(i));
223         if (item && !item->isGroup()) {
224             if (item->clipType() == IMAGE) {
225                 item->referencedClip()->producer()->set("force_reload", 1);
226             } else if (item->clipType() == TEXT) {
227                 if (!item->referencedClip()->getProperty("xmltemplate").isEmpty()) regenerateTemplate(item);
228             }
229             //requestClipInfo(item->toXml(), item->clipId(), true);
230             // Clear the file_hash value, which will cause a complete reload of the clip
231             emit getFileProperties(item->toXml(), item->clipId(), true);
232         }
233     }
234 }
235
236 void ProjectList::setRenderer(Render *projectRender)
237 {
238     m_render = projectRender;
239     m_listView->setIconSize(QSize(40 * m_render->dar(), 40));
240 }
241
242 void ProjectList::slotClipSelected()
243 {
244     if (m_listView->currentItem()) {
245         ProjectItem *clip = static_cast <ProjectItem*>(m_listView->currentItem());
246         if (!clip->isGroup()) {
247             m_selectedItem = clip;
248             emit clipSelected(clip->referencedClip());
249         }
250         m_editAction->setEnabled(true);
251         m_deleteAction->setEnabled(true);
252         m_reloadAction->setEnabled(true);
253         m_transcodeAction->setEnabled(true);
254         if (clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) {
255             m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
256             m_openAction->setEnabled(true);
257         } else if (clip->clipType() == AUDIO && !KdenliveSettings::defaultaudioapp().isEmpty()) {
258             m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
259             m_openAction->setEnabled(true);
260         } else m_openAction->setEnabled(false);
261     } else {
262         emit clipSelected(NULL);
263         m_editAction->setEnabled(false);
264         m_deleteAction->setEnabled(false);
265         m_openAction->setEnabled(false);
266         m_reloadAction->setEnabled(false);
267         m_transcodeAction->setEnabled(false);
268     }
269 }
270
271 void ProjectList::slotPauseMonitor()
272 {
273     if (m_render) m_render->pause();
274 }
275
276 void ProjectList::slotUpdateClipProperties(const QString &id, QMap <QString, QString> properties)
277 {
278     ProjectItem *item = getItemById(id);
279     if (item) {
280         slotUpdateClipProperties(item, properties);
281         if (properties.contains("colour") || properties.contains("resource") || properties.contains("xmldata") || properties.contains("force_aspect_ratio") || properties.contains("templatetext")) {
282             slotRefreshClipThumbnail(item);
283             emit refreshClip();
284         }
285         if (properties.contains("out")) item->changeDuration(properties.value("out").toInt());
286     }
287 }
288
289 void ProjectList::slotUpdateClipProperties(ProjectItem *clip, QMap <QString, QString> properties)
290 {
291     if (!clip) return;
292     if (!clip->isGroup()) clip->setProperties(properties);
293     //if (properties.contains("xmldata")) regenerateTemplateImage(clip);
294     if (properties.contains("name")) {
295         m_listView->blockSignals(true);
296         clip->setText(1, properties.value("name"));
297         m_listView->blockSignals(false);
298         emit clipNameChanged(clip->clipId(), properties.value("name"));
299     }
300     if (properties.contains("description")) {
301         CLIPTYPE type = clip->clipType();
302         m_listView->blockSignals(true);
303         clip->setText(2, properties.value("description"));
304         m_listView->blockSignals(false);
305         if (KdenliveSettings::activate_nepomuk() && (type == AUDIO || type == VIDEO || type == AV || type == IMAGE || type == PLAYLIST)) {
306             // Use Nepomuk system to store clip description
307             Nepomuk::Resource f(clip->clipUrl().path());
308             f.setDescription(properties.value("description"));
309         }
310         emit projectModified();
311     }
312 }
313
314 void ProjectList::slotItemEdited(QTreeWidgetItem *item, int column)
315 {
316     ProjectItem *clip = static_cast <ProjectItem*>(item);
317     if (column == 2) {
318         if (clip->referencedClip()) {
319             QMap <QString, QString> oldprops;
320             QMap <QString, QString> newprops;
321             oldprops["description"] = clip->referencedClip()->getProperty("description");
322             newprops["description"] = item->text(2);
323
324             if (clip->clipType() == TEXT && !clip->referencedClip()->getProperty("xmldata").isEmpty()) {
325                 // This is a text template clip, update the image
326                 /*oldprops.insert("xmldata", clip->referencedClip()->getProperty("xmldata"));
327                 newprops.insert("xmldata", generateTemplateXml(clip->referencedClip()->getProperty("xmltemplate"), item->text(2)).toString());*/
328                 oldprops.insert("templatetext", clip->referencedClip()->getProperty("templatetext"));
329                 newprops.insert("templatetext", item->text(2));
330             }
331
332             slotUpdateClipProperties(clip->clipId(), newprops);
333             EditClipCommand *command = new EditClipCommand(this, clip->clipId(), oldprops, newprops, false);
334             m_commandStack->push(command);
335         }
336     } else if (column == 1) {
337         if (clip->isGroup()) {
338             editFolder(item->text(1), clip->groupName(), clip->clipId());
339             clip->setGroupName(item->text(1));
340             m_doc->clipManager()->addFolder(clip->clipId(), item->text(1));
341             const int children = item->childCount();
342             for (int i = 0; i < children; i++) {
343                 ProjectItem *child = static_cast <ProjectItem *>(item->child(i));
344                 child->setProperty("groupname", item->text(1));
345             }
346         } else {
347             if (clip->referencedClip()) {
348                 QMap <QString, QString> oldprops;
349                 QMap <QString, QString> newprops;
350                 oldprops["name"] = clip->referencedClip()->getProperty("name");
351                 newprops["name"] = item->text(1);
352                 slotUpdateClipProperties(clip, newprops);
353                 emit projectModified();
354                 EditClipCommand *command = new EditClipCommand(this, clip->clipId(), oldprops, newprops, false);
355                 m_commandStack->push(command);
356             }
357         }
358     }
359 }
360
361 void ProjectList::slotContextMenu(const QPoint &pos, QTreeWidgetItem *item)
362 {
363     bool enable = false;
364     if (item) {
365         enable = true;
366     }
367     m_editAction->setEnabled(enable);
368     m_deleteAction->setEnabled(enable);
369     m_reloadAction->setEnabled(enable);
370     m_transcodeAction->setEnabled(enable);
371     if (enable) {
372         ProjectItem *clip = static_cast <ProjectItem*>(item);
373         if (clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) {
374             m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
375             m_openAction->setEnabled(true);
376         } else if (clip->clipType() == AUDIO && !KdenliveSettings::defaultaudioapp().isEmpty()) {
377             m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
378             m_openAction->setEnabled(true);
379         } else m_openAction->setEnabled(false);
380     } else m_openAction->setEnabled(false);
381     m_menu->popup(pos);
382 }
383
384 void ProjectList::slotRemoveClip()
385 {
386     if (!m_listView->currentItem()) return;
387     QList <QString> ids;
388     QMap <QString, QString> folderids;
389     QList<QTreeWidgetItem *> selected = m_listView->selectedItems();
390     ProjectItem *item;
391     for (int i = 0; i < selected.count(); i++) {
392         item = static_cast <ProjectItem *>(selected.at(i));
393         if (item->isGroup()) folderids[item->groupName()] = item->clipId();
394         else ids << item->clipId();
395         if (item->numReferences() > 0) {
396             if (KMessageBox::questionYesNo(this, 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")) != KMessageBox::Yes) return;
397         } else if (item->isGroup() && item->childCount() > 0) {
398             int children = item->childCount();
399             if (KMessageBox::questionYesNo(this, i18n("Delete folder <b>%2</b>?<br>This will also remove the %1 clips in that folder", children, item->names().at(1)), i18n("Delete Folder")) != KMessageBox::Yes) return;
400             for (int i = 0; i < children; ++i) {
401                 ProjectItem *child = static_cast <ProjectItem *>(item->child(i));
402                 ids << child->clipId();
403             }
404         }
405     }
406     if (!ids.isEmpty()) m_doc->deleteProjectClip(ids);
407     if (!folderids.isEmpty()) deleteProjectFolder(folderids);
408     if (m_listView->topLevelItemCount() == 0) {
409         m_editAction->setEnabled(false);
410         m_deleteAction->setEnabled(false);
411         m_openAction->setEnabled(false);
412         m_reloadAction->setEnabled(false);
413         m_transcodeAction->setEnabled(false);
414     }
415 }
416
417 void ProjectList::selectItemById(const QString &clipId)
418 {
419     ProjectItem *item = getItemById(clipId);
420     if (item) m_listView->setCurrentItem(item);
421 }
422
423
424 void ProjectList::slotDeleteClip(const QString &clipId)
425 {
426     ProjectItem *item = getItemById(clipId);
427     if (!item) {
428         kDebug() << "/// Cannot find clip to delete";
429         return;
430     }
431     m_listView->blockSignals(true);
432     delete item;
433     m_doc->clipManager()->deleteClip(clipId);
434     m_listView->blockSignals(false);
435     slotClipSelected();
436 }
437
438
439 void ProjectList::editFolder(const QString folderName, const QString oldfolderName, const QString &clipId)
440 {
441     EditFolderCommand *command = new EditFolderCommand(this, folderName, oldfolderName, clipId, false);
442     m_commandStack->push(command);
443     m_doc->setModified(true);
444 }
445
446 void ProjectList::slotAddFolder()
447 {
448     AddFolderCommand *command = new AddFolderCommand(this, i18n("Folder"), QString::number(m_doc->clipManager()->getFreeFolderId()), true);
449     m_commandStack->push(command);
450 }
451
452 void ProjectList::slotAddFolder(const QString foldername, const QString &clipId, bool remove, bool edit)
453 {
454     if (remove) {
455         ProjectItem *item = getFolderItemById(clipId);
456         if (item) {
457             m_doc->clipManager()->deleteFolder(clipId);
458             delete item;
459         }
460     } else {
461         if (edit) {
462             ProjectItem *item = getFolderItemById(clipId);
463             if (item) {
464                 m_listView->blockSignals(true);
465                 item->setGroupName(foldername);
466                 m_listView->blockSignals(false);
467                 m_doc->clipManager()->addFolder(clipId, foldername);
468                 const int children = item->childCount();
469                 for (int i = 0; i < children; i++) {
470                     ProjectItem *child = static_cast <ProjectItem *>(item->child(i));
471                     child->setProperty("groupname", foldername);
472                 }
473             }
474         } else {
475             QStringList text;
476             text << QString() << foldername;
477             m_listView->blockSignals(true);
478             m_listView->setCurrentItem(new ProjectItem(m_listView, text, clipId));
479             m_doc->clipManager()->addFolder(clipId, foldername);
480             m_listView->blockSignals(false);
481         }
482     }
483 }
484
485
486
487 void ProjectList::deleteProjectFolder(QMap <QString, QString> map)
488 {
489     QMapIterator<QString, QString> i(map);
490     QUndoCommand *delCommand = new QUndoCommand();
491     delCommand->setText(i18n("Delete Folder"));
492     while (i.hasNext()) {
493         i.next();
494         new AddFolderCommand(this, i.key(), i.value(), false, delCommand);
495     }
496     m_commandStack->push(delCommand);
497     m_doc->setModified(true);
498 }
499
500 void ProjectList::slotAddClip(DocClipBase *clip, bool getProperties)
501 {
502     if (getProperties) {
503         m_listView->setEnabled(false);
504         m_listView->blockSignals(true);
505     }
506     const QString parent = clip->getProperty("groupid");
507     kDebug() << "Adding clip with groupid: " << parent;
508     ProjectItem *item = NULL;
509     if (!parent.isEmpty()) {
510         ProjectItem *parentitem = getFolderItemById(parent);
511         if (!parentitem) {
512             QStringList text;
513             QString groupName = clip->getProperty("groupname");
514             //kDebug() << "Adding clip to new group: " << groupName;
515             if (groupName.isEmpty()) groupName = i18n("Folder");
516             text << QString() << groupName;
517             parentitem = new ProjectItem(m_listView, text, parent);
518         } else {
519             //kDebug() << "Adding clip to existing group: " << parentitem->groupName();
520         }
521         if (parentitem) item = new ProjectItem(parentitem, clip);
522     }
523     if (item == NULL) item = new ProjectItem(m_listView, clip);
524     KUrl url = clip->fileURL();
525
526     if (getProperties == false && !clip->getClipHash().isEmpty()) {
527         QString cachedPixmap = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "thumbs/" + clip->getClipHash() + ".png";
528         if (QFile::exists(cachedPixmap)) {
529             item->setIcon(0, QPixmap(cachedPixmap));
530         }
531     }
532
533     if (!url.isEmpty() && KdenliveSettings::activate_nepomuk()) {
534         // if file has Nepomuk comment, use it
535         Nepomuk::Resource f(url.path());
536         QString annotation = f.description();
537         if (!annotation.isEmpty()) item->setText(2, annotation);
538         item->setText(3, QString::number(f.rating()));
539     }
540     if (getProperties) m_listView->blockSignals(false);
541 }
542
543 void ProjectList::slotResetProjectList()
544 {
545     m_listView->clear();
546     emit clipSelected(NULL);
547     m_thumbnailQueue.clear();
548     m_infoQueue.clear();
549     m_refreshed = false;
550 }
551
552 void ProjectList::requestClipInfo(const QDomElement xml, const QString id)
553 {
554     m_infoQueue.insert(id, xml);
555     m_listView->setEnabled(false);
556     if (!m_queueTimer.isActive()) m_queueTimer.start();
557     //if (m_infoQueue.count() == 1 || ) QTimer::singleShot(300, this, SLOT(slotProcessNextClipInQueue()));
558 }
559
560 void ProjectList::slotProcessNextClipInQueue()
561 {
562     if (m_infoQueue.isEmpty()) {
563         slotProcessNextThumbnail();
564         return;
565     }
566
567     QMap<QString, QDomElement>::const_iterator j = m_infoQueue.constBegin();
568     if (j != m_infoQueue.constEnd()) {
569         const QDomElement dom = j.value();
570         const QString id = j.key();
571         m_infoQueue.remove(j.key());
572         emit getFileProperties(dom, id, false);
573     }
574     if (!m_infoQueue.isEmpty()) m_queueTimer.start();
575 }
576
577 void ProjectList::slotUpdateClip(const QString &id)
578 {
579     ProjectItem *item = getItemById(id);
580     m_listView->blockSignals(true);
581     if (item) item->setData(1, UsageRole, QString::number(item->numReferences()));
582     m_listView->blockSignals(false);
583 }
584
585 void ProjectList::updateAllClips()
586 {
587     m_listView->setSortingEnabled(false);
588
589     QTreeWidgetItemIterator it(m_listView);
590     DocClipBase *clip;
591     ProjectItem *item;
592     m_listView->blockSignals(true);
593     while (*it) {
594         item = static_cast <ProjectItem *>(*it);
595         if (!item->isGroup()) {
596             clip = item->referencedClip();
597             /*if (clip->clipType() == TEXT && !QFile::exists(clip->fileURL().path())) {
598                 // regenerate text clip image if required
599                 TitleWidget *dia_ui = new TitleWidget(KUrl(), QString(), m_render, this);
600                 QDomDocument doc;
601                 doc.setContent(clip->getProperty("xmldata"));
602                 dia_ui->setXml(doc);
603                 QImage pix = dia_ui->renderedPixmap();
604                 pix.save(clip->fileURL().path());
605                 delete dia_ui;
606             }*/
607             if (item->referencedClip()->producer() == NULL) {
608                 if (clip->isPlaceHolder() == false) {
609                     requestClipInfo(clip->toXML(), clip->getId());
610                 } else item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
611             } else {
612                 if (item->icon(0).isNull()) {
613                     requestClipThumbnail(clip->getId());
614                 }
615                 if (item->data(1, DurationRole).toString().isEmpty()) {
616                     item->changeDuration(item->referencedClip()->producer()->get_playtime());
617                 }
618             }
619             item->setData(1, UsageRole, QString::number(item->numReferences()));
620             qApp->processEvents();
621         }
622         ++it;
623     }
624
625     m_listView->blockSignals(false);
626     m_listView->setSortingEnabled(true);
627     if (m_infoQueue.isEmpty()) slotProcessNextThumbnail();
628 }
629
630 void ProjectList::slotAddClip(const QList <QUrl> givenList, const QString &groupName, const QString &groupId)
631 {
632     if (!m_commandStack) {
633         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
634     }
635     KUrl::List list;
636     if (givenList.isEmpty()) {
637         // Build list of mime types
638         QStringList mimeTypes = QStringList() << "application/x-kdenlive" << "application/x-kdenlivetitle" << "video/x-flv" << "application/vnd.rn-realmedia" << "video/x-dv" << "video/dv" << "video/x-msvideo" << "video/x-matroska" << "video/mlt-playlist" << "video/mpeg" << "video/ogg" << "video/x-ms-wmv" << "audio/x-flac" << "audio/x-matroska" << "audio/mp4" << "audio/mpeg" << "audio/x-mp3" << "audio/ogg" << "audio/x-wav" << "application/ogg" << "video/mp4" << "video/quicktime" << "image/gif" << "image/jpeg" << "image/png" << "image/x-tga" << "image/x-bmp" << "image/svg+xml" << "image/tiff" << "image/x-xcf-gimp" << "image/x-vnd.adobe.photoshop" << "image/x-pcx" << "image/x-exr";
639
640         QString allExtensions;
641         foreach(const QString& mimeType, mimeTypes) {
642             KMimeType::Ptr mime(KMimeType::mimeType(mimeType));
643             if (mime) {
644                 allExtensions.append(mime->patterns().join(" "));
645                 allExtensions.append(' ');
646             }
647         }
648         const QString dialogFilter = allExtensions.simplified() + ' ' + QLatin1Char('|') + i18n("All Supported Files") + "\n* " + QLatin1Char('|') + i18n("All Files");
649         list = KFileDialog::getOpenUrls(KUrl("kfiledialog:///clipfolder"), dialogFilter, this);
650
651     } else {
652         for (int i = 0; i < givenList.count(); i++)
653             list << givenList.at(i);
654     }
655     if (list.isEmpty()) return;
656
657     if (givenList.isEmpty()) {
658         QStringList groupInfo = getGroup();
659         m_doc->slotAddClipList(list, groupInfo.at(0), groupInfo.at(1));
660     } else m_doc->slotAddClipList(list, groupName, groupId);
661 }
662
663 void ProjectList::slotRemoveInvalidClip(const QString &id, bool replace)
664 {
665     ProjectItem *item = getItemById(id);
666     QTimer::singleShot(300, this, SLOT(slotProcessNextClipInQueue()));
667     if (item) {
668         const QString path = item->referencedClip()->fileURL().path();
669         if (!path.isEmpty()) {
670             if (replace) KMessageBox::sorry(this, i18n("Clip <b>%1</b><br>is invalid, will be removed from project.", path));
671             else {
672                 if (KMessageBox::questionYesNo(this, i18n("Clip <b>%1</b><br>is missing or invalid. Remove it from project?", path), i18n("Invalid clip")) == KMessageBox::Yes) replace = true;
673             }
674         }
675         QList <QString> ids;
676         ids << id;
677         if (replace) m_doc->deleteProjectClip(ids);
678     }
679 }
680
681 void ProjectList::slotAddColorClip()
682 {
683     if (!m_commandStack) {
684         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
685     }
686     QDialog *dia = new QDialog(this);
687     Ui::ColorClip_UI dia_ui;
688     dia_ui.setupUi(dia);
689     dia_ui.clip_name->setText(i18n("Color Clip"));
690     dia_ui.clip_duration->setText(KdenliveSettings::color_duration());
691     if (dia->exec() == QDialog::Accepted) {
692         QString color = dia_ui.clip_color->color().name();
693         color = color.replace(0, 1, "0x") + "ff";
694         QStringList groupInfo = getGroup();
695         m_doc->slotCreateColorClip(dia_ui.clip_name->text(), color, dia_ui.clip_duration->text(), groupInfo.at(0), groupInfo.at(1));
696     }
697     delete dia;
698 }
699
700
701 void ProjectList::slotAddSlideshowClip()
702 {
703     if (!m_commandStack) {
704         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
705     }
706     SlideshowClip *dia = new SlideshowClip(m_timecode, this);
707
708     if (dia->exec() == QDialog::Accepted) {
709         QStringList groupInfo = getGroup();
710         m_doc->slotCreateSlideshowClipFile(dia->clipName(), dia->selectedPath(), dia->imageCount(), dia->clipDuration(), dia->loop(), dia->fade(), dia->lumaDuration(), dia->lumaFile(), dia->softness(), groupInfo.at(0), groupInfo.at(1));
711     }
712     delete dia;
713 }
714
715 void ProjectList::slotAddTitleClip()
716 {
717     QStringList groupInfo = getGroup();
718     m_doc->slotCreateTextClip(groupInfo.at(0), groupInfo.at(1));
719 }
720
721 void ProjectList::slotAddTitleTemplateClip()
722 {
723     QStringList groupInfo = getGroup();
724     if (!m_commandStack) {
725         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
726     }
727
728     // Get the list of existing templates
729     QStringList filter;
730     filter << "*.kdenlivetitle";
731     const QString path = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
732     QStringList templateFiles = QDir(path).entryList(filter, QDir::Files);
733
734     QDialog *dia = new QDialog(this);
735     Ui::TemplateClip_UI dia_ui;
736     dia_ui.setupUi(dia);
737     for (int i = 0; i < templateFiles.size(); ++i) {
738         dia_ui.template_list->comboBox()->addItem(templateFiles.at(i), path + templateFiles.at(i));
739     }
740     dia_ui.template_list->fileDialog()->setFilter("*.kdenlivetitle");
741     //warning: setting base directory doesn't work??
742     KUrl startDir(path);
743     dia_ui.template_list->fileDialog()->setUrl(startDir);
744     dia_ui.description->setHidden(true);
745     if (dia->exec() == QDialog::Accepted) {
746         QString textTemplate = dia_ui.template_list->comboBox()->itemData(dia_ui.template_list->comboBox()->currentIndex()).toString();
747         if (textTemplate.isEmpty()) textTemplate = dia_ui.template_list->comboBox()->currentText();
748         if (dia_ui.normal_clip->isChecked()) {
749             // Create a normal title clip
750             m_doc->slotCreateTextClip(groupInfo.at(0), groupInfo.at(1), textTemplate);
751         } else {
752             // Create a cloned template clip
753             m_doc->slotCreateTextTemplateClip(groupInfo.at(0), groupInfo.at(1), KUrl(textTemplate));
754         }
755     }
756     delete dia;
757 }
758
759 QStringList ProjectList::getGroup() const
760 {
761     QStringList result;
762     ProjectItem *item = static_cast <ProjectItem*>(m_listView->currentItem());
763     if (item && !item->isGroup()) {
764         while (item->parent()) {
765             item = static_cast <ProjectItem*>(item->parent());
766             if (item->isGroup()) break;
767         }
768     }
769     if (item && item->isGroup()) {
770         result << item->groupName();
771         result << item->clipId();
772     } else result << QString() << QString();
773     return result;
774 }
775
776 void ProjectList::setDocument(KdenliveDoc *doc)
777 {
778     m_listView->blockSignals(true);
779     m_listView->clear();
780     m_listView->setSortingEnabled(false);
781     emit clipSelected(NULL);
782     m_thumbnailQueue.clear();
783     m_infoQueue.clear();
784     m_refreshed = false;
785     m_fps = doc->fps();
786     m_timecode = doc->timecode();
787     m_commandStack = doc->commandStack();
788     m_doc = doc;
789
790     QMap <QString, QString> flist = doc->clipManager()->documentFolderList();
791     QMapIterator<QString, QString> f(flist);
792     while (f.hasNext()) {
793         f.next();
794         (void) new ProjectItem(m_listView, QStringList() << QString() << f.value(), f.key());
795     }
796
797     QList <DocClipBase*> list = doc->clipManager()->documentClipList();
798     for (int i = 0; i < list.count(); i++) {
799         slotAddClip(list.at(i), false);
800     }
801
802     m_listView->blockSignals(false);
803     m_toolbar->setEnabled(true);
804     connect(m_doc->clipManager(), SIGNAL(reloadClip(const QString &)), this, SLOT(slotReloadClip(const QString &)));
805     connect(m_doc->clipManager(), SIGNAL(checkAllClips()), this, SLOT(updateAllClips()));
806 }
807
808 QDomElement ProjectList::producersList()
809 {
810     QDomDocument doc;
811     QDomElement prods = doc.createElement("producerlist");
812     doc.appendChild(prods);
813     kDebug() << "////////////  PRO LISTĀ BUILD PRDSLIST ";
814     QTreeWidgetItemIterator it(m_listView);
815     while (*it) {
816         if (!((ProjectItem *)(*it))->isGroup())
817             prods.appendChild(doc.importNode(((ProjectItem *)(*it))->toXml(), true));
818         ++it;
819     }
820     return prods;
821 }
822
823 void ProjectList::slotCheckForEmptyQueue()
824 {
825     if (!m_refreshed && m_thumbnailQueue.isEmpty() && m_infoQueue.isEmpty()) {
826         m_refreshed = true;
827         emit loadingIsOver();
828     } else QTimer::singleShot(300, this, SLOT(slotCheckForEmptyQueue()));
829 }
830
831 void ProjectList::reloadClipThumbnails()
832 {
833     m_thumbnailQueue.clear();
834     QTreeWidgetItemIterator it(m_listView);
835     while (*it) {
836         if (!((ProjectItem *)(*it))->isGroup())
837             m_thumbnailQueue << ((ProjectItem *)(*it))->clipId();
838         ++it;
839     }
840     QTimer::singleShot(300, this, SLOT(slotProcessNextThumbnail()));
841 }
842
843 void ProjectList::requestClipThumbnail(const QString id)
844 {
845     m_thumbnailQueue.append(id);
846 }
847
848 void ProjectList::slotProcessNextThumbnail()
849 {
850     if (m_thumbnailQueue.isEmpty() && m_infoQueue.isEmpty()) {
851         m_listView->setEnabled(true);
852         slotCheckForEmptyQueue();
853         return;
854     }
855     if (!m_infoQueue.isEmpty()) {
856         //QTimer::singleShot(300, this, SLOT(slotProcessNextThumbnail()));
857         return;
858     }
859     slotRefreshClipThumbnail(m_thumbnailQueue.takeFirst(), false);
860 }
861
862 void ProjectList::slotRefreshClipThumbnail(const QString &clipId, bool update)
863 {
864     ProjectItem *item = getItemById(clipId);
865     if (item) slotRefreshClipThumbnail(item, update);
866     else slotProcessNextThumbnail();
867 }
868
869 void ProjectList::slotRefreshClipThumbnail(ProjectItem *item, bool update)
870 {
871     if (item) {
872         DocClipBase *clip = item->referencedClip();
873         if (!clip) {
874             slotProcessNextThumbnail();
875             return;
876         }
877         QPixmap pix;
878         int height = 50;
879         int width = (int)(height  * m_render->dar());
880         if (clip->clipType() == AUDIO) pix = KIcon("audio-x-generic").pixmap(QSize(width, height));
881         else if (clip->clipType() == IMAGE) pix = KThumb::getFrame(item->referencedClip()->producer(), 0, width, height);
882         else pix = item->referencedClip()->thumbProducer()->extractImage(item->referencedClip()->getClipThumbFrame(), width, height);
883         if (!pix.isNull()) {
884             m_listView->blockSignals(true);
885             item->setIcon(0, pix);
886             m_listView->blockSignals(false);
887             m_doc->cachePixmap(item->getClipHash(), pix);
888         }
889         if (update) emit projectModified();
890         QTimer::singleShot(100, this, SLOT(slotProcessNextThumbnail()));
891     }
892 }
893
894 void ProjectList::slotReplyGetFileProperties(const QString &clipId, Mlt::Producer *producer, const QMap < QString, QString > &properties, const QMap < QString, QString > &metadata, bool replace)
895 {
896     ProjectItem *item = getItemById(clipId);
897     if (item && producer) {
898         m_listView->blockSignals(true);
899         item->setProperties(properties, metadata);
900         Q_ASSERT_X(item->referencedClip(), "void ProjectList::slotReplyGetFileProperties", QString("Item with groupName %1 does not have a clip associated").arg(item->groupName()).toLatin1());
901         item->referencedClip()->setProducer(producer, replace);
902         emit receivedClipDuration(clipId);
903         if (replace) {
904             // update clip in clip monitor
905             emit clipSelected(NULL);
906             emit clipSelected(item->referencedClip());
907         }
908         /*else {
909             // Check if duration changed.
910             emit receivedClipDuration(clipId);
911             delete producer;
912         }*/
913         m_listView->blockSignals(false);
914         if (item->icon(0).isNull()) {
915             requestClipThumbnail(clipId);
916         }
917     } else kDebug() << "////////  COULD NOT FIND CLIP TO UPDATE PRPS...";
918
919     slotProcessNextClipInQueue();
920 }
921
922 void ProjectList::slotReplyGetImage(const QString &clipId, const QPixmap &pix)
923 {
924     ProjectItem *item = getItemById(clipId);
925     if (item && !pix.isNull()) {
926         m_listView->blockSignals(true);
927         item->setIcon(0, pix);
928         m_doc->cachePixmap(item->getClipHash(), pix);
929         m_listView->blockSignals(false);
930     }
931 }
932
933 ProjectItem *ProjectList::getItemById(const QString &id)
934 {
935     ProjectItem *item;
936     QTreeWidgetItemIterator it(m_listView);
937     while (*it) {
938         item = static_cast<ProjectItem *>(*it);
939         if (item->clipId() == id && item->clipType() != FOLDER)
940             return item;
941         ++it;
942     }
943     return NULL;
944 }
945
946 ProjectItem *ProjectList::getFolderItemById(const QString &id)
947 {
948     ProjectItem *item;
949     QTreeWidgetItemIterator it(m_listView);
950     while (*it) {
951         item = static_cast<ProjectItem *>(*it);
952         if (item->clipId() == id && item->clipType() == FOLDER)
953             return item;
954         ++it;
955     }
956     return NULL;
957 }
958
959 void ProjectList::slotSelectClip(const QString &ix)
960 {
961     ProjectItem *clip = getItemById(ix);
962     if (clip) {
963         m_listView->setCurrentItem(clip);
964         m_listView->scrollToItem(clip);
965         m_editAction->setEnabled(true);
966         m_deleteAction->setEnabled(true);
967         m_reloadAction->setEnabled(true);
968         m_transcodeAction->setEnabled(true);
969         if (clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) {
970             m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
971             m_openAction->setEnabled(true);
972         } else if (clip->clipType() == AUDIO && !KdenliveSettings::defaultaudioapp().isEmpty()) {
973             m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
974             m_openAction->setEnabled(true);
975         } else m_openAction->setEnabled(false);
976     }
977 }
978
979 QString ProjectList::currentClipUrl() const
980 {
981     ProjectItem *item = static_cast <ProjectItem*>(m_listView->currentItem());
982     if (item == NULL) return QString();
983     return item->clipUrl().path();
984 }
985
986 void ProjectList::regenerateTemplate(const QString &id)
987 {
988     ProjectItem *clip = getItemById(id);
989     if (clip) regenerateTemplate(clip);
990 }
991
992 void ProjectList::regenerateTemplate(ProjectItem *clip)
993 {
994     //TODO: remove this unused method, only force_reload is necessary
995     // Generate image for template clip
996     /*const QString comment = clip->referencedClip()->getProperty("description");
997     const QString path = clip->referencedClip()->getProperty("resource");
998     QDomDocument doc = generateTemplateXml(path, comment);
999     TitleWidget *dia_ui = new TitleWidget(KUrl(), QString(), m_render, this);
1000     dia_ui->setXml(doc);
1001     QImage pix = dia_ui->renderedPixmap();
1002     pix.save(clip->clipUrl().path());
1003     delete dia_ui;*/
1004     clip->referencedClip()->producer()->set("force_reload", 1);
1005 }
1006
1007 void ProjectList::regenerateTemplateImage(ProjectItem *clip)
1008 {
1009     //TODO: remove this unused method
1010     // Generate image for template clip
1011     /*TitleWidget *dia_ui = new TitleWidget(KUrl(), QString(), m_render, this);
1012     QDomDocument doc;
1013     doc.setContent(clip->referencedClip()->getProperty("xmldata"));
1014     dia_ui->setXml(doc);
1015     QImage pix = dia_ui->renderedPixmap();
1016     pix.save(clip->clipUrl().path());
1017     delete dia_ui;*/
1018 }
1019
1020 QDomDocument ProjectList::generateTemplateXml(QString path, const QString &replaceString)
1021 {
1022     QDomDocument doc;
1023     QFile file(path);
1024     if (!file.open(QIODevice::ReadOnly)) {
1025         kWarning() << "ERROR, CANNOT READ: " << path;
1026         return doc;
1027     }
1028     if (!doc.setContent(&file)) {
1029         kWarning() << "ERROR, CANNOT READ: " << path;
1030         file.close();
1031         return doc;
1032     }
1033     file.close();
1034     QDomNodeList texts = doc.elementsByTagName("content");
1035     for (int i = 0; i < texts.count(); i++) {
1036         QString data = texts.item(i).firstChild().nodeValue();
1037         data.replace("%s", replaceString);
1038         texts.item(i).firstChild().setNodeValue(data);
1039     }
1040     return doc;
1041 }
1042
1043 #include "projectlist.moc"