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