]> git.sesse.net Git - kdenlive/blob - src/renderwidget.cpp
automatically select if we should export audio or not:
[kdenlive] / src / renderwidget.cpp
1 /***************************************************************************
2  *   Copyright (C) 2008 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
21 #include "renderwidget.h"
22 #include "kdenlivesettings.h"
23 #include "ui_saveprofile_ui.h"
24 #include "timecode.h"
25
26 #include <KStandardDirs>
27 #include <KDebug>
28 #include <KMessageBox>
29 #include <KComboBox>
30 #include <KRun>
31 #include <KIO/NetAccess>
32 #include <KColorScheme>
33 #include <KNotification>
34 #include <KStartupInfo>
35
36 #include <QDomDocument>
37 #include <QItemDelegate>
38 #include <QTreeWidgetItem>
39 #include <QListWidgetItem>
40 #include <QHeaderView>
41 #include <QMenu>
42 #include <QInputDialog>
43 #include <QProcess>
44 #include <QDBusConnectionInterface>
45 #include <QDBusInterface>
46
47 const int GroupRole = Qt::UserRole;
48 const int ExtensionRole = GroupRole + 1;
49 const int StandardRole = GroupRole + 2;
50 const int RenderRole = GroupRole + 3;
51 const int ParamsRole = GroupRole + 4;
52 const int EditableRole = GroupRole + 5;
53 const int MetaGroupRole = GroupRole + 6;
54 const int ExtraRole = GroupRole + 7;
55
56 // Running job status
57 const int WAITINGJOB = 0;
58 const int RUNNINGJOB = 1;
59 const int FINISHEDJOB = 2;
60
61
62 RenderWidget::RenderWidget(const QString &projectfolder, QWidget * parent) :
63         QDialog(parent),
64         m_projectFolder(projectfolder),
65         m_blockProcessing(false),
66         m_autoAudio(false)
67 {
68     m_view.setupUi(this);
69     setWindowTitle(i18n("Rendering"));
70     m_view.buttonDelete->setIcon(KIcon("trash-empty"));
71     m_view.buttonDelete->setToolTip(i18n("Delete profile"));
72     m_view.buttonDelete->setEnabled(false);
73
74     m_view.buttonEdit->setIcon(KIcon("document-properties"));
75     m_view.buttonEdit->setToolTip(i18n("Edit profile"));
76     m_view.buttonEdit->setEnabled(false);
77
78     m_view.buttonSave->setIcon(KIcon("document-new"));
79     m_view.buttonSave->setToolTip(i18n("Create new profile"));
80
81     m_view.buttonInfo->setIcon(KIcon("help-about"));
82     m_view.hide_log->setIcon(KIcon("go-down"));
83
84     m_view.buttonFavorite->setIcon(KIcon("favorites"));
85     m_view.buttonFavorite->setToolTip(i18n("Copy profile to favorites"));
86
87     if (KdenliveSettings::showrenderparams()) {
88         m_view.buttonInfo->setDown(true);
89     } else m_view.advanced_params->hide();
90
91     m_view.rescale_keep->setChecked(KdenliveSettings::rescalekeepratio());
92     connect(m_view.rescale_width, SIGNAL(valueChanged(int)), this, SLOT(slotUpdateRescaleWidth(int)));
93     connect(m_view.rescale_height, SIGNAL(valueChanged(int)), this, SLOT(slotUpdateRescaleHeight(int)));
94     m_view.rescale_keep->setIcon(KIcon("insert-link"));
95     m_view.rescale_keep->setToolTip(i18n("Preserve aspect ratio"));
96     connect(m_view.rescale_keep, SIGNAL(clicked()), this, SLOT(slotSwitchAspectRatio()));
97
98     connect(m_view.buttonRender, SIGNAL(clicked()), this, SLOT(slotPrepareExport()));
99     connect(m_view.buttonGenerateScript, SIGNAL(clicked()), this, SLOT(slotGenerateScript()));
100
101     m_view.abort_job->setEnabled(false);
102     m_view.start_script->setEnabled(false);
103     m_view.delete_script->setEnabled(false);
104
105     m_view.format_list->setAlternatingRowColors(true);
106     m_view.size_list->setAlternatingRowColors(true);
107
108     KColorScheme scheme(palette().currentColorGroup(), KColorScheme::Window);
109     QPalette p = m_view.errorLabel->palette();
110     p.setColor(QPalette::Background, scheme.background(KColorScheme::NegativeBackground).color());
111     m_view.errorLabel->setAutoFillBackground(true);
112     m_view.errorLabel->setPalette(p);
113     m_view.errorLabel->setHidden(true);
114
115     connect(m_view.export_audio, SIGNAL(stateChanged(int)), this, SLOT(slotUpdateAudioLabel(int)));
116     m_view.export_audio->setCheckState(Qt::PartiallyChecked);
117
118     parseProfiles();
119     parseScriptFiles();
120
121     connect(m_view.start_script, SIGNAL(clicked()), this, SLOT(slotStartScript()));
122     connect(m_view.delete_script, SIGNAL(clicked()), this, SLOT(slotDeleteScript()));
123     connect(m_view.scripts_list, SIGNAL(itemSelectionChanged()), this, SLOT(slotCheckScript()));
124     connect(m_view.running_jobs, SIGNAL(itemSelectionChanged()), this, SLOT(slotCheckJob()));
125     connect(m_view.running_jobs, SIGNAL(itemDoubleClicked(QTreeWidgetItem *, int)), this, SLOT(slotPlayRendering(QTreeWidgetItem *, int)));
126
127     connect(m_view.buttonInfo, SIGNAL(clicked()), this, SLOT(showInfoPanel()));
128
129     connect(m_view.buttonSave, SIGNAL(clicked()), this, SLOT(slotSaveProfile()));
130     connect(m_view.buttonEdit, SIGNAL(clicked()), this, SLOT(slotEditProfile()));
131     connect(m_view.buttonDelete, SIGNAL(clicked()), this, SLOT(slotDeleteProfile()));
132     connect(m_view.buttonFavorite, SIGNAL(clicked()), this, SLOT(slotCopyToFavorites()));
133
134     connect(m_view.abort_job, SIGNAL(clicked()), this, SLOT(slotAbortCurrentJob()));
135     connect(m_view.start_job, SIGNAL(clicked()), this, SLOT(slotStartCurrentJob()));
136     connect(m_view.clean_up, SIGNAL(clicked()), this, SLOT(slotCLeanUpJobs()));
137     connect(m_view.hide_log, SIGNAL(clicked()), this, SLOT(slotHideLog()));
138
139     connect(m_view.buttonClose, SIGNAL(clicked()), this, SLOT(hide()));
140     connect(m_view.buttonClose2, SIGNAL(clicked()), this, SLOT(hide()));
141     connect(m_view.buttonClose3, SIGNAL(clicked()), this, SLOT(hide()));
142     connect(m_view.rescale, SIGNAL(toggled(bool)), m_view.rescale_box, SLOT(setEnabled(bool)));
143     connect(m_view.destination_list, SIGNAL(activated(int)), this, SLOT(refreshCategory()));
144     connect(m_view.out_file, SIGNAL(textChanged(const QString &)), this, SLOT(slotUpdateButtons()));
145     connect(m_view.out_file, SIGNAL(urlSelected(const KUrl &)), this, SLOT(slotUpdateButtons(const KUrl &)));
146     connect(m_view.format_list, SIGNAL(currentRowChanged(int)), this, SLOT(refreshView()));
147     connect(m_view.size_list, SIGNAL(currentRowChanged(int)), this, SLOT(refreshParams()));
148
149     connect(m_view.size_list, SIGNAL(itemDoubleClicked(QListWidgetItem *)), this, SLOT(slotEditItem(QListWidgetItem *)));
150
151     connect(m_view.render_guide, SIGNAL(clicked(bool)), this, SLOT(slotUpdateGuideBox()));
152     connect(m_view.render_zone, SIGNAL(clicked(bool)), this, SLOT(slotUpdateGuideBox()));
153     connect(m_view.render_full, SIGNAL(clicked(bool)), this, SLOT(slotUpdateGuideBox()));
154
155     connect(m_view.guide_end, SIGNAL(activated(int)), this, SLOT(slotCheckStartGuidePosition()));
156     connect(m_view.guide_start, SIGNAL(activated(int)), this, SLOT(slotCheckEndGuidePosition()));
157
158     connect(m_view.format_selection, SIGNAL(activated(int)), this, SLOT(refreshView()));
159
160     m_view.buttonRender->setEnabled(false);
161     m_view.buttonGenerateScript->setEnabled(false);
162     m_view.rescale_box->setEnabled(false);
163     m_view.guides_box->setVisible(false);
164     m_view.open_dvd->setVisible(false);
165     m_view.create_chapter->setVisible(false);
166     m_view.open_browser->setVisible(false);
167     m_view.error_box->setVisible(false);
168
169     m_view.splitter->setStretchFactor(1, 5);
170     m_view.splitter->setStretchFactor(0, 2);
171
172     m_view.out_file->setMode(KFile::File);
173
174     m_view.running_jobs->setHeaderLabels(QStringList() << QString() << i18n("File") << i18n("Progress"));
175     m_jobsDelegate = new RenderViewDelegate(this);
176     m_view.running_jobs->setItemDelegate(m_jobsDelegate);
177
178     QHeaderView *header = m_view.running_jobs->header();
179     QFontMetrics fm = fontMetrics();
180     header->setResizeMode(0, QHeaderView::Fixed);
181     header->resizeSection(0, 30);
182     header->setResizeMode(1, QHeaderView::Interactive);
183     header->setResizeMode(2, QHeaderView::Fixed);
184     header->resizeSection(1, width() * 2 / 3 - 15);
185     header->setResizeMode(2, QHeaderView::Interactive);
186     //header->setResizeMode(1, QHeaderView::Fixed);
187
188
189     m_view.scripts_list->setHeaderLabels(QStringList() << QString() << i18n("Script Files"));
190     m_scriptsDelegate = new RenderViewDelegate(this);
191     m_view.scripts_list->setItemDelegate(m_scriptsDelegate);
192     header = m_view.scripts_list->header();
193     header->setResizeMode(0, QHeaderView::Fixed);
194     header->resizeSection(0, 30);
195
196     // Find path for Kdenlive renderer
197     m_renderer = QCoreApplication::applicationDirPath() + QString("/kdenlive_render");
198     if (!QFile::exists(m_renderer)) {
199         m_renderer = KStandardDirs::findExe("kdenlive_render");
200         if (m_renderer.isEmpty()) m_renderer = KStandardDirs::locate("exe", "kdenlive_render");
201         if (m_renderer.isEmpty()) m_renderer = "kdenlive_render";
202     }
203
204     QDBusConnectionInterface* interface = QDBusConnection::sessionBus().interface();
205     if (!interface || (!interface->isServiceRegistered("org.kde.ksmserver") && !interface->isServiceRegistered("org.gnome.SessionManager")))
206         m_view.shutdown->setEnabled(false);
207
208     focusFirstVisibleItem();
209 }
210
211 RenderWidget::~RenderWidget()
212 {
213     m_view.running_jobs->blockSignals(true);
214     m_view.scripts_list->blockSignals(true);
215     m_view.running_jobs->clear();
216     m_view.scripts_list->clear();
217     delete m_jobsDelegate;
218     delete m_scriptsDelegate;
219 }
220
221 void RenderWidget::slotEditItem(QListWidgetItem *item)
222 {
223     QString edit = item->data(EditableRole).toString();
224     if (edit.isEmpty() || !edit.endsWith("customprofiles.xml")) slotSaveProfile();
225     else slotEditProfile();
226 }
227
228 void RenderWidget::showInfoPanel()
229 {
230     if (m_view.advanced_params->isVisible()) {
231         m_view.advanced_params->setVisible(false);
232         m_view.buttonInfo->setDown(false);
233         KdenliveSettings::setShowrenderparams(false);
234     } else {
235         m_view.advanced_params->setVisible(true);
236         m_view.buttonInfo->setDown(true);
237         KdenliveSettings::setShowrenderparams(true);
238     }
239 }
240
241 void RenderWidget::setDocumentPath(const QString path)
242 {
243     if (m_view.out_file->url().directory() == KUrl(m_projectFolder).directory()) {
244         const QString fileName = m_view.out_file->url().fileName();
245         m_view.out_file->setUrl(KUrl(path + fileName));
246     }
247     m_projectFolder = path;
248     parseScriptFiles();
249
250 }
251
252 void RenderWidget::slotUpdateGuideBox()
253 {
254     m_view.guides_box->setVisible(m_view.render_guide->isChecked());
255 }
256
257 void RenderWidget::slotCheckStartGuidePosition()
258 {
259     if (m_view.guide_start->currentIndex() > m_view.guide_end->currentIndex())
260         m_view.guide_start->setCurrentIndex(m_view.guide_end->currentIndex());
261 }
262
263 void RenderWidget::slotCheckEndGuidePosition()
264 {
265     if (m_view.guide_end->currentIndex() < m_view.guide_start->currentIndex())
266         m_view.guide_end->setCurrentIndex(m_view.guide_start->currentIndex());
267 }
268
269 void RenderWidget::setGuides(QDomElement guidesxml, double duration)
270 {
271     m_view.guide_start->clear();
272     m_view.guide_end->clear();
273     QDomNodeList nodes = guidesxml.elementsByTagName("guide");
274     if (nodes.count() > 0) {
275         m_view.guide_start->addItem(i18n("Beginning"), "0");
276         m_view.render_guide->setEnabled(true);
277         m_view.create_chapter->setEnabled(true);
278     } else {
279         m_view.render_guide->setEnabled(false);
280         m_view.create_chapter->setEnabled(false);
281     }
282     double fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
283     for (int i = 0; i < nodes.count(); i++) {
284         QDomElement e = nodes.item(i).toElement();
285         if (!e.isNull()) {
286             GenTime pos = GenTime(e.attribute("time").toDouble());
287             const QString guidePos = Timecode::getStringTimecode(pos.frames(fps), fps);
288             m_view.guide_start->addItem(e.attribute("comment") + '/' + guidePos, e.attribute("time").toDouble());
289             m_view.guide_end->addItem(e.attribute("comment") + '/' + guidePos, e.attribute("time").toDouble());
290         }
291     }
292     if (nodes.count() > 0)
293         m_view.guide_end->addItem(i18n("End"), QString::number(duration));
294 }
295
296 /**
297  * Will be called when the user selects an output file via the file dialog.
298  * File extension will be added automatically.
299  */
300 void RenderWidget::slotUpdateButtons(KUrl url)
301 {
302     if (m_view.out_file->url().isEmpty()) {
303         m_view.buttonGenerateScript->setEnabled(false);
304         m_view.buttonRender->setEnabled(false);
305     } else {
306         updateButtons(); // This also checks whether the selected format is available
307     }
308     if (url != 0) {
309         QListWidgetItem *item = m_view.size_list->currentItem();
310         if (!item) {
311             m_view.buttonRender->setEnabled(false);
312             m_view.buttonGenerateScript->setEnabled(false);
313             return;
314         }
315         QString extension = item->data(ExtensionRole).toString();
316         url = filenameWithExtension(url, extension);
317         m_view.out_file->setUrl(url);
318     }
319 }
320
321 /**
322  * Will be called when the user changes the output file path in the text line.
323  * File extension must NOT be added, would make editing impossible!
324  */
325 void RenderWidget::slotUpdateButtons()
326 {
327     if (m_view.out_file->url().isEmpty()) {
328         m_view.buttonRender->setEnabled(false);
329         m_view.buttonGenerateScript->setEnabled(false);
330     } else {
331         updateButtons(); // This also checks whether the selected format is available
332     }
333 }
334
335 void RenderWidget::slotSaveProfile()
336 {
337     //TODO: update to correctly use metagroups
338     Ui::SaveProfile_UI ui;
339     QDialog *d = new QDialog(this);
340     ui.setupUi(d);
341
342     for (int i = 0; i < m_view.destination_list->count(); i++)
343         ui.destination_list->addItem(m_view.destination_list->itemIcon(i), m_view.destination_list->itemText(i), m_view.destination_list->itemData(i, Qt::UserRole));
344
345     ui.destination_list->setCurrentIndex(m_view.destination_list->currentIndex());
346     QString dest = ui.destination_list->itemData(ui.destination_list->currentIndex(), Qt::UserRole).toString();
347
348     QString customGroup = m_view.format_list->currentItem()->text();
349     if (customGroup.isEmpty()) customGroup = i18n("Custom");
350     ui.group_name->setText(customGroup);
351
352     ui.parameters->setText(m_view.advanced_params->toPlainText());
353     ui.extension->setText(m_view.size_list->currentItem()->data(ExtensionRole).toString());
354     ui.profile_name->setFocus();
355
356     if (d->exec() == QDialog::Accepted && !ui.profile_name->text().simplified().isEmpty()) {
357         QString newProfileName = ui.profile_name->text().simplified();
358         QString newGroupName = ui.group_name->text().simplified();
359         if (newGroupName.isEmpty()) newGroupName = i18n("Custom");
360         QString newMetaGroupId = ui.destination_list->itemData(ui.destination_list->currentIndex(), Qt::UserRole).toString();
361
362         QDomDocument doc;
363         QDomElement profileElement = doc.createElement("profile");
364         profileElement.setAttribute("name", newProfileName);
365         profileElement.setAttribute("category", newGroupName);
366         profileElement.setAttribute("destinationid", newMetaGroupId);
367         profileElement.setAttribute("extension", ui.extension->text().simplified());
368         profileElement.setAttribute("args", ui.parameters->toPlainText().simplified());
369         doc.appendChild(profileElement);
370         saveProfile(doc.documentElement());
371
372         parseProfiles(newMetaGroupId, newGroupName, newProfileName);
373     }
374     delete d;
375 }
376
377
378 void RenderWidget::saveProfile(QDomElement newprofile)
379 {
380     QString exportFile = KStandardDirs::locateLocal("appdata", "export/customprofiles.xml");
381     QDomDocument doc;
382     QFile file(exportFile);
383     doc.setContent(&file, false);
384     file.close();
385     QDomElement documentElement;
386     QDomElement profiles = doc.documentElement();
387     if (profiles.isNull() || profiles.tagName() != "profiles") {
388         doc.clear();
389         profiles = doc.createElement("profiles");
390         profiles.setAttribute("version", 1);
391         doc.appendChild(profiles);
392     }
393     int version = profiles.attribute("version", 0).toInt();
394     if (version < 1) {
395         kDebug() << "// OLD profile version";
396         doc.clear();
397         profiles = doc.createElement("profiles");
398         profiles.setAttribute("version", 1);
399         doc.appendChild(profiles);
400     }
401
402
403     QDomNodeList profilelist = doc.elementsByTagName("profile");
404     int i = 0;
405     while (!profilelist.item(i).isNull()) {
406         // make sure a profile with same name doesn't exist
407         documentElement = profilelist.item(i).toElement();
408         QString profileName = documentElement.attribute("name");
409         if (profileName == newprofile.attribute("name")) {
410             // a profile with that same name already exists
411             bool ok;
412             QString newProfileName = QInputDialog::getText(this, i18n("Profile already exists"), i18n("This profile name already exists. Change the name if you don't want to overwrite it."), QLineEdit::Normal, profileName, &ok);
413             if (!ok) return;
414             if (profileName == newProfileName) {
415                 profiles.removeChild(profilelist.item(i));
416                 break;
417             }
418         }
419         i++;
420     }
421
422     profiles.appendChild(newprofile);
423
424     //QCString save = doc.toString().utf8();
425
426     if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
427         KMessageBox::sorry(this, i18n("Unable to write to file %1", exportFile));
428         return;
429     }
430     QTextStream out(&file);
431     out << doc.toString();
432     if (file.error() != QFile::NoError) {
433         KMessageBox::error(this, i18n("Cannot write to file %1", exportFile));
434         file.close();
435         return;
436     }
437     file.close();
438 }
439
440 void RenderWidget::slotCopyToFavorites()
441 {
442     QListWidgetItem *item = m_view.size_list->currentItem();
443     if (!item) return;
444     QString currentGroup = m_view.format_list->currentItem()->text();
445
446     QString params = item->data(ParamsRole).toString();
447     QString extension = item->data(ExtensionRole).toString();
448     QString currentProfile = item->text();
449     QDomDocument doc;
450     QDomElement profileElement = doc.createElement("profile");
451     profileElement.setAttribute("name", currentProfile);
452     profileElement.setAttribute("category", i18n("Custom"));
453     profileElement.setAttribute("destinationid", "favorites");
454     profileElement.setAttribute("extension", extension);
455     profileElement.setAttribute("args", params);
456     doc.appendChild(profileElement);
457     saveProfile(doc.documentElement());
458     parseProfiles(m_view.destination_list->itemData(m_view.destination_list->currentIndex(), Qt::UserRole).toString(), currentGroup, currentProfile);
459 }
460
461 void RenderWidget::slotEditProfile()
462 {
463     QListWidgetItem *item = m_view.size_list->currentItem();
464     if (!item) return;
465     QString currentGroup = m_view.format_list->currentItem()->text();
466
467     QString params = item->data(ParamsRole).toString();
468     QString extension = item->data(ExtensionRole).toString();
469     QString currentProfile = item->text();
470
471     Ui::SaveProfile_UI ui;
472     QDialog *d = new QDialog(this);
473     ui.setupUi(d);
474
475     for (int i = 0; i < m_view.destination_list->count(); i++)
476         ui.destination_list->addItem(m_view.destination_list->itemIcon(i), m_view.destination_list->itemText(i), m_view.destination_list->itemData(i, Qt::UserRole));
477
478     ui.destination_list->setCurrentIndex(m_view.destination_list->currentIndex());
479     QString dest = ui.destination_list->itemData(ui.destination_list->currentIndex(), Qt::UserRole).toString();
480
481     QString customGroup = m_view.format_list->currentItem()->text();
482     if (customGroup.isEmpty()) customGroup = i18n("Custom");
483     ui.group_name->setText(customGroup);
484
485     ui.profile_name->setText(currentProfile);
486     ui.extension->setText(extension);
487     ui.parameters->setText(params);
488     ui.profile_name->setFocus();
489     d->setWindowTitle(i18n("Edit Profile"));
490     if (d->exec() == QDialog::Accepted) {
491         slotDeleteProfile(false);
492         QString exportFile = KStandardDirs::locateLocal("appdata", "export/customprofiles.xml");
493         QDomDocument doc;
494         QFile file(exportFile);
495         doc.setContent(&file, false);
496         file.close();
497         QDomElement documentElement;
498         QDomElement profiles = doc.documentElement();
499
500         if (profiles.isNull() || profiles.tagName() != "profiles") {
501             doc.clear();
502             profiles = doc.createElement("profiles");
503             profiles.setAttribute("version", 1);
504             doc.appendChild(profiles);
505         }
506
507         int version = profiles.attribute("version", 0).toInt();
508         if (version < 1) {
509             kDebug() << "// OLD profile version";
510             doc.clear();
511             profiles = doc.createElement("profiles");
512             profiles.setAttribute("version", 1);
513             doc.appendChild(profiles);
514         }
515
516         QString newProfileName = ui.profile_name->text().simplified();
517         QString newGroupName = ui.group_name->text().simplified();
518         if (newGroupName.isEmpty()) newGroupName = i18n("Custom");
519         QString newMetaGroupId = ui.destination_list->itemData(ui.destination_list->currentIndex(), Qt::UserRole).toString();
520         QDomNodeList profilelist = doc.elementsByTagName("profile");
521         int i = 0;
522         while (!profilelist.item(i).isNull()) {
523             // make sure a profile with same name doesn't exist
524             documentElement = profilelist.item(i).toElement();
525             QString profileName = documentElement.attribute("name");
526             if (profileName == newProfileName) {
527                 // a profile with that same name already exists
528                 bool ok;
529                 newProfileName = QInputDialog::getText(this, i18n("Profile already exists"), i18n("This profile name already exists. Change the name if you don't want to overwrite it."), QLineEdit::Normal, newProfileName, &ok);
530                 if (!ok) return;
531                 if (profileName == newProfileName) {
532                     profiles.removeChild(profilelist.item(i));
533                     break;
534                 }
535             }
536             i++;
537         }
538
539         QDomElement profileElement = doc.createElement("profile");
540         profileElement.setAttribute("name", newProfileName);
541         profileElement.setAttribute("category", newGroupName);
542         profileElement.setAttribute("destinationid", newMetaGroupId);
543         profileElement.setAttribute("extension", ui.extension->text().simplified());
544         profileElement.setAttribute("args", ui.parameters->toPlainText().simplified());
545         profiles.appendChild(profileElement);
546
547         //QCString save = doc.toString().utf8();
548         delete d;
549         if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
550             KMessageBox::error(this, i18n("Cannot write to file %1", exportFile));
551             return;
552         }
553         QTextStream out(&file);
554         out << doc.toString();
555         if (file.error() != QFile::NoError) {
556             KMessageBox::error(this, i18n("Cannot write to file %1", exportFile));
557             file.close();
558             return;
559         }
560         file.close();
561         parseProfiles(newMetaGroupId, newGroupName, newProfileName);
562     } else delete d;
563 }
564
565 void RenderWidget::slotDeleteProfile(bool refresh)
566 {
567     //TODO: delete a profile installed by KNewStuff the easy way
568     /*
569     QString edit = m_view.size_list->currentItem()->data(EditableRole).toString();
570     if (!edit.endsWith("customprofiles.xml")) {
571         // This is a KNewStuff installed file, process through KNS
572         KNS::Engine engine(0);
573         if (engine.init("kdenlive_render.knsrc")) {
574             KNS::Entry::List entries;
575         }
576         return;
577     }*/
578     QString currentGroup = m_view.format_list->currentItem()->text();
579     QString currentProfile = m_view.size_list->currentItem()->text();
580     QString metaGroupId = m_view.destination_list->itemData(m_view.destination_list->currentIndex(), Qt::UserRole).toString();
581
582     QString exportFile = KStandardDirs::locateLocal("appdata", "export/customprofiles.xml");
583     QDomDocument doc;
584     QFile file(exportFile);
585     doc.setContent(&file, false);
586     file.close();
587
588     QDomElement documentElement;
589     QDomNodeList profiles = doc.elementsByTagName("profile");
590     int i = 0;
591     QString groupName;
592     QString profileName;
593     QString destination;
594
595     while (!profiles.item(i).isNull()) {
596         documentElement = profiles.item(i).toElement();
597         profileName = documentElement.attribute("name");
598         groupName = documentElement.attribute("category");
599         destination = documentElement.attribute("destinationid");
600
601         if (profileName == currentProfile && groupName == currentGroup && destination == metaGroupId) {
602             kDebug() << "// GOT it: " << profileName;
603             doc.documentElement().removeChild(profiles.item(i));
604             break;
605         }
606         i++;
607     }
608
609     if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
610         KMessageBox::sorry(this, i18n("Unable to write to file %1", exportFile));
611         return;
612     }
613     QTextStream out(&file);
614     out << doc.toString();
615     if (file.error() != QFile::NoError) {
616         KMessageBox::error(this, i18n("Cannot write to file %1", exportFile));
617         file.close();
618         return;
619     }
620     file.close();
621     if (refresh) {
622         parseProfiles(metaGroupId, currentGroup);
623         focusFirstVisibleItem();
624     }
625 }
626
627 void RenderWidget::updateButtons()
628 {
629     if (!m_view.size_list->currentItem() || m_view.size_list->currentItem()->isHidden()) {
630         m_view.buttonSave->setEnabled(false);
631         m_view.buttonDelete->setEnabled(false);
632         m_view.buttonEdit->setEnabled(false);
633         m_view.buttonRender->setEnabled(false);
634         m_view.buttonGenerateScript->setEnabled(false);
635     } else {
636         m_view.buttonSave->setEnabled(true);
637         m_view.buttonRender->setEnabled(m_view.size_list->currentItem()->toolTip().isEmpty());
638         m_view.buttonGenerateScript->setEnabled(m_view.size_list->currentItem()->toolTip().isEmpty());
639         QString edit = m_view.size_list->currentItem()->data(EditableRole).toString();
640         if (edit.isEmpty() || !edit.endsWith("customprofiles.xml")) {
641             m_view.buttonDelete->setEnabled(false);
642             m_view.buttonEdit->setEnabled(false);
643         } else {
644             m_view.buttonDelete->setEnabled(true);
645             m_view.buttonEdit->setEnabled(true);
646         }
647     }
648 }
649
650
651 void RenderWidget::focusFirstVisibleItem()
652 {
653     if (m_view.size_list->currentItem()) {
654         updateButtons();
655         return;
656     }
657     m_view.size_list->setCurrentRow(0);
658     updateButtons();
659 }
660
661 void RenderWidget::slotPrepareExport(bool scriptExport)
662 {
663     if (!QFile::exists(KdenliveSettings::rendererpath())) {
664         KMessageBox::sorry(this, i18n("Cannot find the melt program required for rendering (part of Mlt)"));
665         return;
666     }
667     if (m_view.play_after->isChecked() && KdenliveSettings::defaultplayerapp().isEmpty()) {
668         KMessageBox::sorry(this, i18n("Cannot play video after rendering because the default video player application is not set.\nPlease define it in Kdenlive settings dialog."));
669     }
670     QString chapterFile;
671     if (m_view.create_chapter->isChecked()) chapterFile = m_view.out_file->url().path() + ".dvdchapter";
672
673     // mantisbt 1051
674     if (!KStandardDirs::makeDir(m_view.out_file->url().directory())) {
675         KMessageBox::sorry(this, i18n("The directory %1, could not be created.\nPlease make sure you have the required permissions.", m_view.out_file->url().directory()));
676         return;
677     }
678
679     emit prepareRenderingData(scriptExport, m_view.render_zone->isChecked(), chapterFile);
680 }
681
682
683 void RenderWidget::slotExport(bool scriptExport, int zoneIn, int zoneOut, const QString &playlistPath, const QString &scriptPath)
684 {
685     QListWidgetItem *item = m_view.size_list->currentItem();
686     if (!item) return;
687
688     QString dest = m_view.out_file->url().path();
689     if (dest.isEmpty()) return;
690
691     // Check whether target file has an extension.
692     // If not, ask whether extension should be added or not.
693     QString extension = item->data(ExtensionRole).toString();
694     if (!dest.endsWith(extension, Qt::CaseInsensitive)) {
695         if (KMessageBox::questionYesNo(this, i18n("File has no extension. Add extension (%1)?", extension)) == KMessageBox::Yes) {
696             dest.append("." + extension);
697         }
698     }
699
700     QFile f(dest);
701     if (f.exists()) {
702         if (KMessageBox::warningYesNo(this, i18n("Output file already exists. Do you want to overwrite it?")) != KMessageBox::Yes)
703             return;
704     }
705
706     QStringList overlayargs;
707     if (m_view.tc_overlay->isChecked()) {
708         QString filterFile = KStandardDirs::locate("appdata", "metadata.properties");
709         overlayargs << "meta.attr.timecode=1" << "meta.attr.timecode.markup=#timecode";
710         overlayargs << "-attach" << "data_feed:attr_check" << "-attach";
711         overlayargs << "data_show:" + filterFile << "_loader=1" << "dynamic=1";
712     }
713
714     QStringList render_process_args;
715
716     if (!scriptExport) render_process_args << "-erase";
717     if (KdenliveSettings::usekuiserver()) render_process_args << "-kuiserver";
718
719     double guideStart = 0;
720     double guideEnd = 0;
721
722     if (m_view.render_zone->isChecked()) render_process_args << "in=" + QString::number(zoneIn) << "out=" + QString::number(zoneOut);
723     else if (m_view.render_guide->isChecked()) {
724         double fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
725         guideStart = m_view.guide_start->itemData(m_view.guide_start->currentIndex()).toDouble();
726         guideEnd = m_view.guide_end->itemData(m_view.guide_end->currentIndex()).toDouble();
727         render_process_args << "in=" + QString::number(GenTime(guideStart).frames(fps)) << "out=" + QString::number(GenTime(guideEnd).frames(fps));
728     }
729
730     if (!overlayargs.isEmpty()) render_process_args << "preargs=" + overlayargs.join(" ");
731
732     render_process_args << KdenliveSettings::rendererpath() << m_profile.path << item->data(RenderRole).toString();
733     if (m_view.play_after->isChecked()) render_process_args << KdenliveSettings::KdenliveSettings::defaultplayerapp();
734     else render_process_args << "-";
735
736     QString renderArgs = m_view.advanced_params->toPlainText().simplified();
737
738     // Adjust frame scale
739     int width;
740     int height;
741     if (m_view.rescale->isChecked() && m_view.rescale->isEnabled()) {
742         width = m_view.rescale_width->value();
743         height = m_view.rescale_height->value();
744     } else {
745         width = m_profile.width;
746         height = m_profile.height;
747     }
748     renderArgs.replace("%dar", '@' + QString::number(m_profile.display_aspect_num) + '/' + QString::number(m_profile.display_aspect_den));
749
750     // Adjust scanning
751     if (m_view.scanning_list->currentIndex() == 1) renderArgs.append(" progressive=1");
752     else if (m_view.scanning_list->currentIndex() == 2) renderArgs.append(" progressive=0");
753
754     // disable audio if requested
755     if (m_view.export_audio->checkState() == Qt::Unchecked || (m_view.export_audio->checkState() == Qt::PartiallyChecked && !m_autoAudio))
756         renderArgs.append(" an=1 ");
757
758     // Check if the rendering profile is different from project profile,
759     // in which case we need to use the producer_comsumer from MLT
760     QString std = renderArgs;
761     QString destination = m_view.destination_list->itemData(m_view.destination_list->currentIndex()).toString();
762     const QString currentSize = QString::number(width) + 'x' + QString::number(height);
763     QString subsize = currentSize;
764     if (std.startsWith("s=")) {
765         subsize = std.section(' ', 0, 0).toLower();
766         subsize = subsize.section("=", 1, 1);
767     } else if (std.contains(" s=")) {
768         subsize = std.section(" s=", 1, 1);
769         subsize = subsize.section(' ', 0, 0).toLower();
770     } else if (destination != "audioonly" && m_view.rescale->isChecked() && m_view.rescale->isEnabled()) {
771         subsize = QString(" s=%1x%2").arg(width).arg(height);
772         // Add current size parameter
773         renderArgs.append(subsize);
774     }
775     bool resizeProfile = (subsize != currentSize);
776     QStringList paramsList = renderArgs.split(" ", QString::SkipEmptyParts);
777     for (int i = 0; i < paramsList.count(); i++) {
778         if (paramsList.at(i).startsWith("profile=")) {
779             if (paramsList.at(i).section('=', 1) != m_profile.path) resizeProfile = true;
780             break;
781         }
782     }
783
784     if (resizeProfile) render_process_args << "consumer:" + playlistPath;
785     else render_process_args << playlistPath;
786     render_process_args << dest;
787     render_process_args << paramsList;
788
789     QString group = m_view.size_list->currentItem()->data(MetaGroupRole).toString();
790
791     QStringList renderParameters;
792     renderParameters << dest << item->data(RenderRole).toString() << renderArgs.simplified();
793     renderParameters << QString::number(zoneIn) << QString::number(zoneOut) << QString::number(m_view.play_after->isChecked());
794     renderParameters << QString::number(guideStart) << QString::number(guideEnd) << QString::number(resizeProfile);
795
796     QString scriptName;
797     if (scriptExport) {
798         // Generate script file
799         QFile file(scriptPath);
800         if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
801             KMessageBox::error(this, i18n("Cannot write to file %1", scriptPath));
802             return;
803         }
804         QTextStream outStream(&file);
805         outStream << "#! /bin/sh" << "\n" << "\n";
806         outStream << "SOURCE=" << "\"" + playlistPath + "\"" << "\n";
807         outStream << "TARGET=" << "\"" + dest + "\"" << "\n";
808         outStream << "RENDERER=" << "\"" + m_renderer + "\"" << "\n";
809         outStream << "MELT=" << "\"" + render_process_args.takeFirst() + "\"" << "\n";
810         outStream << "PARAMETERS=" << "\"" + render_process_args.join(" ") + "\"" << "\n";
811         outStream << "$RENDERER $MELT $PARAMETERS" << "\n" << "\n";
812         if (file.error() != QFile::NoError) {
813             KMessageBox::error(this, i18n("Cannot write to file %1", scriptPath));
814             file.close();
815             return;
816         }
817         file.close();
818         QFile::setPermissions(scriptPath, file.permissions() | QFile::ExeUser);
819
820         QTimer::singleShot(400, this, SLOT(parseScriptFiles()));
821         m_view.tabWidget->setCurrentIndex(2);
822         return;
823     }
824     renderParameters << scriptName;
825     m_view.tabWidget->setCurrentIndex(1);
826
827     // Save rendering profile to document
828     emit selectedRenderProfile(m_view.size_list->currentItem()->data(MetaGroupRole).toString(), m_view.size_list->currentItem()->data(GroupRole).toString(), m_view.size_list->currentItem()->text(), dest);
829
830     // insert item in running jobs list
831     QTreeWidgetItem *renderItem;
832     QList<QTreeWidgetItem *> existing = m_view.running_jobs->findItems(dest, Qt::MatchExactly, 1);
833     if (!existing.isEmpty()) {
834         renderItem = existing.at(0);
835         if (renderItem->data(1, Qt::UserRole + 2).toInt() == RUNNINGJOB) {
836             KMessageBox::information(this, i18n("There is already a job writing file:<br /><b>%1</b><br />Abort the job if you want to overwrite it...", dest), i18n("Already running"));
837             return;
838         }
839         renderItem->setData(1, Qt::UserRole + 4, QString());
840     } else {
841         renderItem = new QTreeWidgetItem(m_view.running_jobs, QStringList() << QString() << dest << QString());
842     }
843     renderItem->setData(1, Qt::UserRole + 2, WAITINGJOB);
844     renderItem->setIcon(0, KIcon("media-playback-pause"));
845     renderItem->setData(1, Qt::UserRole, i18n("Waiting..."));
846     renderItem->setSizeHint(1, QSize(m_view.running_jobs->columnWidth(1), fontMetrics().height() * 2));
847     renderItem->setData(1, Qt::UserRole + 1, QTime::currentTime());
848
849     // Set rendering type
850     if (group == "dvd") {
851         if (m_view.open_dvd->isChecked()) {
852             renderItem->setData(0, Qt::UserRole, group);
853             if (renderArgs.contains("profile=")) {
854                 // rendering profile contains an MLT profile, so pass it to the running jog item, useful for dvd
855                 QString prof = renderArgs.section("profile=", 1, 1);
856                 prof = prof.section(' ', 0, 0);
857                 kDebug() << "// render profile: " << prof;
858                 renderItem->setData(0, Qt::UserRole + 1, prof);
859             }
860         }
861     } else {
862         if (group == "websites" && m_view.open_browser->isChecked()) {
863             renderItem->setData(0, Qt::UserRole, group);
864             // pass the url
865             QString url = m_view.size_list->currentItem()->data(ExtraRole).toString();
866             renderItem->setData(0, Qt::UserRole + 1, url);
867         }
868     }
869     renderItem->setData(1, Qt::UserRole + 3, render_process_args);
870     checkRenderStatus();
871 }
872
873 void RenderWidget::checkRenderStatus()
874 {
875     // check if we have a job waiting to render
876     if (m_blockProcessing) return;
877     QTreeWidgetItem *item = m_view.running_jobs->topLevelItem(0);
878     while (item) {
879         if (item->data(1, Qt::UserRole + 2).toInt() == RUNNINGJOB) return;
880         item = m_view.running_jobs->itemBelow(item);
881     }
882     item = m_view.running_jobs->topLevelItem(0);
883     bool waitingJob = false;
884     while (item) {
885         if (item->data(1, Qt::UserRole + 2).toInt() == WAITINGJOB) {
886             item->setData(1, Qt::UserRole + 1, QTime::currentTime());
887             waitingJob = true;
888             startRendering(item);
889             break;
890         }
891         item = m_view.running_jobs->itemBelow(item);
892     }
893     if (waitingJob == false && m_view.shutdown->isChecked()) emit shutdown();
894 }
895
896 void RenderWidget::startRendering(QTreeWidgetItem *item)
897 {
898     if (item->data(1, Qt::UserRole + 4).isNull()) {
899         // Normal render process
900         if (QProcess::startDetached(m_renderer, item->data(1, Qt::UserRole + 3).toStringList()) == false) {
901             item->setData(1, Qt::UserRole + 2, FINISHEDJOB);
902             item->setData(1, Qt::UserRole, i18n("Rendering crashed"));
903             item->setIcon(0, KIcon("dialog-close"));
904             item->setData(2, Qt::UserRole, 100);
905         } else KNotification::event("RenderStarted", i18n("Rendering <i>%1</i> started", item->text(1)), QPixmap(), this);
906     } else {
907         // Script item
908         if (QProcess::startDetached(item->data(1, Qt::UserRole + 3).toString()) == false) {
909             item->setData(1, Qt::UserRole + 2, FINISHEDJOB);
910             item->setData(1, Qt::UserRole, i18n("Rendering crashed"));
911             item->setIcon(0, KIcon("dialog-close"));
912             item->setData(2, Qt::UserRole, 100);
913         }
914     }
915 }
916
917 int RenderWidget::waitingJobsCount() const
918 {
919     int count = 0;
920     QTreeWidgetItem *item = m_view.running_jobs->topLevelItem(0);
921     while (item) {
922         if (item->data(1, Qt::UserRole + 2).toInt() == WAITINGJOB) count++;
923         item = m_view.running_jobs->itemBelow(item);
924     }
925     return count;
926 }
927
928 void RenderWidget::setProfile(MltVideoProfile profile)
929 {
930     m_profile = profile;
931     //WARNING: this way to tell the video standard is a bit hackish...
932     if (m_profile.description.contains("pal", Qt::CaseInsensitive) || m_profile.description.contains("25", Qt::CaseInsensitive) || m_profile.description.contains("50", Qt::CaseInsensitive)) m_view.format_selection->setCurrentIndex(0);
933     else m_view.format_selection->setCurrentIndex(1);
934     m_view.scanning_list->setCurrentIndex(0);
935     m_view.rescale_width->setValue(KdenliveSettings::defaultrescalewidth());
936     if (!m_view.rescale_keep->isChecked()) {
937         m_view.rescale_height->blockSignals(true);
938         m_view.rescale_height->setValue(KdenliveSettings::defaultrescaleheight());
939         m_view.rescale_height->blockSignals(false);
940     }
941     refreshView();
942 }
943
944 void RenderWidget::refreshCategory()
945 {
946     m_view.format_list->blockSignals(true);
947     m_view.format_list->clear();
948     QListWidgetItem *sizeItem;
949
950     QString destination;
951     if (m_view.destination_list->currentIndex() > 0)
952         destination = m_view.destination_list->itemData(m_view.destination_list->currentIndex()).toString();
953
954
955     if (destination == "dvd") {
956         m_view.open_dvd->setVisible(true);
957         m_view.create_chapter->setVisible(true);
958     } else {
959         m_view.open_dvd->setVisible(false);
960         m_view.create_chapter->setVisible(false);
961     }
962
963     if (destination == "websites")
964         m_view.open_browser->setVisible(true);
965     else
966         m_view.open_browser->setVisible(false);
967
968     // hide groups that are not in the correct destination
969     for (int i = 0; i < m_renderCategory.count(); i++) {
970         sizeItem = m_renderCategory.at(i);
971         if (sizeItem->data(MetaGroupRole).toString() == destination) {
972             m_view.format_list->addItem(sizeItem->clone());
973             //kDebug() << "// SET GRP:: " << sizeItem->text() << ", METY:" << sizeItem->data(MetaGroupRole).toString();
974         }
975     }
976
977     // activate first visible item
978     QListWidgetItem * item = m_view.format_list->currentItem();
979     if (!item) {
980         m_view.format_list->setCurrentRow(0);
981         item = m_view.format_list->currentItem();
982     }
983     if (!item) {
984         m_view.format_list->setEnabled(false);
985         m_view.size_list->setEnabled(false);
986         m_view.size_list->blockSignals(false);
987         m_view.format_list->blockSignals(false);
988         return;
989     } else {
990         m_view.format_list->setEnabled(true);
991         m_view.size_list->setEnabled(true);
992     }
993
994     if (m_view.format_list->count() > 1)
995         m_view.format_list->setVisible(true);
996     else
997         m_view.format_list->setVisible(false);
998     refreshView();
999 }
1000
1001 void RenderWidget::refreshView()
1002 {
1003     if (!m_view.format_list->currentItem()) return;
1004     m_view.size_list->blockSignals(true);
1005     m_view.size_list->clear();
1006     QListWidgetItem *sizeItem;
1007     QString std;
1008     QString group = m_view.format_list->currentItem()->text();
1009     QString destination;
1010     if (m_view.destination_list->currentIndex() > 0)
1011         destination = m_view.destination_list->itemData(m_view.destination_list->currentIndex()).toString();
1012     KIcon brokenIcon("dialog-close");
1013
1014     const QStringList formatsList = KdenliveSettings::supportedformats();
1015     const QStringList vcodecsList = KdenliveSettings::videocodecs();
1016     const QStringList acodecsList = KdenliveSettings::audiocodecs();
1017
1018     KColorScheme scheme(palette().currentColorGroup(), KColorScheme::Window);
1019     const QColor disabled = scheme.foreground(KColorScheme::InactiveText).color();
1020     const QColor disabledbg = scheme.background(KColorScheme::NegativeBackground).color();
1021
1022
1023     for (int i = 0; i < m_renderItems.count(); i++) {
1024         sizeItem = m_renderItems.at(i);
1025         QListWidgetItem *dupItem = NULL;
1026         if ((sizeItem->data(GroupRole).toString() == group || sizeItem->data(GroupRole).toString().isEmpty()) && sizeItem->data(MetaGroupRole).toString() == destination) {
1027             std = sizeItem->data(StandardRole).toString();
1028             if (!std.isEmpty()) {
1029                 if (std.contains("PAL", Qt::CaseInsensitive) && m_view.format_selection->currentIndex() == 0) dupItem = sizeItem->clone();
1030                 else if (std.contains("NTSC", Qt::CaseInsensitive) && m_view.format_selection->currentIndex() == 1)  dupItem = sizeItem->clone();
1031             } else {
1032                 dupItem = sizeItem->clone();
1033             }
1034
1035             if (dupItem) {
1036                 m_view.size_list->addItem(dupItem);
1037                 // Make sure the selected profile uses an installed avformat codec / format
1038                 std = dupItem->data(ParamsRole).toString();
1039                 if (!formatsList.isEmpty()) {
1040                     QString format;
1041                     if (std.startsWith("f=")) format = std.section("f=", 1, 1);
1042                     else if (std.contains(" f=")) format = std.section(" f=", 1, 1);
1043                     if (!format.isEmpty()) {
1044                         format = format.section(' ', 0, 0).toLower();
1045                         if (!formatsList.contains(format)) {
1046                             kDebug() << "***** UNSUPPORTED F: " << format;
1047                             //sizeItem->setHidden(true);
1048                             //sizeItem->setFlags(Qt::ItemIsSelectable);
1049                             dupItem->setToolTip(i18n("Unsupported video format: %1", format));
1050                             dupItem->setIcon(brokenIcon);
1051                             dupItem->setForeground(disabled);
1052                         }
1053                     }
1054                 }
1055                 if (!acodecsList.isEmpty()) {
1056                     QString format;
1057                     if (std.startsWith("acodec=")) format = std.section("acodec=", 1, 1);
1058                     else if (std.contains(" acodec=")) format = std.section(" acodec=", 1, 1);
1059                     if (!format.isEmpty()) {
1060                         format = format.section(' ', 0, 0).toLower();
1061                         if (!acodecsList.contains(format)) {
1062                             kDebug() << "*****  UNSUPPORTED ACODEC: " << format;
1063                             //sizeItem->setHidden(true);
1064                             //sizeItem->setFlags(Qt::ItemIsSelectable);
1065                             dupItem->setToolTip(i18n("Unsupported audio codec: %1", format));
1066                             dupItem->setIcon(brokenIcon);
1067                             dupItem->setForeground(disabled);
1068                             dupItem->setBackground(disabledbg);
1069                         }
1070                     }
1071                 }
1072                 if (!vcodecsList.isEmpty()) {
1073                     QString format;
1074                     if (std.startsWith("vcodec=")) format = std.section("vcodec=", 1, 1);
1075                     else if (std.contains(" vcodec=")) format = std.section(" vcodec=", 1, 1);
1076                     if (!format.isEmpty()) {
1077                         format = format.section(' ', 0, 0).toLower();
1078                         if (!vcodecsList.contains(format)) {
1079                             kDebug() << "*****  UNSUPPORTED VCODEC: " << format;
1080                             //sizeItem->setHidden(true);
1081                             //sizeItem->setFlags(Qt::ItemIsSelectable);
1082                             dupItem->setToolTip(i18n("Unsupported video codec: %1", format));
1083                             dupItem->setIcon(brokenIcon);
1084                             dupItem->setForeground(disabled);
1085                         }
1086                     }
1087                 }
1088             }
1089         }
1090     }
1091     // m_view.size_list->sortItems();
1092     focusFirstVisibleItem();
1093     m_view.size_list->blockSignals(false);
1094     m_view.format_list->blockSignals(false);
1095     refreshParams();
1096 }
1097
1098 KUrl RenderWidget::filenameWithExtension(KUrl url, QString extension)
1099 {
1100     if (url.isEmpty()) url = KUrl(m_projectFolder);
1101     QString directory = url.directory(KUrl::AppendTrailingSlash | KUrl::ObeyTrailingSlash);
1102     QString filename = url.fileName(KUrl::ObeyTrailingSlash);
1103     QString ext;
1104
1105     if (extension.at(0) == '.') ext = extension;
1106     else ext = '.' + extension;
1107
1108     if (filename.isEmpty()) filename = i18n("untitled");
1109
1110     int pos = filename.lastIndexOf('.');
1111     if (pos == 0) filename.append(ext);
1112     else {
1113         if (!filename.endsWith(ext, Qt::CaseInsensitive)) {
1114             filename = filename.left(pos) + ext;
1115         }
1116     }
1117
1118     return KUrl(directory + filename);
1119 }
1120
1121 void RenderWidget::refreshParams()
1122 {
1123     // Format not available (e.g. codec not installed); Disable start button
1124     QListWidgetItem *item = m_view.size_list->currentItem();
1125     if (!item || item->isHidden()) {
1126         m_view.advanced_params->clear();
1127         m_view.buttonRender->setEnabled(false);
1128         m_view.buttonGenerateScript->setEnabled(false);
1129         return;
1130     }
1131     QString params = item->data(ParamsRole).toString();
1132     QString extension = item->data(ExtensionRole).toString();
1133     m_view.advanced_params->setPlainText(params);
1134     QString destination = m_view.destination_list->itemData(m_view.destination_list->currentIndex()).toString();
1135     if (params.contains(" s=") || params.startsWith("s=") || destination == "audioonly") {
1136         // profile has a fixed size, do not allow resize
1137         m_view.rescale->setEnabled(false);
1138         m_view.rescale_box->setEnabled(false);
1139     } else {
1140         m_view.rescale->setEnabled(true);
1141         m_view.rescale_box->setEnabled(m_view.rescale->isChecked());
1142     }
1143     KUrl url = filenameWithExtension(m_view.out_file->url(), extension);
1144     m_view.out_file->setUrl(url);
1145 //     if (!url.isEmpty()) {
1146 //         QString path = url.path();
1147 //         int pos = path.lastIndexOf('.') + 1;
1148 //  if (pos == 0) path.append('.' + extension);
1149 //         else path = path.left(pos) + extension;
1150 //         m_view.out_file->setUrl(KUrl(path));
1151 //     } else {
1152 //         m_view.out_file->setUrl(KUrl(QDir::homePath() + "/untitled." + extension));
1153 //     }
1154     m_view.out_file->setFilter("*." + extension);
1155     QString edit = item->data(EditableRole).toString();
1156     if (edit.isEmpty() || !edit.endsWith("customprofiles.xml")) {
1157         m_view.buttonDelete->setEnabled(false);
1158         m_view.buttonEdit->setEnabled(false);
1159     } else {
1160         m_view.buttonDelete->setEnabled(true);
1161         m_view.buttonEdit->setEnabled(true);
1162     }
1163
1164     m_view.buttonRender->setEnabled(m_view.size_list->currentItem()->toolTip().isEmpty());
1165     m_view.buttonGenerateScript->setEnabled(m_view.size_list->currentItem()->toolTip().isEmpty());
1166 }
1167
1168 void RenderWidget::reloadProfiles()
1169 {
1170     parseProfiles();
1171 }
1172
1173 void RenderWidget::parseProfiles(QString meta, QString group, QString profile)
1174 {
1175     m_view.size_list->blockSignals(true);
1176     m_view.format_list->blockSignals(true);
1177     m_view.size_list->clear();
1178     m_view.format_list->clear();
1179     m_view.destination_list->clear();
1180     qDeleteAll(m_renderItems);
1181     qDeleteAll(m_renderCategory);
1182     m_renderItems.clear();
1183     m_renderCategory.clear();
1184     m_view.destination_list->addItem(KIcon("video-x-generic"), i18n("File rendering"));
1185     m_view.destination_list->addItem(KIcon("favorites"), i18n("Favorites"), "favorites");
1186     m_view.destination_list->addItem(KIcon("media-optical"), i18n("DVD"), "dvd");
1187     m_view.destination_list->addItem(KIcon("audio-x-generic"), i18n("Audio only"), "audioonly");
1188     m_view.destination_list->addItem(KIcon("applications-internet"), i18n("Web sites"), "websites");
1189     m_view.destination_list->addItem(KIcon("applications-multimedia"), i18n("Media players"), "mediaplayers");
1190     m_view.destination_list->addItem(KIcon("drive-harddisk"), i18n("Lossless / HQ"), "lossless");
1191     m_view.destination_list->addItem(KIcon("pda"), i18n("Mobile devices"), "mobile");
1192
1193     QString exportFile = KStandardDirs::locate("appdata", "export/profiles.xml");
1194     parseFile(exportFile, false);
1195
1196
1197     QString exportFolder = KStandardDirs::locateLocal("appdata", "export/");
1198     QDir directory = QDir(exportFolder);
1199     QStringList filter;
1200     filter << "*.xml";
1201     QStringList fileList = directory.entryList(filter, QDir::Files);
1202     // We should parse customprofiles.xml in last position, so that user profiles
1203     // can also override profiles installed by KNewStuff
1204     fileList.removeAll("customprofiles.xml");
1205     foreach(const QString &filename, fileList)
1206     parseFile(exportFolder + filename, true);
1207     if (QFile::exists(exportFolder + "customprofiles.xml")) parseFile(exportFolder + "customprofiles.xml", true);
1208
1209     if (!meta.isEmpty()) {
1210         m_view.destination_list->blockSignals(true);
1211         m_view.destination_list->setCurrentIndex(m_view.destination_list->findData(meta));
1212         m_view.destination_list->blockSignals(false);
1213     }
1214     refreshCategory();
1215     QList<QListWidgetItem *> child;
1216     if (!group.isEmpty()) child = m_view.format_list->findItems(group, Qt::MatchExactly);
1217     if (!child.isEmpty()) {
1218         for (int i = 0; i < child.count(); i++) {
1219             if (child.at(i)->data(MetaGroupRole).toString() == meta) {
1220                 m_view.format_list->setCurrentItem(child.at(i));
1221                 break;
1222             }
1223         }
1224     }
1225     child.clear();
1226     m_view.size_list->blockSignals(false);
1227     m_view.format_list->blockSignals(false);
1228     if (!profile.isEmpty()) child = m_view.size_list->findItems(profile, Qt::MatchExactly);
1229     if (!child.isEmpty()) m_view.size_list->setCurrentItem(child.at(0));
1230 }
1231
1232 void RenderWidget::parseFile(QString exportFile, bool editable)
1233 {
1234     kDebug() << "// Parsing file: " << exportFile;
1235     kDebug() << "------------------------------";
1236     QDomDocument doc;
1237     QFile file(exportFile);
1238     doc.setContent(&file, false);
1239     file.close();
1240     QDomElement documentElement;
1241     QDomElement profileElement;
1242     QString extension;
1243     QDomNodeList groups = doc.elementsByTagName("group");
1244     QListWidgetItem *item = NULL;
1245     const QStringList acodecsList = KdenliveSettings::audiocodecs();
1246     bool replaceVorbisCodec = false;
1247     if (acodecsList.contains("libvorbis")) replaceVorbisCodec = true;
1248     bool replaceLibfaacCodec = false;
1249     if (!acodecsList.contains("aac") && acodecsList.contains("libfaac")) replaceLibfaacCodec = true;
1250
1251
1252     if (editable || groups.count() == 0) {
1253         QDomElement profiles = doc.documentElement();
1254         if (editable && profiles.attribute("version", 0).toInt() < 1) {
1255             kDebug() << "// OLD profile version";
1256             // this is an old profile version, update it
1257             QDomDocument newdoc;
1258             QDomElement newprofiles = newdoc.createElement("profiles");
1259             newprofiles.setAttribute("version", 1);
1260             newdoc.appendChild(newprofiles);
1261             QDomNodeList profilelist = doc.elementsByTagName("profile");
1262             for (int i = 0; i < profilelist.count(); i++) {
1263                 QString category = i18n("Custom");
1264                 QString extension;
1265                 QDomNode parent = profilelist.at(i).parentNode();
1266                 if (!parent.isNull()) {
1267                     QDomElement parentNode = parent.toElement();
1268                     if (parentNode.hasAttribute("name")) category = parentNode.attribute("name");
1269                     extension = parentNode.attribute("extension");
1270                 }
1271                 profilelist.at(i).toElement().setAttribute("category", category);
1272                 if (!extension.isEmpty()) profilelist.at(i).toElement().setAttribute("extension", extension);
1273                 QDomNode n = profilelist.at(i).cloneNode();
1274                 newprofiles.appendChild(newdoc.importNode(n, true));
1275             }
1276             if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
1277                 KMessageBox::sorry(this, i18n("Unable to write to file %1", exportFile));
1278                 return;
1279             }
1280             QTextStream out(&file);
1281             out << newdoc.toString();
1282             file.close();
1283             parseFile(exportFile, editable);
1284             return;
1285         }
1286
1287         QDomNode node = doc.elementsByTagName("profile").at(0);
1288         if (node.isNull()) {
1289             kDebug() << "// Export file: " << exportFile << " IS BROKEN";
1290             return;
1291         }
1292         int count = 1;
1293         while (!node.isNull()) {
1294             QDomElement profile = node.toElement();
1295             QString profileName = profile.attribute("name");
1296             QString standard = profile.attribute("standard");
1297             QString params = profile.attribute("args");
1298
1299             if (replaceVorbisCodec && params.contains("acodec=vorbis")) {
1300                 // replace vorbis with libvorbis
1301                 params = params.replace("vorbis", "libvorbis");
1302             }
1303             if (replaceLibfaacCodec && params.contains("acodec=aac")) {
1304                 // replace libfaac with aac
1305                 params = params.replace("aac", "libfaac");
1306             }
1307
1308             QString category = profile.attribute("category", i18n("Custom"));
1309             QString dest = profile.attribute("destinationid");
1310             QString prof_extension = profile.attribute("extension");
1311             if (!prof_extension.isEmpty()) extension = prof_extension;
1312             bool exists = false;
1313             for (int j = 0; j < m_renderCategory.count(); j++) {
1314                 if (m_renderCategory.at(j)->text() == category && m_renderCategory.at(j)->data(MetaGroupRole) == dest) {
1315                     exists = true;
1316                     break;
1317                 }
1318             }
1319
1320             if (!exists) {
1321                 QListWidgetItem *itemcat = new QListWidgetItem(category);
1322                 itemcat->setData(MetaGroupRole, dest);
1323                 m_renderCategory.append(itemcat);
1324             }
1325
1326             // Check if item with same name already exists and replace it,
1327             // allowing to override default profiles
1328
1329
1330             for (int j = 0; j < m_renderItems.count(); j++) {
1331                 if (m_renderItems.at(j)->text() == profileName && m_renderItems.at(j)->data(MetaGroupRole) == dest) {
1332                     QListWidgetItem *duplicate = m_renderItems.takeAt(j);
1333                     delete duplicate;
1334                     j--;
1335                 }
1336             }
1337
1338             item = new QListWidgetItem(profileName); // , m_view.size_list
1339             //kDebug() << "// ADDINg item with name: " << profileName << ", GRP" << category << ", DEST:" << dest ;
1340             item->setData(GroupRole, category);
1341             item->setData(MetaGroupRole, dest);
1342             item->setData(ExtensionRole, extension);
1343             item->setData(RenderRole, "avformat");
1344             item->setData(StandardRole, standard);
1345             item->setData(ParamsRole, params);
1346             if (profile.hasAttribute("url")) item->setData(ExtraRole, profile.attribute("url"));
1347             if (editable) {
1348                 item->setData(EditableRole, exportFile);
1349                 if (exportFile.endsWith("customprofiles.xml")) item->setIcon(KIcon("emblem-favorite"));
1350                 else item->setIcon(KIcon("applications-internet"));
1351             }
1352             m_renderItems.append(item);
1353             node = doc.elementsByTagName("profile").at(count);
1354             count++;
1355         }
1356         return;
1357     }
1358
1359     int i = 0;
1360     QString groupName;
1361     QString profileName;
1362
1363     QString prof_extension;
1364     QString renderer;
1365     QString params;
1366     QString standard;
1367     KIcon icon;
1368
1369     while (!groups.item(i).isNull()) {
1370         documentElement = groups.item(i).toElement();
1371         QDomNode gname = documentElement.elementsByTagName("groupname").at(0);
1372         QString metagroupName;
1373         QString metagroupId;
1374         if (!gname.isNull()) {
1375             metagroupName = gname.firstChild().nodeValue();
1376             metagroupId = gname.toElement().attribute("id");
1377
1378             if (!metagroupName.isEmpty() && m_view.destination_list->findData(metagroupId) == -1) {
1379                 if (metagroupId == "dvd") icon = KIcon("media-optical");
1380                 else if (metagroupId == "audioonly") icon = KIcon("audio-x-generic");
1381                 else if (metagroupId == "websites") icon = KIcon("applications-internet");
1382                 else if (metagroupId == "mediaplayers") icon = KIcon("applications-multimedia");
1383                 else if (metagroupId == "lossless") icon = KIcon("drive-harddisk");
1384                 else if (metagroupId == "mobile") icon = KIcon("pda");
1385                 m_view.destination_list->addItem(icon, i18n(metagroupName.toUtf8().data()), metagroupId);
1386             }
1387         }
1388         groupName = documentElement.attribute("name", i18n("Custom"));
1389         extension = documentElement.attribute("extension", QString());
1390         renderer = documentElement.attribute("renderer", QString());
1391         bool exists = false;
1392         for (int j = 0; j < m_renderCategory.count(); j++) {
1393             if (m_renderCategory.at(j)->text() == groupName && m_renderCategory.at(j)->data(MetaGroupRole) == metagroupId) {
1394                 exists = true;
1395                 break;
1396             }
1397         }
1398         if (!exists) {
1399             QListWidgetItem *itemcat = new QListWidgetItem(groupName); //, m_view.format_list);
1400             itemcat->setData(MetaGroupRole, metagroupId);
1401             m_renderCategory.append(itemcat);
1402         }
1403
1404         QDomNode n = groups.item(i).firstChild();
1405         while (!n.isNull()) {
1406             if (n.toElement().tagName() != "profile") {
1407                 n = n.nextSibling();
1408                 continue;
1409             }
1410             profileElement = n.toElement();
1411             profileName = profileElement.attribute("name");
1412             standard = profileElement.attribute("standard");
1413             params = profileElement.attribute("args");
1414
1415             if (replaceVorbisCodec && params.contains("acodec=vorbis")) {
1416                 // replace vorbis with libvorbis
1417                 params = params.replace("vorbis", "libvorbis");
1418             }
1419             if (replaceLibfaacCodec && params.contains("acodec=aac")) {
1420                 // replace libfaac with aac
1421                 params = params.replace("aac", "libfaac");
1422             }
1423
1424             prof_extension = profileElement.attribute("extension");
1425             if (!prof_extension.isEmpty()) extension = prof_extension;
1426             item = new QListWidgetItem(profileName); //, m_view.size_list);
1427             item->setData(GroupRole, groupName);
1428             item->setData(MetaGroupRole, metagroupId);
1429             item->setData(ExtensionRole, extension);
1430             item->setData(RenderRole, renderer);
1431             item->setData(StandardRole, standard);
1432             item->setData(ParamsRole, params);
1433             if (profileElement.hasAttribute("url")) item->setData(ExtraRole, profileElement.attribute("url"));
1434             if (editable) item->setData(EditableRole, exportFile);
1435             m_renderItems.append(item);
1436             n = n.nextSibling();
1437         }
1438
1439         i++;
1440     }
1441 }
1442
1443 void RenderWidget::setRenderJob(const QString &dest, int progress)
1444 {
1445     QTreeWidgetItem *item;
1446     QList<QTreeWidgetItem *> existing = m_view.running_jobs->findItems(dest, Qt::MatchExactly, 1);
1447     if (!existing.isEmpty()) item = existing.at(0);
1448     else {
1449         item = new QTreeWidgetItem(m_view.running_jobs, QStringList() << QString() << dest << QString());
1450         item->setSizeHint(1, QSize(m_view.running_jobs->columnWidth(1), fontMetrics().height() * 2));
1451         if (progress == 0) {
1452             item->setData(1, Qt::UserRole + 2, WAITINGJOB);
1453             item->setIcon(0, KIcon("media-playback-pause"));
1454             item->setData(1, Qt::UserRole, i18n("Waiting..."));
1455         }
1456     }
1457     item->setData(2, Qt::UserRole, progress);
1458     item->setData(1, Qt::UserRole + 2, RUNNINGJOB);
1459     if (progress == 0) {
1460         item->setIcon(0, KIcon("system-run"));
1461         item->setSizeHint(1, QSize(m_view.running_jobs->columnWidth(1), fontMetrics().height() * 2));
1462         item->setData(1, Qt::UserRole + 1, QTime::currentTime());
1463         slotCheckJob();
1464     } else {
1465         QTime startTime = item->data(1, Qt::UserRole + 1).toTime();
1466         int seconds = startTime.secsTo(QTime::currentTime());;
1467         const QString t = i18n("Estimated time %1", QTime().addSecs(seconds * (100 - progress) / progress).toString("hh:mm:ss"));
1468         item->setData(1, Qt::UserRole, t);
1469     }
1470 }
1471
1472 void RenderWidget::setRenderStatus(const QString &dest, int status, const QString &error)
1473 {
1474     QTreeWidgetItem *item;
1475     QList<QTreeWidgetItem *> existing = m_view.running_jobs->findItems(dest, Qt::MatchExactly, 1);
1476     if (!existing.isEmpty()) item = existing.at(0);
1477     else {
1478         item = new QTreeWidgetItem(m_view.running_jobs, QStringList() << QString() << dest << QString());
1479         item->setSizeHint(1, QSize(m_view.running_jobs->columnWidth(1), fontMetrics().height() * 2));
1480     }
1481     item->setData(1, Qt::UserRole + 2, FINISHEDJOB);
1482     if (status == -1) {
1483         // Job finished successfully
1484         item->setIcon(0, KIcon("dialog-ok"));
1485         item->setData(2, Qt::UserRole, 100);
1486         QTime startTime = item->data(1, Qt::UserRole + 1).toTime();
1487         int seconds = startTime.secsTo(QTime::currentTime());
1488         const QTime tm = QTime().addSecs(seconds);
1489         const QString t = i18n("Rendering finished in %1", tm.toString("hh:mm:ss"));
1490         item->setData(1, Qt::UserRole, t);
1491         QString itemGroup = item->data(0, Qt::UserRole).toString();
1492         if (itemGroup == "dvd") {
1493             emit openDvdWizard(item->text(1), item->data(0, Qt::UserRole + 1).toString());
1494         } else if (itemGroup == "websites") {
1495             QString url = item->data(0, Qt::UserRole + 1).toString();
1496             if (!url.isEmpty()) new KRun(url, this);
1497         }
1498     } else if (status == -2) {
1499         // Rendering crashed
1500         item->setData(1, Qt::UserRole, i18n("Rendering crashed"));
1501         item->setIcon(0, KIcon("dialog-close"));
1502         item->setData(2, Qt::UserRole, 100);
1503         m_view.error_log->append(i18n("<strong>Rendering of %1 crashed</strong><br />", dest));
1504         m_view.error_log->append(error);
1505         m_view.error_log->append("<hr />");
1506         m_view.error_box->setVisible(true);
1507     } else if (status == -3) {
1508         // User aborted job
1509         item->setData(1, Qt::UserRole, i18n("Rendering aborted"));
1510         item->setIcon(0, KIcon("dialog-cancel"));
1511         item->setData(2, Qt::UserRole, 100);
1512     }
1513     slotCheckJob();
1514     checkRenderStatus();
1515 }
1516
1517 void RenderWidget::slotAbortCurrentJob()
1518 {
1519     QTreeWidgetItem *current = m_view.running_jobs->currentItem();
1520     if (current) {
1521         if (current->data(1, Qt::UserRole + 2).toInt() == RUNNINGJOB)
1522             emit abortProcess(current->text(1));
1523         else {
1524             delete current;
1525             slotCheckJob();
1526             checkRenderStatus();
1527         }
1528     }
1529 }
1530
1531 void RenderWidget::slotStartCurrentJob()
1532 {
1533     QTreeWidgetItem *current = m_view.running_jobs->currentItem();
1534     if (current && current->data(1, Qt::UserRole + 2).toInt() == WAITINGJOB)
1535         startRendering(current);
1536     m_view.start_job->setEnabled(false);
1537 }
1538
1539 void RenderWidget::slotCheckJob()
1540 {
1541     bool activate = false;
1542     QTreeWidgetItem *current = m_view.running_jobs->currentItem();
1543     if (current) {
1544         if (current->data(1, Qt::UserRole + 2).toInt() == RUNNINGJOB) {
1545             m_view.abort_job->setText(i18n("Abort Job"));
1546             m_view.start_job->setEnabled(false);
1547         } else {
1548             m_view.abort_job->setText(i18n("Remove Job"));
1549             m_view.start_job->setEnabled(current->data(1, Qt::UserRole + 2).toInt() == WAITINGJOB);
1550         }
1551         activate = true;
1552     }
1553     m_view.abort_job->setEnabled(activate);
1554 }
1555
1556 void RenderWidget::slotCLeanUpJobs()
1557 {
1558     int ix = 0;
1559     QTreeWidgetItem *current = m_view.running_jobs->topLevelItem(ix);
1560     while (current) {
1561         if (current->data(1, Qt::UserRole + 2).toInt() == FINISHEDJOB)
1562             delete current;
1563         else ix++;
1564         current = m_view.running_jobs->topLevelItem(ix);
1565     }
1566     slotCheckJob();
1567 }
1568
1569 void RenderWidget::parseScriptFiles()
1570 {
1571     QStringList scriptsFilter;
1572     scriptsFilter << "*.sh";
1573     m_view.scripts_list->clear();
1574
1575     QTreeWidgetItem *item;
1576     // List the project scripts
1577     QStringList scriptFiles = QDir(m_projectFolder + "scripts").entryList(scriptsFilter, QDir::Files);
1578     for (int i = 0; i < scriptFiles.size(); ++i) {
1579         KUrl scriptpath(m_projectFolder + "scripts/" + scriptFiles.at(i));
1580         QString target;
1581         QString renderer;
1582         QString melt;
1583         QFile file(scriptpath.path());
1584         if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
1585             while (!file.atEnd()) {
1586                 QByteArray line = file.readLine();
1587                 if (line.startsWith("TARGET=")) {
1588                     target = QString(line).section("TARGET=", 1).simplified();
1589                     target.remove(QChar('"'));
1590                 } else if (line.startsWith("RENDERER=")) {
1591                     renderer = QString(line).section("RENDERER=", 1).simplified();
1592                     renderer.remove(QChar('"'));
1593                 } else if (line.startsWith("MELT=")) {
1594                     melt = QString(line).section("MELT=", 1).simplified();
1595                     melt.remove(QChar('"'));
1596                 }
1597             }
1598             file.close();
1599         }
1600         if (target.isEmpty()) continue;
1601         item = new QTreeWidgetItem(m_view.scripts_list, QStringList() << QString() << scriptpath.fileName());
1602         if (!renderer.isEmpty() && renderer.contains('/') && !QFile::exists(renderer)) {
1603             item->setIcon(0, KIcon("dialog-cancel"));
1604             item->setToolTip(1, i18n("Script contains wrong command: %1", renderer));
1605             item->setData(0, Qt::UserRole, '1');
1606         } else if (!melt.isEmpty() && melt.contains('/') && !QFile::exists(melt)) {
1607             item->setIcon(0, KIcon("dialog-cancel"));
1608             item->setToolTip(1, i18n("Script contains wrong command: %1", melt));
1609             item->setData(0, Qt::UserRole, '1');
1610         } else item->setIcon(0, KIcon("application-x-executable-script"));
1611         item->setSizeHint(0, QSize(m_view.scripts_list->columnWidth(0), fontMetrics().height() * 2));
1612         item->setData(1, Qt::UserRole, target.simplified());
1613         item->setData(1, Qt::UserRole + 1, scriptpath.path());
1614     }
1615     bool activate = false;
1616     QTreeWidgetItem *script = m_view.scripts_list->topLevelItem(0);
1617     if (script) {
1618         script->setSelected(true);
1619         m_view.scripts_list->setCurrentItem(script);
1620         activate = true;
1621     }
1622 //    m_view.start_script->setEnabled(activate);
1623 //    m_view.delete_script->setEnabled(activate);
1624 }
1625
1626 void RenderWidget::slotCheckScript()
1627 {
1628     QTreeWidgetItem *item = m_view.scripts_list->currentItem();
1629     if (item == NULL) return;
1630     m_view.start_script->setEnabled(item->data(0, Qt::UserRole).toString().isEmpty());
1631     m_view.delete_script->setEnabled(true);
1632 }
1633
1634 void RenderWidget::slotStartScript()
1635 {
1636     QTreeWidgetItem *item = m_view.scripts_list->currentItem();
1637     if (item) {
1638         QString destination = item->data(1, Qt::UserRole).toString();
1639         QString path = item->data(1, Qt::UserRole + 1).toString();
1640         // Insert new job in queue
1641         QTreeWidgetItem *renderItem;
1642         QList<QTreeWidgetItem *> existing = m_view.running_jobs->findItems(destination, Qt::MatchExactly, 1);
1643         kDebug() << "------  START SCRIPT";
1644         if (!existing.isEmpty()) {
1645             renderItem = existing.at(0);
1646             if (renderItem->data(1, Qt::UserRole + 2).toInt() == RUNNINGJOB) {
1647                 KMessageBox::information(this, i18n("There is already a job writing file:<br /><b>%1</b><br />Abort the job if you want to overwrite it...", destination), i18n("Already running"));
1648                 return;
1649             }
1650         } else renderItem = new QTreeWidgetItem(m_view.running_jobs, QStringList() << QString() << destination << QString());
1651         kDebug() << "------  START SCRIPT 2";
1652         renderItem->setData(2, Qt::UserRole, 0);
1653         renderItem->setData(1, Qt::UserRole + 2, WAITINGJOB);
1654         renderItem->setIcon(0, KIcon("media-playback-pause"));
1655         renderItem->setData(1, Qt::UserRole, i18n("Waiting..."));
1656         renderItem->setSizeHint(1, QSize(m_view.running_jobs->columnWidth(1), fontMetrics().height() * 2));
1657         renderItem->setData(1, Qt::UserRole + 1, QTime::currentTime());
1658         renderItem->setData(1, Qt::UserRole + 3, path);
1659         renderItem->setData(1, Qt::UserRole + 4, '1');
1660         checkRenderStatus();
1661         m_view.tabWidget->setCurrentIndex(1);
1662     }
1663 }
1664
1665 void RenderWidget::slotDeleteScript()
1666 {
1667     QTreeWidgetItem *item = m_view.scripts_list->currentItem();
1668     if (item) {
1669         QString path = item->data(1, Qt::UserRole + 1).toString();
1670         KIO::NetAccess::del(path + ".mlt", this);
1671         KIO::NetAccess::del(path, this);
1672         parseScriptFiles();
1673     }
1674 }
1675
1676 void RenderWidget::slotGenerateScript()
1677 {
1678     slotPrepareExport(true);
1679 }
1680
1681 void RenderWidget::slotHideLog()
1682 {
1683     m_view.error_box->setVisible(false);
1684 }
1685
1686 void RenderWidget::setRenderProfile(const QString &dest, const QString &group, const QString &name, const QString &url)
1687 {
1688     m_view.destination_list->blockSignals(true);
1689     m_view.format_list->blockSignals(true);
1690
1691     if (!url.isEmpty()) m_view.out_file->setUrl(KUrl(url));
1692
1693     // set destination
1694     for (int i = 0; i < m_view.destination_list->count(); i++) {
1695         if (m_view.destination_list->itemData(i, Qt::UserRole) == dest) {
1696             m_view.destination_list->setCurrentIndex(i);
1697             break;
1698         }
1699     }
1700     refreshCategory();
1701
1702     // set category
1703     if (!group.isEmpty()) {
1704         QList<QListWidgetItem *> childs = m_view.format_list->findItems(group, Qt::MatchExactly);
1705         if (!childs.isEmpty()) {
1706             m_view.format_list->setCurrentItem(childs.at(0));
1707             m_view.format_list->scrollToItem(childs.at(0));
1708         }
1709         refreshView();
1710     }
1711
1712     // set profile
1713     QList<QListWidgetItem *> childs = m_view.size_list->findItems(name, Qt::MatchExactly);
1714     if (!childs.isEmpty()) {
1715         m_view.size_list->setCurrentItem(childs.at(0));
1716         m_view.size_list->scrollToItem(childs.at(0));
1717     }
1718     //refreshView();
1719     m_view.destination_list->blockSignals(false);
1720     m_view.format_list->blockSignals(false);
1721
1722 }
1723
1724 bool RenderWidget::startWaitingRenderJobs()
1725 {
1726     m_blockProcessing = true;
1727     QString autoscriptFile = getFreeScriptName("auto");
1728     QFile file(autoscriptFile);
1729     if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
1730         kWarning() << "//////  ERROR writing to file: " << autoscriptFile;
1731         KMessageBox::error(0, i18n("Cannot write to file %1", autoscriptFile));
1732         return false;
1733     }
1734
1735     QTextStream outStream(&file);
1736     outStream << "#! /bin/sh" << "\n" << "\n";
1737     QTreeWidgetItem *item = m_view.running_jobs->topLevelItem(0);
1738     while (item) {
1739         if (item->data(1, Qt::UserRole + 2).toInt() == WAITINGJOB) {
1740             if (item->data(1, Qt::UserRole + 4).isNull()) {
1741                 // Add render process for item
1742                 const QString params = item->data(1, Qt::UserRole + 3).toStringList().join(" ");
1743                 outStream << m_renderer << " " << params << "\n";
1744             } else {
1745                 // Script item
1746                 outStream << item->data(1, Qt::UserRole + 3).toString() << "\n";
1747             }
1748         }
1749         item = m_view.running_jobs->itemBelow(item);
1750     }
1751     // erase itself when rendering is finished
1752     outStream << "rm " << autoscriptFile << "\n" << "\n";
1753     if (file.error() != QFile::NoError) {
1754         KMessageBox::error(0, i18n("Cannot write to file %1", autoscriptFile));
1755         file.close();
1756         m_blockProcessing = false;
1757         return false;
1758     }
1759     file.close();
1760     QFile::setPermissions(autoscriptFile, file.permissions() | QFile::ExeUser);
1761     QProcess::startDetached(autoscriptFile, QStringList());
1762     return true;
1763 }
1764
1765 QString RenderWidget::getFreeScriptName(const QString &prefix)
1766 {
1767     int ix = 0;
1768     QString scriptsFolder = m_projectFolder + "scripts/";
1769     KStandardDirs::makeDir(scriptsFolder);
1770     QString path;
1771     while (path.isEmpty() || QFile::exists(path)) {
1772         ix++;
1773         path = scriptsFolder + prefix + i18n("script") + QString::number(ix).rightJustified(3, '0', false) + ".sh";
1774     }
1775     return path;
1776 }
1777
1778 void RenderWidget::slotPlayRendering(QTreeWidgetItem *item, int)
1779 {
1780     if (KdenliveSettings::defaultplayerapp().isEmpty() || item->data(1, Qt::UserRole + 2).toInt() != FINISHEDJOB) return;
1781     const QByteArray startId = KStartupInfo::createNewStartupId();
1782     const QString command = KdenliveSettings::defaultplayerapp() + ' ' + item->text(1);
1783     KRun::runCommand(command, KdenliveSettings::defaultplayerapp(), KdenliveSettings::defaultplayerapp(), this, startId);
1784 }
1785
1786 void RenderWidget::missingClips(bool hasMissing)
1787 {
1788     if (hasMissing) {
1789         m_view.errorLabel->setText(i18n("Check missing clips"));
1790         m_view.errorLabel->setHidden(false);
1791     } else m_view.errorLabel->setHidden(true);
1792 }
1793
1794 void RenderWidget::slotEnableAudio(bool enable)
1795 {
1796     m_autoAudio = enable;
1797     if (m_view.export_audio->checkState() == Qt::PartiallyChecked) m_view.export_audio->setText(m_autoAudio ? i18n("Export audio (on)") : i18n("Export audio (off)"));
1798 }
1799
1800 void RenderWidget::slotUpdateRescaleWidth(int val)
1801 {
1802     KdenliveSettings::setDefaultrescalewidth(val);
1803     if (!m_view.rescale_keep->isChecked()) return;
1804     m_view.rescale_height->blockSignals(true);
1805     m_view.rescale_height->setValue(val * m_profile.height / m_profile.width  + 0.5);
1806     KdenliveSettings::setDefaultrescaleheight(m_view.rescale_height->value());
1807     m_view.rescale_height->blockSignals(false);
1808 }
1809
1810 void RenderWidget::slotUpdateRescaleHeight(int val)
1811 {
1812     KdenliveSettings::setDefaultrescaleheight(val);
1813     if (!m_view.rescale_keep->isChecked()) return;
1814     m_view.rescale_width->blockSignals(true);
1815     m_view.rescale_width->setValue(val * m_profile.width / m_profile.height + 0.5);
1816     KdenliveSettings::setDefaultrescaleheight(m_view.rescale_width->value());
1817     m_view.rescale_width->blockSignals(false);
1818 }
1819
1820 void RenderWidget::slotSwitchAspectRatio()
1821 {
1822     KdenliveSettings::setRescalekeepratio(m_view.rescale_keep->isChecked());
1823     if (m_view.rescale_keep->isChecked()) slotUpdateRescaleWidth(m_view.rescale_width->value());
1824 }
1825
1826 void RenderWidget::slotUpdateAudioLabel(int ix)
1827 {
1828     if (ix == Qt::PartiallyChecked)
1829         m_view.export_audio->setText(m_autoAudio ? i18n("Export audio (on)") : i18n("Export audio (off)"));
1830     else
1831         m_view.export_audio->setText(i18n("Audio export"));
1832 }