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