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