]> git.sesse.net Git - kdenlive/blob - src/projectlist.cpp
6fcbd91a9fe0887418245ede1526ca611f7a967d
[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 "editclipcutcommand.h"
36 #include "editfoldercommand.h"
37 #include "addclipcutcommand.h"
38
39 #include "ui_templateclip_ui.h"
40
41 #include <KDebug>
42 #include <KAction>
43 #include <KLocale>
44 #include <KFileDialog>
45 #include <KInputDialog>
46 #include <KMessageBox>
47 #include <KIO/NetAccess>
48 #include <KFileItem>
49 #ifdef NEPOMUK
50 #include <nepomuk/global.h>
51 #include <nepomuk/resourcemanager.h>
52 //#include <nepomuk/tag.h>
53 #endif
54
55 #include <QMouseEvent>
56 #include <QStylePainter>
57 #include <QPixmap>
58 #include <QIcon>
59 #include <QMenu>
60 #include <QProcess>
61 #include <QHeaderView>
62
63 ProjectList::ProjectList(QWidget *parent) :
64         QWidget(parent),
65         m_render(NULL),
66         m_fps(-1),
67         m_commandStack(NULL),
68         m_editAction(NULL),
69         m_deleteAction(NULL),
70         m_openAction(NULL),
71         m_reloadAction(NULL),
72         m_transcodeAction(NULL),
73         m_doc(NULL),
74         m_refreshed(false),
75         m_infoQueue(),
76         m_thumbnailQueue()
77 {
78
79     m_listView = new ProjectListView(this);;
80     QVBoxLayout *layout = new QVBoxLayout;
81     layout->setContentsMargins(0, 0, 0, 0);
82     layout->setSpacing(0);
83
84     // setup toolbar
85     KTreeWidgetSearchLine *searchView = new KTreeWidgetSearchLine(this);
86     m_toolbar = new QToolBar("projectToolBar", this);
87     m_toolbar->addWidget(searchView);
88     int s = style()->pixelMetric(QStyle::PM_SmallIconSize);
89     m_toolbar->setIconSize(QSize(s, s));
90     searchView->setTreeWidget(m_listView);
91
92     m_addButton = new QToolButton(m_toolbar);
93     m_addButton->setPopupMode(QToolButton::MenuButtonPopup);
94     m_toolbar->addWidget(m_addButton);
95
96     layout->addWidget(m_toolbar);
97     layout->addWidget(m_listView);
98     setLayout(layout);
99
100     m_queueTimer.setInterval(100);
101     connect(&m_queueTimer, SIGNAL(timeout()), this, SLOT(slotProcessNextClipInQueue()));
102     m_queueTimer.setSingleShot(true);
103
104
105     connect(m_listView, SIGNAL(projectModified()), this, SIGNAL(projectModified()));
106     connect(m_listView, SIGNAL(itemSelectionChanged()), this, SLOT(slotClipSelected()));
107     connect(m_listView, SIGNAL(focusMonitor()), this, SLOT(slotClipSelected()));
108     connect(m_listView, SIGNAL(pauseMonitor()), this, SLOT(slotPauseMonitor()));
109     connect(m_listView, SIGNAL(requestMenu(const QPoint &, QTreeWidgetItem *)), this, SLOT(slotContextMenu(const QPoint &, QTreeWidgetItem *)));
110     connect(m_listView, SIGNAL(addClip()), this, SLOT(slotAddClip()));
111     connect(m_listView, SIGNAL(addClip(const QList <QUrl>, const QString &, const QString &)), this, SLOT(slotAddClip(const QList <QUrl>, const QString &, const QString &)));
112     connect(m_listView, SIGNAL(addClipCut(const QString &, int, int)), this, SLOT(slotAddClipCut(const QString &, int, int)));
113     connect(m_listView, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this, SLOT(slotItemEdited(QTreeWidgetItem *, int)));
114     connect(m_listView, SIGNAL(showProperties(DocClipBase *)), this, SIGNAL(showClipProperties(DocClipBase *)));
115
116     m_listViewDelegate = new ItemDelegate(m_listView);
117     m_listView->setItemDelegate(m_listViewDelegate);
118 #ifdef NEPOMUK
119     if (KdenliveSettings::activate_nepomuk()) {
120         Nepomuk::ResourceManager::instance()->init();
121         if (!Nepomuk::ResourceManager::instance()->initialized()) {
122             kDebug() << "Cannot communicate with Nepomuk, DISABLING it";
123             KdenliveSettings::setActivate_nepomuk(false);
124         }
125     }
126 #endif
127 }
128
129 ProjectList::~ProjectList()
130 {
131     delete m_menu;
132     delete m_toolbar;
133     m_listView->blockSignals(true);
134     m_listView->clear();
135     delete m_listViewDelegate;
136 }
137
138 void ProjectList::focusTree() const
139 {
140     m_listView->setFocus();
141 }
142
143 void ProjectList::setupMenu(QMenu *addMenu, QAction *defaultAction)
144 {
145     QList <QAction *> actions = addMenu->actions();
146     for (int i = 0; i < actions.count(); i++) {
147         if (actions.at(i)->data().toString() == "clip_properties") {
148             m_editAction = actions.at(i);
149             m_toolbar->addAction(m_editAction);
150             actions.removeAt(i);
151             i--;
152         } else if (actions.at(i)->data().toString() == "delete_clip") {
153             m_deleteAction = actions.at(i);
154             m_toolbar->addAction(m_deleteAction);
155             actions.removeAt(i);
156             i--;
157         } else if (actions.at(i)->data().toString() == "edit_clip") {
158             m_openAction = actions.at(i);
159             actions.removeAt(i);
160             i--;
161         } else if (actions.at(i)->data().toString() == "reload_clip") {
162             m_reloadAction = actions.at(i);
163             actions.removeAt(i);
164             i--;
165         }
166     }
167
168     QMenu *m = new QMenu();
169     m->addActions(actions);
170     m_addButton->setMenu(m);
171     m_addButton->setDefaultAction(defaultAction);
172     m_menu = new QMenu();
173     m_menu->addActions(addMenu->actions());
174 }
175
176 void ProjectList::setupGeneratorMenu(QMenu *addMenu, QMenu *transcodeMenu, QMenu *inTimelineMenu)
177 {
178     if (!addMenu) return;
179     QMenu *menu = m_addButton->menu();
180     menu->addMenu(addMenu);
181     m_addButton->setMenu(menu);
182
183     m_menu->addMenu(addMenu);
184     if (addMenu->isEmpty()) addMenu->setEnabled(false);
185     m_menu->addMenu(transcodeMenu);
186     if (transcodeMenu->isEmpty()) transcodeMenu->setEnabled(false);
187     m_transcodeAction = transcodeMenu;
188     m_menu->addAction(m_reloadAction);
189     m_menu->addMenu(inTimelineMenu);
190     inTimelineMenu->setEnabled(false);
191     m_menu->addAction(m_editAction);
192     m_menu->addAction(m_openAction);
193     m_menu->addAction(m_deleteAction);
194     m_menu->insertSeparator(m_deleteAction);
195 }
196
197
198 QByteArray ProjectList::headerInfo() const
199 {
200     return m_listView->header()->saveState();
201 }
202
203 void ProjectList::setHeaderInfo(const QByteArray &state)
204 {
205     m_listView->header()->restoreState(state);
206 }
207
208 void ProjectList::updateProjectFormat(Timecode t)
209 {
210     m_timecode = t;
211 }
212
213 void ProjectList::slotEditClip()
214 {
215     QList<QTreeWidgetItem *> list = m_listView->selectedItems();
216     if (list.count() > 1) {
217         editClipSelection(list);
218         return;
219     }
220     ProjectItem *item;
221     if (!m_listView->currentItem() || m_listView->currentItem()->type() == PROJECTFOLDERTYPE) return;
222     if (m_listView->currentItem()->type() == PROJECTSUBCLIPTYPE) {
223         item = static_cast <ProjectItem*>(m_listView->currentItem()->parent());
224     } else item = static_cast <ProjectItem*>(m_listView->currentItem());
225     if (!(item->flags() & Qt::ItemIsDragEnabled)) return;
226     if (item) {
227         emit clipSelected(item->referencedClip());
228         emit showClipProperties(item->referencedClip());
229     }
230 }
231
232 void ProjectList::editClipSelection(QList<QTreeWidgetItem *> list)
233 {
234     // Gather all common properties
235     QMap <QString, QString> commonproperties;
236     QList <DocClipBase *> clipList;
237     commonproperties.insert("force_aspect_ratio", "-");
238     commonproperties.insert("force_fps", "-");
239     commonproperties.insert("force_progressive", "-");
240     commonproperties.insert("threads", "-");
241     commonproperties.insert("video_index", "-");
242     commonproperties.insert("audio_index", "-");
243
244     bool allowDurationChange = true;
245     int commonDuration = -1;
246     ProjectItem *item;
247     for (int i = 0; i < list.count(); i++) {
248         item = NULL;
249         if (list.at(i)->type() == PROJECTFOLDERTYPE) continue;
250         if (list.at(i)->type() == PROJECTSUBCLIPTYPE) {
251             item = static_cast <ProjectItem*>(list.at(i)->parent());
252         } else item = static_cast <ProjectItem*>(list.at(i));
253         if (!(item->flags() & Qt::ItemIsDragEnabled)) continue;
254         if (item) {
255             // check properties
256             DocClipBase *clip = item->referencedClip();
257             if (clipList.contains(clip)) continue;
258             if (clip->clipType() != COLOR && clip->clipType() != IMAGE && clip->clipType() != TEXT) {
259                 allowDurationChange = false;
260             }
261             if (allowDurationChange && commonDuration != 0) {
262                 if (commonDuration == -1) {
263                     commonDuration = clip->duration().frames(m_fps);
264                 } else if (commonDuration != clip->duration().frames(m_fps)) {
265                     commonDuration = 0;
266                 }
267             }
268             clipList.append(clip);
269             QMap <QString, QString> clipprops = clip->properties();
270             QMapIterator<QString, QString> p(commonproperties);
271             while (p.hasNext()) {
272                 p.next();
273                 if (p.value().isEmpty()) continue;
274                 if (clipprops.contains(p.key())) {
275                     if (p.value() == "-") commonproperties.insert(p.key(), clipprops.value(p.key()));
276                     else if (p.value() != clipprops.value(p.key())) commonproperties.insert(p.key(), QString());
277                 } else commonproperties.insert(p.key(), QString());
278             }
279         }
280     }
281     if (allowDurationChange) commonproperties.insert("out", QString::number(commonDuration));
282     QMapIterator<QString, QString> p(commonproperties);
283     while (p.hasNext()) {
284         p.next();
285         kDebug() << "Result: " << p.key() << " = " << p.value();
286     }
287     emit showClipProperties(clipList, commonproperties);
288 }
289
290 void ProjectList::slotOpenClip()
291 {
292     ProjectItem *item;
293     if (!m_listView->currentItem() || m_listView->currentItem()->type() == PROJECTFOLDERTYPE) return;
294     if (m_listView->currentItem()->type() == QTreeWidgetItem::UserType + 1) {
295         item = static_cast <ProjectItem*>(m_listView->currentItem()->parent());
296     } else item = static_cast <ProjectItem*>(m_listView->currentItem());
297     if (item) {
298         if (item->clipType() == IMAGE) {
299             if (KdenliveSettings::defaultimageapp().isEmpty()) KMessageBox::sorry(this, i18n("Please set a default application to open images in the Settings dialog"));
300             else QProcess::startDetached(KdenliveSettings::defaultimageapp(), QStringList() << item->clipUrl().path());
301         }
302         if (item->clipType() == AUDIO) {
303             if (KdenliveSettings::defaultaudioapp().isEmpty()) KMessageBox::sorry(this, i18n("Please set a default application to open audio files in the Settings dialog"));
304             else QProcess::startDetached(KdenliveSettings::defaultaudioapp(), QStringList() << item->clipUrl().path());
305         }
306     }
307 }
308
309 void ProjectList::cleanup()
310 {
311     m_listView->clearSelection();
312     QTreeWidgetItemIterator it(m_listView);
313     ProjectItem *item;
314     while (*it) {
315         if ((*it)->type() != PROJECTCLIPTYPE) {
316             it++;
317             continue;
318         }
319         item = static_cast <ProjectItem *>(*it);
320         if (item->numReferences() == 0) item->setSelected(true);
321         it++;
322     }
323     slotRemoveClip();
324 }
325
326 void ProjectList::trashUnusedClips()
327 {
328     QTreeWidgetItemIterator it(m_listView);
329     ProjectItem *item;
330     QStringList ids;
331     QStringList urls;
332     while (*it) {
333         if ((*it)->type() != PROJECTCLIPTYPE) {
334             it++;
335             continue;
336         }
337         item = static_cast <ProjectItem *>(*it);
338         if (item->numReferences() == 0) {
339             ids << item->clipId();
340             KUrl url = item->clipUrl();
341             if (!url.isEmpty() && !urls.contains(url.path())) urls << url.path();
342         }
343         it++;
344     }
345
346     // Check that we don't use the URL in another clip
347     QTreeWidgetItemIterator it2(m_listView);
348     while (*it2) {
349         if ((*it2)->type() != PROJECTCLIPTYPE) {
350             it2++;
351             continue;
352         }
353         item = static_cast <ProjectItem *>(*it2);
354         if (item->numReferences() > 0) {
355             KUrl url = item->clipUrl();
356             if (!url.isEmpty() && urls.contains(url.path())) urls.removeAll(url.path());
357         }
358         it2++;
359     }
360
361     emit deleteProjectClips(ids, QMap <QString, QString>());
362     for (int i = 0; i < urls.count(); i++) {
363         KIO::NetAccess::del(KUrl(urls.at(i)), this);
364     }
365 }
366
367 void ProjectList::slotReloadClip(const QString &id)
368 {
369     QList<QTreeWidgetItem *> selected;
370     if (id.isEmpty()) selected = m_listView->selectedItems();
371     else selected.append(getItemById(id));
372     ProjectItem *item;
373     for (int i = 0; i < selected.count(); i++) {
374         if (selected.at(i)->type() != PROJECTCLIPTYPE) {
375             if (selected.at(i)->type() == PROJECTFOLDERTYPE) {
376                 for (int j = 0; j < selected.at(i)->childCount(); j++)
377                     selected.append(selected.at(i)->child(j));
378             }
379             continue;
380         }
381         item = static_cast <ProjectItem *>(selected.at(i));
382         if (item) {
383             if (item->clipType() == TEXT) {
384                 if (!item->referencedClip()->getProperty("xmltemplate").isEmpty()) regenerateTemplate(item);
385             } else if (item->clipType() != COLOR && item->clipType() != SLIDESHOW && item->referencedClip() &&  item->referencedClip()->checkHash() == false) {
386                 item->referencedClip()->setPlaceHolder(true);
387                 item->setProperty("file_hash", QString());
388             } else if (item->clipType() == IMAGE) {
389                 item->referencedClip()->producer()->set("force_reload", 1);
390             }
391             //requestClipInfo(item->toXml(), item->clipId(), true);
392             // Clear the file_hash value, which will cause a complete reload of the clip
393             emit getFileProperties(item->toXml(), item->clipId(), m_listView->iconSize().height(), true);
394         }
395     }
396 }
397
398 void ProjectList::slotMissingClip(const QString &id)
399 {
400     ProjectItem *item = getItemById(id);
401     if (item) {
402         item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
403         if (item->referencedClip()) {
404             item->referencedClip()->setPlaceHolder(true);
405             if (m_render == NULL) kDebug() << "*********  ERROR, NULL RENDR";
406             item->referencedClip()->setProducer(m_render->invalidProducer(id), true);
407             item->slotSetToolTip();
408             emit clipNeedsReload(id, true);
409         }
410     }
411     update();
412     emit displayMessage(i18n("Check missing clips"), -2);
413     emit updateRenderStatus();
414 }
415
416 void ProjectList::slotAvailableClip(const QString &id)
417 {
418     ProjectItem *item = getItemById(id);
419     if (item == NULL) return;
420     item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | Qt::ItemIsEditable);
421     if (item->referencedClip()) { // && item->referencedClip()->checkHash() == false) {
422         item->setProperty("file_hash", QString());
423         slotReloadClip(id);
424     }
425     /*else {
426     item->referencedClip()->setValid();
427     item->slotSetToolTip();
428     }
429     update();*/
430     emit updateRenderStatus();
431 }
432
433 bool ProjectList::hasMissingClips()
434 {
435     bool missing = false;
436     QTreeWidgetItemIterator it(m_listView);
437     while (*it) {
438         if ((*it)->type() == PROJECTCLIPTYPE && !((*it)->flags() & Qt::ItemIsDragEnabled)) {
439             missing = true;
440             break;
441         }
442         it++;
443     }
444     return missing;
445 }
446
447 void ProjectList::setRenderer(Render *projectRender)
448 {
449     m_render = projectRender;
450     m_listView->setIconSize(QSize((ProjectItem::itemDefaultHeight() - 2) * m_render->dar(), ProjectItem::itemDefaultHeight() - 2));
451 }
452
453 void ProjectList::slotClipSelected()
454 {
455     if (!m_listView->isEnabled()) return;
456     if (m_listView->currentItem()) {
457         if (m_listView->currentItem()->type() == PROJECTFOLDERTYPE) {
458             emit clipSelected(NULL);
459             m_editAction->setEnabled(false);
460             m_deleteAction->setEnabled(true);
461             m_openAction->setEnabled(false);
462             m_reloadAction->setEnabled(false);
463             m_transcodeAction->setEnabled(false);
464         } else {
465             ProjectItem *clip;
466             if (m_listView->currentItem()->type() == PROJECTSUBCLIPTYPE) {
467                 // this is a sub item, use base clip
468                 m_deleteAction->setEnabled(true);
469                 clip = static_cast <ProjectItem*>(m_listView->currentItem()->parent());
470                 if (clip == NULL) kDebug() << "-----------ERROR";
471                 SubProjectItem *sub = static_cast <SubProjectItem*>(m_listView->currentItem());
472                 emit clipSelected(clip->referencedClip(), sub->zone());
473                 m_transcodeAction->setEnabled(false);
474                 return;
475             }
476             clip = static_cast <ProjectItem*>(m_listView->currentItem());
477             if (clip) emit clipSelected(clip->referencedClip());
478             m_editAction->setEnabled(true);
479             m_deleteAction->setEnabled(true);
480             m_reloadAction->setEnabled(true);
481             m_transcodeAction->setEnabled(true);
482             if (clip && clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) {
483                 m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
484                 m_openAction->setEnabled(true);
485             } else if (clip && clip->clipType() == AUDIO && !KdenliveSettings::defaultaudioapp().isEmpty()) {
486                 m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
487                 m_openAction->setEnabled(true);
488             } else m_openAction->setEnabled(false);
489             // Display relevant transcoding actions only
490             adjustTranscodeActions(clip);
491             // Display uses in timeline
492             emit findInTimeline(clip->clipId());
493         }
494     } else {
495         emit clipSelected(NULL);
496         m_editAction->setEnabled(false);
497         m_deleteAction->setEnabled(false);
498         m_openAction->setEnabled(false);
499         m_reloadAction->setEnabled(false);
500         m_transcodeAction->setEnabled(false);
501     }
502 }
503
504 void ProjectList::adjustTranscodeActions(ProjectItem *clip) const
505 {
506     if (clip == NULL || clip->type() != PROJECTCLIPTYPE || clip->clipType() == COLOR || clip->clipType() == TEXT || clip->clipType() == PLAYLIST || clip->clipType() == SLIDESHOW || clip->clipType() == IMAGE) {
507         m_transcodeAction->setEnabled(false);
508         return;
509     }
510     m_transcodeAction->setEnabled(true);
511     QList<QAction *> transcodeActions = m_transcodeAction->actions();
512     QStringList data;
513     QString condition;
514     for (int i = 0; i < transcodeActions.count(); i++) {
515         data = transcodeActions.at(i)->data().toStringList();
516         if (data.count() > 2) {
517             condition = data.at(2);
518             if (condition.startsWith("vcodec")) transcodeActions.at(i)->setEnabled(clip->referencedClip()->hasVideoCodec(condition.section("=", 1, 1)));
519             else if (condition.startsWith("acodec")) transcodeActions.at(i)->setEnabled(clip->referencedClip()->hasVideoCodec(condition.section("=", 1, 1)));
520         }
521     }
522
523 }
524
525 void ProjectList::slotPauseMonitor()
526 {
527     if (m_render) m_render->pause();
528 }
529
530 void ProjectList::slotUpdateClipProperties(const QString &id, QMap <QString, QString> properties)
531 {
532     ProjectItem *item = getItemById(id);
533     if (item) {
534         slotUpdateClipProperties(item, properties);
535         if (properties.contains("out") || properties.contains("force_fps")) {
536             slotReloadClip(id);
537         } else if (properties.contains("colour") || properties.contains("resource") || properties.contains("xmldata") || properties.contains("force_aspect_ratio") || properties.contains("templatetext")) {
538             slotRefreshClipThumbnail(item);
539             emit refreshClip();
540         }
541     }
542 }
543
544 void ProjectList::slotUpdateClipProperties(ProjectItem *clip, QMap <QString, QString> properties)
545 {
546     if (!clip) return;
547     clip->setProperties(properties);
548     if (properties.contains("name")) {
549         m_listView->blockSignals(true);
550         clip->setText(0, properties.value("name"));
551         m_listView->blockSignals(false);
552         emit clipNameChanged(clip->clipId(), properties.value("name"));
553     }
554     if (properties.contains("description")) {
555         CLIPTYPE type = clip->clipType();
556         m_listView->blockSignals(true);
557         clip->setText(1, properties.value("description"));
558         m_listView->blockSignals(false);
559 #ifdef NEPOMUK
560         if (KdenliveSettings::activate_nepomuk() && (type == AUDIO || type == VIDEO || type == AV || type == IMAGE || type == PLAYLIST)) {
561             // Use Nepomuk system to store clip description
562             Nepomuk::Resource f(clip->clipUrl().path());
563             f.setDescription(properties.value("description"));
564         }
565 #endif
566         emit projectModified();
567     }
568 }
569
570 void ProjectList::slotItemEdited(QTreeWidgetItem *item, int column)
571 {
572     if (item->type() == PROJECTSUBCLIPTYPE) {
573         // this is a sub-item
574         if (column == 1) {
575             // user edited description
576             SubProjectItem *sub = static_cast <SubProjectItem*>(item);
577             ProjectItem *item = static_cast <ProjectItem *>(sub->parent());
578             EditClipCutCommand *command = new EditClipCutCommand(this, item->clipId(), sub->zone(), sub->zone(), sub->description(), sub->text(1), true);
579             m_commandStack->push(command);
580             //slotUpdateCutClipProperties(sub->clipId(), sub->zone(), sub->text(1), sub->text(1));
581         }
582         return;
583     }
584     if (item->type() == PROJECTFOLDERTYPE) {
585         if (column != 0) return;
586         FolderProjectItem *folder = static_cast <FolderProjectItem*>(item);
587         editFolder(item->text(0), folder->groupName(), folder->clipId());
588         folder->setGroupName(item->text(0));
589         m_doc->clipManager()->addFolder(folder->clipId(), item->text(0));
590         const int children = item->childCount();
591         for (int i = 0; i < children; i++) {
592             ProjectItem *child = static_cast <ProjectItem *>(item->child(i));
593             child->setProperty("groupname", item->text(0));
594         }
595         return;
596     }
597
598     ProjectItem *clip = static_cast <ProjectItem*>(item);
599     if (column == 1) {
600         if (clip->referencedClip()) {
601             QMap <QString, QString> oldprops;
602             QMap <QString, QString> newprops;
603             oldprops["description"] = clip->referencedClip()->getProperty("description");
604             newprops["description"] = item->text(1);
605
606             if (clip->clipType() == TEXT) {
607                 // This is a text template clip, update the image
608                 /*oldprops.insert("xmldata", clip->referencedClip()->getProperty("xmldata"));
609                 newprops.insert("xmldata", generateTemplateXml(clip->referencedClip()->getProperty("xmltemplate"), item->text(2)).toString());*/
610                 oldprops.insert("templatetext", clip->referencedClip()->getProperty("templatetext"));
611                 newprops.insert("templatetext", item->text(1));
612             }
613             slotUpdateClipProperties(clip->clipId(), newprops);
614             EditClipCommand *command = new EditClipCommand(this, clip->clipId(), oldprops, newprops, false);
615             m_commandStack->push(command);
616         }
617     } else if (column == 0) {
618         if (clip->referencedClip()) {
619             QMap <QString, QString> oldprops;
620             QMap <QString, QString> newprops;
621             oldprops["name"] = clip->referencedClip()->getProperty("name");
622             newprops["name"] = item->text(0);
623             slotUpdateClipProperties(clip, newprops);
624             emit projectModified();
625             EditClipCommand *command = new EditClipCommand(this, clip->clipId(), oldprops, newprops, false);
626             m_commandStack->push(command);
627         }
628     }
629 }
630
631 void ProjectList::slotContextMenu(const QPoint &pos, QTreeWidgetItem *item)
632 {
633     bool enable = false;
634     if (item) {
635         enable = true;
636     }
637     m_editAction->setEnabled(enable);
638     m_deleteAction->setEnabled(enable);
639     m_reloadAction->setEnabled(enable);
640     m_transcodeAction->setEnabled(enable);
641     if (enable) {
642         ProjectItem *clip = NULL;
643         if (m_listView->currentItem()->type() == PROJECTSUBCLIPTYPE) {
644             clip = static_cast <ProjectItem*>(item->parent());
645             m_transcodeAction->setEnabled(false);
646         } else if (m_listView->currentItem()->type() == PROJECTCLIPTYPE) {
647             clip = static_cast <ProjectItem*>(item);
648             // Display relevant transcoding actions only
649             adjustTranscodeActions(clip);
650             // Display uses in timeline
651             emit findInTimeline(clip->clipId());
652         } else m_transcodeAction->setEnabled(false);
653         if (clip && clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) {
654             m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
655             m_openAction->setEnabled(true);
656         } else if (clip && clip->clipType() == AUDIO && !KdenliveSettings::defaultaudioapp().isEmpty()) {
657             m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
658             m_openAction->setEnabled(true);
659         } else m_openAction->setEnabled(false);
660
661     } else m_openAction->setEnabled(false);
662     m_menu->popup(pos);
663 }
664
665 void ProjectList::slotRemoveClip()
666 {
667     if (!m_listView->currentItem()) return;
668     QStringList ids;
669     QMap <QString, QString> folderids;
670     QList<QTreeWidgetItem *> selected = m_listView->selectedItems();
671
672     QUndoCommand *delCommand = new QUndoCommand();
673     delCommand->setText(i18n("Delete Clip Zone"));
674
675     for (int i = 0; i < selected.count(); i++) {
676         if (selected.at(i)->type() == PROJECTSUBCLIPTYPE) {
677             // subitem
678             SubProjectItem *sub = static_cast <SubProjectItem *>(selected.at(i));
679             ProjectItem *item = static_cast <ProjectItem *>(sub->parent());
680             new AddClipCutCommand(this, item->clipId(), sub->zone().x(), sub->zone().y(), sub->description(), false, true, delCommand);
681         } else if (selected.at(i)->type() == PROJECTFOLDERTYPE) {
682             // folder
683             FolderProjectItem *folder = static_cast <FolderProjectItem *>(selected.at(i));
684             folderids[folder->groupName()] = folder->clipId();
685             int children = folder->childCount();
686
687             if (children > 0 && KMessageBox::questionYesNo(this, 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) return;
688             for (int i = 0; i < children; ++i) {
689                 ProjectItem *child = static_cast <ProjectItem *>(folder->child(i));
690                 ids << child->clipId();
691             }
692         } else {
693             ProjectItem *item = static_cast <ProjectItem *>(selected.at(i));
694             ids << item->clipId();
695             if (item->numReferences() > 0) {
696                 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;
697             }
698         }
699     }
700
701     if (delCommand->childCount() == 0) delete delCommand;
702     else m_commandStack->push(delCommand);
703     emit deleteProjectClips(ids, folderids);
704 }
705
706 void ProjectList::updateButtons() const
707 {
708     if (m_listView->topLevelItemCount() == 0) {
709         m_deleteAction->setEnabled(false);
710     } else {
711         m_deleteAction->setEnabled(true);
712         if (!m_listView->currentItem()) m_listView->setCurrentItem(m_listView->topLevelItem(0));
713         QTreeWidgetItem *item = m_listView->currentItem();
714         if (item && item->type() == PROJECTCLIPTYPE) {
715             m_editAction->setEnabled(true);
716             m_openAction->setEnabled(true);
717             m_reloadAction->setEnabled(true);
718             m_transcodeAction->setEnabled(true);
719             return;
720         }
721     }
722
723     m_editAction->setEnabled(false);
724     m_openAction->setEnabled(false);
725     m_reloadAction->setEnabled(false);
726     m_transcodeAction->setEnabled(false);
727 }
728
729 void ProjectList::selectItemById(const QString &clipId)
730 {
731     ProjectItem *item = getItemById(clipId);
732     if (item) m_listView->setCurrentItem(item);
733 }
734
735
736 void ProjectList::slotDeleteClip(const QString &clipId)
737 {
738     ProjectItem *item = getItemById(clipId);
739     if (!item) {
740         kDebug() << "/// Cannot find clip to delete";
741         return;
742     }
743     m_listView->blockSignals(true);
744     QTreeWidgetItem *newSelectedItem = m_listView->itemAbove(item);
745     if (!newSelectedItem) newSelectedItem = m_listView->itemBelow(item);
746     delete item;
747     m_doc->clipManager()->deleteClip(clipId);
748     m_listView->blockSignals(false);
749     if (newSelectedItem) {
750         m_listView->setCurrentItem(newSelectedItem);
751     } else {
752         updateButtons();
753         emit clipSelected(NULL);
754     }
755 }
756
757
758 void ProjectList::editFolder(const QString folderName, const QString oldfolderName, const QString &clipId)
759 {
760     EditFolderCommand *command = new EditFolderCommand(this, folderName, oldfolderName, clipId, false);
761     m_commandStack->push(command);
762     m_doc->setModified(true);
763 }
764
765 void ProjectList::slotAddFolder()
766 {
767     AddFolderCommand *command = new AddFolderCommand(this, i18n("Folder"), QString::number(m_doc->clipManager()->getFreeFolderId()), true);
768     m_commandStack->push(command);
769 }
770
771 void ProjectList::slotAddFolder(const QString foldername, const QString &clipId, bool remove, bool edit)
772 {
773     if (remove) {
774         FolderProjectItem *item = getFolderItemById(clipId);
775         if (item) {
776             m_doc->clipManager()->deleteFolder(clipId);
777             QTreeWidgetItem *newSelectedItem = m_listView->itemAbove(item);
778             if (!newSelectedItem) newSelectedItem = m_listView->itemBelow(item);
779             delete item;
780             if (newSelectedItem) m_listView->setCurrentItem(newSelectedItem);
781             else updateButtons();
782         }
783     } else {
784         if (edit) {
785             FolderProjectItem *item = getFolderItemById(clipId);
786             if (item) {
787                 m_listView->blockSignals(true);
788                 item->setGroupName(foldername);
789                 m_listView->blockSignals(false);
790                 m_doc->clipManager()->addFolder(clipId, foldername);
791                 const int children = item->childCount();
792                 for (int i = 0; i < children; i++) {
793                     ProjectItem *child = static_cast <ProjectItem *>(item->child(i));
794                     child->setProperty("groupname", foldername);
795                 }
796             }
797         } else {
798             m_listView->blockSignals(true);
799             m_listView->setCurrentItem(new FolderProjectItem(m_listView, QStringList() << foldername, clipId));
800             m_doc->clipManager()->addFolder(clipId, foldername);
801             m_listView->blockSignals(false);
802             m_listView->editItem(m_listView->currentItem(), 0);
803         }
804         updateButtons();
805     }
806     m_doc->setModified(true);
807 }
808
809
810
811 void ProjectList::deleteProjectFolder(QMap <QString, QString> map)
812 {
813     QMapIterator<QString, QString> i(map);
814     QUndoCommand *delCommand = new QUndoCommand();
815     delCommand->setText(i18n("Delete Folder"));
816     while (i.hasNext()) {
817         i.next();
818         new AddFolderCommand(this, i.key(), i.value(), false, delCommand);
819     }
820     m_commandStack->push(delCommand);
821 }
822
823 void ProjectList::slotAddClip(DocClipBase *clip, bool getProperties)
824 {
825     m_listView->setEnabled(false);
826     if (getProperties) {
827         m_listView->blockSignals(true);
828         m_refreshed = false;
829         // remove file_hash so that we load all properties for the clip
830         QDomElement e = clip->toXML().cloneNode().toElement();
831         e.removeAttribute("file_hash");
832         m_infoQueue.insert(clip->getId(), e);
833         //m_render->getFileProperties(clip->toXML(), clip->getId(), true);
834     }
835     clip->askForAudioThumbs();
836     const QString parent = clip->getProperty("groupid");
837     ProjectItem *item = NULL;
838     if (!parent.isEmpty()) {
839         FolderProjectItem *parentitem = getFolderItemById(parent);
840         if (!parentitem) {
841             QStringList text;
842             QString groupName = clip->getProperty("groupname");
843             //kDebug() << "Adding clip to new group: " << groupName;
844             if (groupName.isEmpty()) groupName = i18n("Folder");
845             text << groupName;
846             parentitem = new FolderProjectItem(m_listView, text, parent);
847         } else {
848             //kDebug() << "Adding clip to existing group: " << parentitem->groupName();
849         }
850         if (parentitem) item = new ProjectItem(parentitem, clip);
851     }
852     if (item == NULL) item = new ProjectItem(m_listView, clip);
853     KUrl url = clip->fileURL();
854
855     if (getProperties == false && !clip->getClipHash().isEmpty()) {
856         QString cachedPixmap = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "thumbs/" + clip->getClipHash() + ".png";
857         if (QFile::exists(cachedPixmap)) {
858             QPixmap pix(cachedPixmap);
859             if (pix.isNull()) KIO::NetAccess::del(KUrl(cachedPixmap), this);
860             item->setData(0, Qt::DecorationRole, pix);
861         }
862     }
863 #ifdef NEPOMUK
864     if (!url.isEmpty() && KdenliveSettings::activate_nepomuk()) {
865         // if file has Nepomuk comment, use it
866         Nepomuk::Resource f(url.path());
867         QString annotation = f.description();
868         if (!annotation.isEmpty()) item->setText(1, annotation);
869         item->setText(2, QString::number(f.rating()));
870     }
871 #endif
872     // Add cut zones
873     QList <CutZoneInfo> cuts = clip->cutZones();
874     if (!cuts.isEmpty()) {
875         for (int i = 0; i < cuts.count(); i++) {
876             SubProjectItem *sub = new SubProjectItem(item, cuts.at(i).zone.x(), cuts.at(i).zone.y(), cuts.at(i).description);
877             if (!clip->getClipHash().isEmpty()) {
878                 QString cachedPixmap = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "thumbs/" + clip->getClipHash() + '#' + QString::number(cuts.at(i).zone.x()) + ".png";
879                 if (QFile::exists(cachedPixmap)) {
880                     QPixmap pix(cachedPixmap);
881                     if (pix.isNull()) KIO::NetAccess::del(KUrl(cachedPixmap), this);
882                     sub->setData(0, Qt::DecorationRole, pix);
883                 }
884             }
885         }
886     }
887     if (m_listView->isEnabled()) {
888         updateButtons();
889         if (getProperties) m_listView->blockSignals(false);
890     }
891     if (getProperties && !m_queueTimer.isActive()) m_queueTimer.start();
892 }
893
894 void ProjectList::slotResetProjectList()
895 {
896     m_listView->clear();
897     emit clipSelected(NULL);
898     m_thumbnailQueue.clear();
899     m_infoQueue.clear();
900     m_refreshed = false;
901 }
902
903 void ProjectList::requestClipInfo(const QDomElement xml, const QString id)
904 {
905     m_refreshed = false;
906     m_infoQueue.insert(id, xml);
907     //if (m_infoQueue.count() == 1 || ) QTimer::singleShot(300, this, SLOT(slotProcessNextClipInQueue()));
908 }
909
910 void ProjectList::slotProcessNextClipInQueue()
911 {
912     if (m_infoQueue.isEmpty()) {
913         slotProcessNextThumbnail();
914         return;
915     }
916
917     QMap<QString, QDomElement>::const_iterator j = m_infoQueue.constBegin();
918     if (j != m_infoQueue.constEnd()) {
919         const QDomElement dom = j.value();
920         const QString id = j.key();
921         m_infoQueue.remove(j.key());
922         emit getFileProperties(dom, id, m_listView->iconSize().height(), false);
923     }
924 }
925
926 void ProjectList::slotUpdateClip(const QString &id)
927 {
928     ProjectItem *item = getItemById(id);
929     m_listView->blockSignals(true);
930     if (item) item->setData(0, UsageRole, QString::number(item->numReferences()));
931     m_listView->blockSignals(false);
932 }
933
934 void ProjectList::updateAllClips()
935 {
936     m_listView->setSortingEnabled(false);
937     kDebug() << "// UPDATE ALL CLPY";
938
939     QTreeWidgetItemIterator it(m_listView);
940     DocClipBase *clip;
941     ProjectItem *item;
942     m_listView->blockSignals(true);
943     while (*it) {
944         if ((*it)->type() == PROJECTSUBCLIPTYPE) {
945             // subitem
946             SubProjectItem *sub = static_cast <SubProjectItem *>(*it);
947             if (sub->data(0, Qt::DecorationRole).isNull()) {
948                 item = static_cast <ProjectItem *>((*it)->parent());
949                 requestClipThumbnail(item->clipId() + '#' + QString::number(sub->zone().x()));
950             }
951             ++it;
952             continue;
953         } else if ((*it)->type() == PROJECTFOLDERTYPE) {
954             // folder
955             ++it;
956             continue;
957         } else {
958             item = static_cast <ProjectItem *>(*it);
959             clip = item->referencedClip();
960             if (item->referencedClip()->producer() == NULL) {
961                 if (clip->isPlaceHolder() == false) {
962                     requestClipInfo(clip->toXML(), clip->getId());
963                 } else if (!clip->isPlaceHolder()) item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
964             } else {
965                 if (item->data(0, Qt::DecorationRole).isNull()) {
966                     requestClipThumbnail(clip->getId());
967                 }
968                 if (item->data(0, DurationRole).toString().isEmpty()) {
969                     item->changeDuration(item->referencedClip()->producer()->get_playtime());
970                 }
971             }
972             item->setData(0, UsageRole, QString::number(item->numReferences()));
973         }
974         //qApp->processEvents();
975         ++it;
976     }
977     if (!m_queueTimer.isActive()) m_queueTimer.start();
978     if (m_listView->isEnabled()) m_listView->blockSignals(false);
979     m_listView->setSortingEnabled(true);
980     if (m_infoQueue.isEmpty()) slotProcessNextThumbnail();
981 }
982
983 void ProjectList::slotAddClip(const QList <QUrl> givenList, const QString &groupName, const QString &groupId)
984 {
985     if (!m_commandStack) {
986         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
987     }
988     KUrl::List list;
989     if (givenList.isEmpty()) {
990         // Build list of mime types
991         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" << "image/x-xcf-gimp" << "image/x-vnd.adobe.photoshop" << "image/x-pcx" << "image/x-exr";
992
993         QString allExtensions;
994         foreach(const QString& mimeType, mimeTypes) {
995             KMimeType::Ptr mime(KMimeType::mimeType(mimeType));
996             if (mime) {
997                 allExtensions.append(mime->patterns().join(" "));
998                 allExtensions.append(' ');
999             }
1000         }
1001         const QString dialogFilter = allExtensions.simplified() + ' ' + QLatin1Char('|') + i18n("All Supported Files") + "\n* " + QLatin1Char('|') + i18n("All Files");
1002         list = KFileDialog::getOpenUrls(KUrl("kfiledialog:///clipfolder"), dialogFilter, this);
1003
1004     } else {
1005         for (int i = 0; i < givenList.count(); i++)
1006             list << givenList.at(i);
1007     }
1008
1009     foreach(const KUrl &file, list) {
1010         // Check there is no folder here
1011         KMimeType::Ptr type = KMimeType::findByUrl(file);
1012         if (type->is("inode/directory")) {
1013             // user dropped a folder
1014             list.removeAll(file);
1015         }
1016     }
1017
1018     if (list.isEmpty()) return;
1019
1020     if (givenList.isEmpty()) {
1021         QStringList groupInfo = getGroup();
1022         m_doc->slotAddClipList(list, groupInfo.at(0), groupInfo.at(1));
1023     } else m_doc->slotAddClipList(list, groupName, groupId);
1024 }
1025
1026 void ProjectList::slotRemoveInvalidClip(const QString &id, bool replace)
1027 {
1028     ProjectItem *item = getItemById(id);
1029     QTimer::singleShot(300, this, SLOT(slotProcessNextClipInQueue()));
1030     if (item) {
1031         const QString path = item->referencedClip()->fileURL().path();
1032         if (item->referencedClip()->isPlaceHolder()) replace = false;
1033         if (!path.isEmpty()) {
1034             if (replace) KMessageBox::sorry(this, i18n("Clip <b>%1</b><br />is invalid, will be removed from project.", path));
1035             else {
1036                 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;
1037             }
1038         }
1039         QStringList ids;
1040         ids << id;
1041         if (replace) emit deleteProjectClips(ids, QMap <QString, QString>());
1042     }
1043 }
1044
1045 void ProjectList::slotAddColorClip()
1046 {
1047     if (!m_commandStack) {
1048         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1049     }
1050     QDialog *dia = new QDialog(this);
1051     Ui::ColorClip_UI dia_ui;
1052     dia_ui.setupUi(dia);
1053     dia->setWindowTitle(i18n("Color Clip"));
1054     dia_ui.clip_name->setText(i18n("Color Clip"));
1055     dia_ui.clip_duration->setInputMask("");
1056     dia_ui.clip_duration->setValidator(m_timecode.validator());
1057     dia_ui.clip_duration->setText(m_timecode.reformatSeparators(KdenliveSettings::color_duration()));
1058     if (dia->exec() == QDialog::Accepted) {
1059         QString color = dia_ui.clip_color->color().name();
1060         color = color.replace(0, 1, "0x") + "ff";
1061         QStringList groupInfo = getGroup();
1062         m_doc->slotCreateColorClip(dia_ui.clip_name->text(), color, dia_ui.clip_duration->text(), groupInfo.at(0), groupInfo.at(1));
1063     }
1064     delete dia;
1065 }
1066
1067
1068 void ProjectList::slotAddSlideshowClip()
1069 {
1070     if (!m_commandStack) {
1071         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1072     }
1073     SlideshowClip *dia = new SlideshowClip(m_timecode, this);
1074
1075     if (dia->exec() == QDialog::Accepted) {
1076         QStringList groupInfo = getGroup();
1077         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));
1078     }
1079     delete dia;
1080 }
1081
1082 void ProjectList::slotAddTitleClip()
1083 {
1084     QStringList groupInfo = getGroup();
1085     m_doc->slotCreateTextClip(groupInfo.at(0), groupInfo.at(1));
1086 }
1087
1088 void ProjectList::slotAddTitleTemplateClip()
1089 {
1090     QStringList groupInfo = getGroup();
1091     if (!m_commandStack) {
1092         kDebug() << "!!!!!!!!!!!!!!!! NO CMD STK";
1093     }
1094
1095     // Get the list of existing templates
1096     QStringList filter;
1097     filter << "*.kdenlivetitle";
1098     const QString path = m_doc->projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1099     QStringList templateFiles = QDir(path).entryList(filter, QDir::Files);
1100
1101     QDialog *dia = new QDialog(this);
1102     Ui::TemplateClip_UI dia_ui;
1103     dia_ui.setupUi(dia);
1104     for (int i = 0; i < templateFiles.size(); ++i) {
1105         dia_ui.template_list->comboBox()->addItem(templateFiles.at(i), path + templateFiles.at(i));
1106     }
1107     if (!templateFiles.isEmpty())
1108         dia_ui.buttonBox->button(QDialogButtonBox::Ok)->setFocus();
1109     dia_ui.template_list->fileDialog()->setFilter("*.kdenlivetitle");
1110     //warning: setting base directory doesn't work??
1111     KUrl startDir(path);
1112     dia_ui.template_list->fileDialog()->setUrl(startDir);
1113     dia_ui.text_box->setHidden(true);
1114     if (dia->exec() == QDialog::Accepted) {
1115         QString textTemplate = dia_ui.template_list->comboBox()->itemData(dia_ui.template_list->comboBox()->currentIndex()).toString();
1116         if (textTemplate.isEmpty()) textTemplate = dia_ui.template_list->comboBox()->currentText();
1117         // Create a cloned template clip
1118         m_doc->slotCreateTextTemplateClip(groupInfo.at(0), groupInfo.at(1), KUrl(textTemplate));
1119     }
1120     delete dia;
1121 }
1122
1123 QStringList ProjectList::getGroup() const
1124 {
1125     QStringList result;
1126     QTreeWidgetItem *item = m_listView->currentItem();
1127     while (item && item->type() != PROJECTFOLDERTYPE) {
1128         item = item->parent();
1129     }
1130
1131     if (item) {
1132         FolderProjectItem *folder = static_cast <FolderProjectItem *>(item);
1133         result << folder->groupName();
1134         result << folder->clipId();
1135     } else result << QString() << QString();
1136     return result;
1137 }
1138
1139 void ProjectList::setDocument(KdenliveDoc *doc)
1140 {
1141     m_listView->blockSignals(true);
1142     m_listView->clear();
1143     m_listView->setSortingEnabled(false);
1144     emit clipSelected(NULL);
1145     m_thumbnailQueue.clear();
1146     m_infoQueue.clear();
1147     m_refreshed = false;
1148     m_fps = doc->fps();
1149     m_timecode = doc->timecode();
1150     m_commandStack = doc->commandStack();
1151     m_doc = doc;
1152
1153     QMap <QString, QString> flist = doc->clipManager()->documentFolderList();
1154     QMapIterator<QString, QString> f(flist);
1155     while (f.hasNext()) {
1156         f.next();
1157         (void) new FolderProjectItem(m_listView, QStringList() << f.value(), f.key());
1158     }
1159
1160     QList <DocClipBase*> list = doc->clipManager()->documentClipList();
1161     for (int i = 0; i < list.count(); i++) {
1162         slotAddClip(list.at(i), false);
1163     }
1164
1165     m_listView->blockSignals(false);
1166     m_toolbar->setEnabled(true);
1167     connect(m_doc->clipManager(), SIGNAL(reloadClip(const QString &)), this, SLOT(slotReloadClip(const QString &)));
1168     connect(m_doc->clipManager(), SIGNAL(missingClip(const QString &)), this, SLOT(slotMissingClip(const QString &)));
1169     connect(m_doc->clipManager(), SIGNAL(availableClip(const QString &)), this, SLOT(slotAvailableClip(const QString &)));
1170     connect(m_doc->clipManager(), SIGNAL(checkAllClips()), this, SLOT(updateAllClips()));
1171 }
1172
1173 QList <DocClipBase*> ProjectList::documentClipList() const
1174 {
1175     if (m_doc == NULL) return QList <DocClipBase*> ();
1176     return m_doc->clipManager()->documentClipList();
1177 }
1178
1179 QDomElement ProjectList::producersList()
1180 {
1181     QDomDocument doc;
1182     QDomElement prods = doc.createElement("producerlist");
1183     doc.appendChild(prods);
1184     kDebug() << "////////////  PRO LIST BUILD PRDSLIST ";
1185     QTreeWidgetItemIterator it(m_listView);
1186     while (*it) {
1187         if ((*it)->type() != PROJECTCLIPTYPE) {
1188             // subitem
1189             ++it;
1190             continue;
1191         }
1192         prods.appendChild(doc.importNode(((ProjectItem *)(*it))->toXml(), true));
1193         ++it;
1194     }
1195     return prods;
1196 }
1197
1198 void ProjectList::slotCheckForEmptyQueue()
1199 {
1200     if (!m_refreshed && m_thumbnailQueue.isEmpty() && m_infoQueue.isEmpty()) {
1201         m_refreshed = true;
1202         emit loadingIsOver();
1203         emit displayMessage(QString(), -1);
1204         m_listView->blockSignals(false);
1205         m_listView->setEnabled(true);
1206         updateButtons();
1207     } else if (!m_refreshed) QTimer::singleShot(300, this, SLOT(slotCheckForEmptyQueue()));
1208 }
1209
1210 void ProjectList::reloadClipThumbnails()
1211 {
1212     kDebug() << "//////////////  RELOAD CLIPS THUMBNAILS!!!";
1213     m_thumbnailQueue.clear();
1214     QTreeWidgetItemIterator it(m_listView);
1215     while (*it) {
1216         if ((*it)->type() != PROJECTCLIPTYPE) {
1217             // subitem
1218             ++it;
1219             continue;
1220         }
1221         m_thumbnailQueue << ((ProjectItem *)(*it))->clipId();
1222         ++it;
1223     }
1224     QTimer::singleShot(300, this, SLOT(slotProcessNextThumbnail()));
1225 }
1226
1227 void ProjectList::requestClipThumbnail(const QString id)
1228 {
1229     if (!m_thumbnailQueue.contains(id)) m_thumbnailQueue.append(id);
1230 }
1231
1232 void ProjectList::slotProcessNextThumbnail()
1233 {
1234     if (m_thumbnailQueue.isEmpty() && m_infoQueue.isEmpty()) {
1235         slotCheckForEmptyQueue();
1236         return;
1237     }
1238     if (!m_infoQueue.isEmpty()) {
1239         //QTimer::singleShot(300, this, SLOT(slotProcessNextThumbnail()));
1240         return;
1241     }
1242     if (m_thumbnailQueue.count() > 1) {
1243         int max = m_doc->clipManager()->clipsCount();
1244         emit displayMessage(i18n("Loading thumbnails"), (int)(100 *(max - m_thumbnailQueue.count()) / max));
1245     }
1246     slotRefreshClipThumbnail(m_thumbnailQueue.takeFirst(), false);
1247 }
1248
1249 void ProjectList::slotRefreshClipThumbnail(const QString &clipId, bool update)
1250 {
1251     QTreeWidgetItem *item = getAnyItemById(clipId);
1252     if (item) slotRefreshClipThumbnail(item, update);
1253     else slotProcessNextThumbnail();
1254 }
1255
1256 void ProjectList::slotRefreshClipThumbnail(QTreeWidgetItem *it, bool update)
1257 {
1258     if (it == NULL) return;
1259     ProjectItem *item = NULL;
1260     bool isSubItem = false;
1261     int frame;
1262     if (it->type() == PROJECTFOLDERTYPE) return;
1263     if (it->type() == PROJECTSUBCLIPTYPE) {
1264         item = static_cast <ProjectItem *>(it->parent());
1265         frame = static_cast <SubProjectItem *>(it)->zone().x();
1266         isSubItem = true;
1267     } else {
1268         item = static_cast <ProjectItem *>(it);
1269         frame = item->referencedClip()->getClipThumbFrame();
1270     }
1271
1272     if (item) {
1273         DocClipBase *clip = item->referencedClip();
1274         if (!clip) {
1275             slotProcessNextThumbnail();
1276             return;
1277         }
1278         QPixmap pix;
1279         int height = m_listView->iconSize().height();
1280         int width = (int)(height  * m_render->dar());
1281         if (clip->clipType() == AUDIO) pix = KIcon("audio-x-generic").pixmap(QSize(width, height));
1282         else if (clip->clipType() == IMAGE) pix = QPixmap::fromImage(KThumb::getFrame(item->referencedClip()->producer(), 0, width, height));
1283         else pix = item->referencedClip()->thumbProducer()->extractImage(frame, width, height);
1284
1285         if (!pix.isNull()) {
1286             m_listView->blockSignals(true);
1287             it->setData(0, Qt::DecorationRole, pix);
1288             if (m_listView->isEnabled()) m_listView->blockSignals(false);
1289             if (!isSubItem) m_doc->cachePixmap(item->getClipHash(), pix);
1290             else m_doc->cachePixmap(item->getClipHash() + '#' + QString::number(frame), pix);
1291         }
1292         if (update) emit projectModified();
1293         QTimer::singleShot(30, this, SLOT(slotProcessNextThumbnail()));
1294     }
1295 }
1296
1297 void ProjectList::slotReplyGetFileProperties(const QString &clipId, Mlt::Producer *producer, const QMap < QString, QString > &properties, const QMap < QString, QString > &metadata, bool replace)
1298 {
1299     QString toReload;
1300     ProjectItem *item = getItemById(clipId);
1301     if (item && producer) {
1302         m_listView->blockSignals(true);
1303         item->setProperties(properties, metadata);
1304         if (item->referencedClip()->isPlaceHolder() && producer->is_valid()) {
1305             item->referencedClip()->setValid();
1306             item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | Qt::ItemIsEditable);
1307             toReload = clipId;
1308         }
1309         //Q_ASSERT_X(item->referencedClip(), "void ProjectList::slotReplyGetFileProperties", QString("Item with groupName %1 does not have a clip associated").arg(item->groupName()).toLatin1());
1310         item->referencedClip()->setProducer(producer, replace);
1311         item->referencedClip()->askForAudioThumbs();
1312         if (!replace && item->data(0, Qt::DecorationRole).isNull()) {
1313             requestClipThumbnail(clipId);
1314         }
1315         if (!toReload.isEmpty()) {
1316             item->slotSetToolTip();
1317
1318         }
1319         //emit receivedClipDuration(clipId);
1320         if (m_listView->isEnabled() && replace) {
1321             // update clip in clip monitor
1322             emit clipSelected(NULL);
1323             emit clipSelected(item->referencedClip());
1324             //TODO: Make sure the line below has no side effect
1325             toReload = clipId;
1326         }
1327         /*else {
1328             // Check if duration changed.
1329             emit receivedClipDuration(clipId);
1330             delete producer;
1331         }*/
1332         if (m_listView->isEnabled()) m_listView->blockSignals(false);
1333         /*if (item->icon(0).isNull()) {
1334             requestClipThumbnail(clipId);
1335         }*/
1336     } else kDebug() << "////////  COULD NOT FIND CLIP TO UPDATE PRPS...";
1337     int max = m_doc->clipManager()->clipsCount();
1338     if (item && m_infoQueue.isEmpty() && m_thumbnailQueue.isEmpty()) {
1339         m_listView->setCurrentItem(item);
1340         emit clipSelected(item->referencedClip());
1341     } else emit displayMessage(i18n("Loading clips"), (int)(100 *(max - m_infoQueue.count()) / max));
1342     if (!toReload.isEmpty()) emit clipNeedsReload(toReload, true);
1343     // small delay so that the app can display the progress info
1344     QTimer::singleShot(30, this, SLOT(slotProcessNextClipInQueue()));
1345 }
1346
1347 void ProjectList::slotReplyGetImage(const QString &clipId, const QPixmap &pix)
1348 {
1349     ProjectItem *item = getItemById(clipId);
1350     if (item && !pix.isNull()) {
1351         m_listView->blockSignals(true);
1352         item->setData(0, Qt::DecorationRole, pix);
1353         m_doc->cachePixmap(item->getClipHash(), pix);
1354         if (m_listView->isEnabled()) m_listView->blockSignals(false);
1355     }
1356 }
1357
1358 QTreeWidgetItem *ProjectList::getAnyItemById(const QString &id)
1359 {
1360     QTreeWidgetItemIterator it(m_listView);
1361     QString lookId = id;
1362     if (id.contains('#')) {
1363         lookId = id.section('#', 0, 0);
1364     }
1365
1366     ProjectItem *result = NULL;
1367     while (*it) {
1368         if ((*it)->type() != PROJECTCLIPTYPE) {
1369             // subitem
1370             ++it;
1371             continue;
1372         }
1373         ProjectItem *item = static_cast<ProjectItem *>(*it);
1374         if (item->clipId() == lookId) {
1375             result = item;
1376             break;
1377         }
1378         ++it;
1379     }
1380     if (result == NULL || !id.contains('#')) return result;
1381     else for (int i = 0; i < result->childCount(); i++) {
1382             SubProjectItem *sub = static_cast <SubProjectItem *>(result->child(i));
1383             if (sub && sub->zone().x() == id.section('#', 1, 1).toInt()) {
1384                 return sub;
1385             }
1386         }
1387
1388     return NULL;
1389 }
1390
1391
1392 ProjectItem *ProjectList::getItemById(const QString &id)
1393 {
1394     ProjectItem *item;
1395     QTreeWidgetItemIterator it(m_listView);
1396     while (*it) {
1397         if ((*it)->type() != PROJECTCLIPTYPE) {
1398             // subitem
1399             ++it;
1400             continue;
1401         }
1402         item = static_cast<ProjectItem *>(*it);
1403         if (item->clipId() == id)
1404             return item;
1405         ++it;
1406     }
1407     return NULL;
1408 }
1409
1410 FolderProjectItem *ProjectList::getFolderItemById(const QString &id)
1411 {
1412     FolderProjectItem *item;
1413     QTreeWidgetItemIterator it(m_listView);
1414     while (*it) {
1415         if ((*it)->type() == PROJECTFOLDERTYPE) {
1416             item = static_cast<FolderProjectItem *>(*it);
1417             if (item->clipId() == id) return item;
1418         }
1419         ++it;
1420     }
1421     return NULL;
1422 }
1423
1424 void ProjectList::slotSelectClip(const QString &ix)
1425 {
1426     ProjectItem *clip = getItemById(ix);
1427     if (clip) {
1428         m_listView->setCurrentItem(clip);
1429         m_listView->scrollToItem(clip);
1430         m_editAction->setEnabled(true);
1431         m_deleteAction->setEnabled(true);
1432         m_reloadAction->setEnabled(true);
1433         m_transcodeAction->setEnabled(true);
1434         if (clip->clipType() == IMAGE && !KdenliveSettings::defaultimageapp().isEmpty()) {
1435             m_openAction->setIcon(KIcon(KdenliveSettings::defaultimageapp()));
1436             m_openAction->setEnabled(true);
1437         } else if (clip->clipType() == AUDIO && !KdenliveSettings::defaultaudioapp().isEmpty()) {
1438             m_openAction->setIcon(KIcon(KdenliveSettings::defaultaudioapp()));
1439             m_openAction->setEnabled(true);
1440         } else m_openAction->setEnabled(false);
1441     }
1442 }
1443
1444 QString ProjectList::currentClipUrl() const
1445 {
1446     ProjectItem *item;
1447     if (!m_listView->currentItem() || m_listView->currentItem()->type() == PROJECTFOLDERTYPE) return QString();
1448     if (m_listView->currentItem()->type() == PROJECTSUBCLIPTYPE) {
1449         // subitem
1450         item = static_cast <ProjectItem*>(m_listView->currentItem()->parent());
1451     } else item = static_cast <ProjectItem*>(m_listView->currentItem());
1452     if (item == NULL) return QString();
1453     return item->clipUrl().path();
1454 }
1455
1456 KUrl::List ProjectList::getConditionalUrls(const QString &condition) const
1457 {
1458     KUrl::List result;
1459     ProjectItem *item;
1460     QList<QTreeWidgetItem *> list = m_listView->selectedItems();
1461     for (int i = 0; i < list.count(); i++) {
1462         if (list.at(i)->type() == PROJECTFOLDERTYPE) continue;
1463         if (list.at(i)->type() == PROJECTSUBCLIPTYPE) {
1464             // subitem
1465             item = static_cast <ProjectItem*>(list.at(i)->parent());
1466         } else item = static_cast <ProjectItem*>(list.at(i));
1467         if (item == NULL) continue;
1468         if (item->type() == COLOR || item->type() == SLIDESHOW || item->type() == TEXT) continue;
1469         DocClipBase *clip = item->referencedClip();
1470         if (!condition.isEmpty()) {
1471             if (condition.startsWith("vcodec") && !clip->hasVideoCodec(condition.section("=", 1, 1))) continue;
1472             else if (condition.startsWith("acodec") && !clip->hasAudioCodec(condition.section("=", 1, 1))) continue;
1473         }
1474         result.append(item->clipUrl());
1475     }
1476     return result;
1477 }
1478
1479 void ProjectList::regenerateTemplate(const QString &id)
1480 {
1481     ProjectItem *clip = getItemById(id);
1482     if (clip) regenerateTemplate(clip);
1483 }
1484
1485 void ProjectList::regenerateTemplate(ProjectItem *clip)
1486 {
1487     //TODO: remove this unused method, only force_reload is necessary
1488     clip->referencedClip()->producer()->set("force_reload", 1);
1489 }
1490
1491 QDomDocument ProjectList::generateTemplateXml(QString path, const QString &replaceString)
1492 {
1493     QDomDocument doc;
1494     QFile file(path);
1495     if (!file.open(QIODevice::ReadOnly)) {
1496         kWarning() << "ERROR, CANNOT READ: " << path;
1497         return doc;
1498     }
1499     if (!doc.setContent(&file)) {
1500         kWarning() << "ERROR, CANNOT READ: " << path;
1501         file.close();
1502         return doc;
1503     }
1504     file.close();
1505     QDomNodeList texts = doc.elementsByTagName("content");
1506     for (int i = 0; i < texts.count(); i++) {
1507         QString data = texts.item(i).firstChild().nodeValue();
1508         data.replace("%s", replaceString);
1509         texts.item(i).firstChild().setNodeValue(data);
1510     }
1511     return doc;
1512 }
1513
1514
1515 void ProjectList::slotAddClipCut(const QString &id, int in, int out)
1516 {
1517     ProjectItem *clip = getItemById(id);
1518     if (clip == NULL) return;
1519     if (clip->referencedClip()->hasCutZone(QPoint(in, out))) return;
1520     AddClipCutCommand *command = new AddClipCutCommand(this, id, in, out, QString(), true, false);
1521     m_commandStack->push(command);
1522 }
1523
1524 void ProjectList::addClipCut(const QString &id, int in, int out, const QString desc, bool newItem)
1525 {
1526     ProjectItem *clip = getItemById(id);
1527     if (clip) {
1528         DocClipBase *base = clip->referencedClip();
1529         base->addCutZone(in, out);
1530         m_listView->blockSignals(true);
1531         SubProjectItem *sub = new SubProjectItem(clip, in, out, desc);
1532         if (newItem && desc.isEmpty() && !m_listView->isColumnHidden(1)) {
1533             if (!clip->isExpanded()) clip->setExpanded(true);
1534             m_listView->scrollToItem(sub);
1535             m_listView->editItem(sub, 1);
1536         }
1537         QPixmap p = clip->referencedClip()->thumbProducer()->extractImage(in, (int)(sub->sizeHint(0).height()  * m_render->dar()), sub->sizeHint(0).height() - 2);
1538         sub->setData(0, Qt::DecorationRole, p);
1539         m_doc->cachePixmap(clip->getClipHash() + '#' + QString::number(in), p);
1540         m_listView->blockSignals(false);
1541     }
1542     emit projectModified();
1543 }
1544
1545 void ProjectList::removeClipCut(const QString &id, int in, int out)
1546 {
1547     ProjectItem *clip = getItemById(id);
1548     if (clip) {
1549         DocClipBase *base = clip->referencedClip();
1550         base->removeCutZone(in, out);
1551         SubProjectItem *sub = getSubItem(clip, QPoint(in, out));
1552         if (sub) {
1553             m_listView->blockSignals(true);
1554             delete sub;
1555             m_listView->blockSignals(false);
1556         }
1557     }
1558     emit projectModified();
1559 }
1560
1561 SubProjectItem *ProjectList::getSubItem(ProjectItem *clip, QPoint zone)
1562 {
1563     SubProjectItem *sub = NULL;
1564     if (clip) {
1565         for (int i = 0; i < clip->childCount(); i++) {
1566             QTreeWidgetItem *it = clip->child(i);
1567             if (it->type() == PROJECTSUBCLIPTYPE) {
1568                 sub = static_cast <SubProjectItem*>(it);
1569                 if (sub->zone() == zone) break;
1570                 else sub = NULL;
1571             }
1572         }
1573     }
1574     return sub;
1575 }
1576
1577 void ProjectList::slotUpdateClipCut(QPoint p)
1578 {
1579     if (!m_listView->currentItem() || m_listView->currentItem()->type() != PROJECTSUBCLIPTYPE) return;
1580     SubProjectItem *sub = static_cast <SubProjectItem*>(m_listView->currentItem());
1581     ProjectItem *item = static_cast <ProjectItem *>(sub->parent());
1582     EditClipCutCommand *command = new EditClipCutCommand(this, item->clipId(), sub->zone(), p, sub->text(1), sub->text(1), true);
1583     m_commandStack->push(command);
1584 }
1585
1586 void ProjectList::doUpdateClipCut(const QString &id, const QPoint oldzone, const QPoint zone, const QString &comment)
1587 {
1588     ProjectItem *clip = getItemById(id);
1589     SubProjectItem *sub = getSubItem(clip, oldzone);
1590     if (sub == NULL || clip == NULL) return;
1591     DocClipBase *base = clip->referencedClip();
1592     base->updateCutZone(oldzone.x(), oldzone.y(), zone.x(), zone.y(), comment);
1593     m_listView->blockSignals(true);
1594     sub->setZone(zone);
1595     sub->setDescription(comment);
1596     m_listView->blockSignals(false);
1597     emit projectModified();
1598 }
1599
1600 #include "projectlist.moc"