]> git.sesse.net Git - kdenlive/blob - src/renderwidget.cpp
Sequential rendering (one job after another)
[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
25 #include <KStandardDirs>
26 #include <KDebug>
27 #include <KMessageBox>
28 #include <KComboBox>
29 #include <KRun>
30 #include <KIO/NetAccess>
31 // #include <knewstuff2/engine.h>
32
33 #include <QDomDocument>
34 #include <QItemDelegate>
35 #include <QTreeWidgetItem>
36 #include <QListWidgetItem>
37 #include <QHeaderView>
38 #include <QMenu>
39 #include <QProcess>
40 #include <QInputDialog>
41
42 const int GroupRole = Qt::UserRole;
43 const int ExtensionRole = GroupRole + 1;
44 const int StandardRole = GroupRole + 2;
45 const int RenderRole = GroupRole + 3;
46 const int ParamsRole = GroupRole + 4;
47 const int EditableRole = GroupRole + 5;
48 const int MetaGroupRole = GroupRole + 6;
49 const int ExtraRole = GroupRole + 7;
50
51 // Running job status
52 const int WAITINGJOB = 0;
53 const int RUNNINGJOB = 1;
54 const int FINISHEDJOB = 2;
55
56
57 RenderWidget::RenderWidget(const QString &projectfolder, QWidget * parent) :
58         QDialog(parent),
59         m_projectFolder(projectfolder)
60 {
61     m_view.setupUi(this);
62     setWindowTitle(i18n("Rendering"));
63     m_view.buttonDelete->setIcon(KIcon("trash-empty"));
64     m_view.buttonDelete->setToolTip(i18n("Delete profile"));
65     m_view.buttonDelete->setEnabled(false);
66
67     m_view.buttonEdit->setIcon(KIcon("document-properties"));
68     m_view.buttonEdit->setToolTip(i18n("Edit profile"));
69     m_view.buttonEdit->setEnabled(false);
70
71     m_view.buttonSave->setIcon(KIcon("document-new"));
72     m_view.buttonSave->setToolTip(i18n("Create new profile"));
73
74     m_view.buttonInfo->setIcon(KIcon("help-about"));
75     m_view.hide_log->setIcon(KIcon("go-down"));
76
77     if (KdenliveSettings::showrenderparams()) {
78         m_view.buttonInfo->setDown(true);
79     } else m_view.advanced_params->hide();
80
81     m_view.rescale_size->setInputMask("0099\\x0099");
82     m_view.rescale_size->setText("320x240");
83
84
85     QMenu *renderMenu = new QMenu(i18n("Start Rendering"), this);
86     QAction *renderAction = renderMenu->addAction(KIcon("video-x-generic"), i18n("Render to File"));
87     connect(renderAction, SIGNAL(triggered()), this, SLOT(slotExport()));
88     QAction *scriptAction = renderMenu->addAction(KIcon("application-x-shellscript"), i18n("Generate Script"));
89     connect(scriptAction, SIGNAL(triggered()), this, SLOT(slotGenerateScript()));
90
91     m_view.buttonStart->setMenu(renderMenu);
92     m_view.buttonStart->setPopupMode(QToolButton::MenuButtonPopup);
93     m_view.buttonStart->setDefaultAction(renderAction);
94     m_view.buttonStart->setToolButtonStyle(Qt::ToolButtonTextOnly);
95     m_view.abort_job->setEnabled(false);
96     m_view.start_script->setEnabled(false);
97     m_view.delete_script->setEnabled(false);
98
99     m_view.format_list->setAlternatingRowColors(true);
100     m_view.size_list->setAlternatingRowColors(true);
101
102     parseProfiles();
103     parseScriptFiles();
104
105     connect(m_view.start_script, SIGNAL(clicked()), this, SLOT(slotStartScript()));
106     connect(m_view.delete_script, SIGNAL(clicked()), this, SLOT(slotDeleteScript()));
107     connect(m_view.scripts_list, SIGNAL(itemSelectionChanged()), this, SLOT(slotCheckScript()));
108     connect(m_view.running_jobs, SIGNAL(itemSelectionChanged()), this, SLOT(slotCheckJob()));
109
110     connect(m_view.buttonInfo, SIGNAL(clicked()), this, SLOT(showInfoPanel()));
111
112     connect(m_view.buttonSave, SIGNAL(clicked()), this, SLOT(slotSaveProfile()));
113     connect(m_view.buttonEdit, SIGNAL(clicked()), this, SLOT(slotEditProfile()));
114     connect(m_view.buttonDelete, SIGNAL(clicked()), this, SLOT(slotDeleteProfile()));
115     connect(m_view.abort_job, SIGNAL(clicked()), this, SLOT(slotAbortCurrentJob()));
116     connect(m_view.clean_up, SIGNAL(clicked()), this, SLOT(slotCLeanUpJobs()));
117     connect(m_view.hide_log, SIGNAL(clicked()), this, SLOT(slotHideLog()));
118
119     connect(m_view.buttonClose, SIGNAL(clicked()), this, SLOT(hide()));
120     connect(m_view.buttonClose2, SIGNAL(clicked()), this, SLOT(hide()));
121     connect(m_view.buttonClose3, SIGNAL(clicked()), this, SLOT(hide()));
122     connect(m_view.rescale, SIGNAL(toggled(bool)), m_view.rescale_size, SLOT(setEnabled(bool)));
123     connect(m_view.destination_list, SIGNAL(activated(int)), this, SLOT(refreshView()));
124     connect(m_view.out_file, SIGNAL(textChanged(const QString &)), this, SLOT(slotUpdateButtons()));
125     connect(m_view.out_file, SIGNAL(urlSelected(const KUrl &)), this, SLOT(slotUpdateButtons(const KUrl &)));
126     connect(m_view.format_list, SIGNAL(currentRowChanged(int)), this, SLOT(refreshView()));
127     connect(m_view.size_list, SIGNAL(currentRowChanged(int)), this, SLOT(refreshParams()));
128
129     connect(m_view.size_list, SIGNAL(itemDoubleClicked(QListWidgetItem *)), this, SLOT(slotEditItem(QListWidgetItem *)));
130
131     connect(m_view.render_guide, SIGNAL(clicked(bool)), this, SLOT(slotUpdateGuideBox()));
132     connect(m_view.render_zone, SIGNAL(clicked(bool)), this, SLOT(slotUpdateGuideBox()));
133     connect(m_view.render_full, SIGNAL(clicked(bool)), this, SLOT(slotUpdateGuideBox()));
134
135     connect(m_view.guide_end, SIGNAL(activated(int)), this, SLOT(slotCheckStartGuidePosition()));
136     connect(m_view.guide_start, SIGNAL(activated(int)), this, SLOT(slotCheckEndGuidePosition()));
137
138     connect(m_view.format_selection, SIGNAL(activated(int)), this, SLOT(refreshView()));
139
140     m_view.buttonStart->setEnabled(false);
141     m_view.rescale_size->setEnabled(false);
142     m_view.guides_box->setVisible(false);
143     m_view.open_dvd->setVisible(false);
144     m_view.open_browser->setVisible(false);
145     m_view.error_box->setVisible(false);
146
147     m_view.splitter->setStretchFactor(1, 5);
148     m_view.splitter->setStretchFactor(0, 2);
149
150     m_view.out_file->setMode(KFile::File);
151
152     m_view.running_jobs->setHeaderLabels(QStringList() << QString() << i18n("File") << i18n("Progress"));
153     m_view.running_jobs->setItemDelegate(new RenderViewDelegate(this));
154
155     QHeaderView *header = m_view.running_jobs->header();
156     QFontMetrics fm = fontMetrics();
157     //header->resizeSection(0, fm.width("typical-name-for-a-torrent.torrent"));
158     header->setResizeMode(0, QHeaderView::Fixed);
159     header->resizeSection(0, 30);
160     header->setResizeMode(1, QHeaderView::Interactive);
161     header->resizeSection(1, fm.width("typical-name-for-a-file.torrent"));
162     header->setResizeMode(2, QHeaderView::Fixed);
163     header->resizeSection(1, width() * 2 / 3);
164     header->setResizeMode(2, QHeaderView::Interactive);
165     //header->setResizeMode(1, QHeaderView::Fixed);
166
167     m_view.scripts_list->setHeaderLabels(QStringList() << i18n("Script Files"));
168     m_view.scripts_list->setItemDelegate(new RenderScriptDelegate(this));
169
170
171     focusFirstVisibleItem();
172 }
173
174 void RenderWidget::slotEditItem(QListWidgetItem *item)
175 {
176     QString edit = item->data(EditableRole).toString();
177     if (edit.isEmpty() || !edit.endsWith("customprofiles.xml")) slotSaveProfile();
178     else slotEditProfile();
179 }
180
181 void RenderWidget::showInfoPanel()
182 {
183     if (m_view.advanced_params->isVisible()) {
184         m_view.advanced_params->setVisible(false);
185         m_view.buttonInfo->setDown(false);
186         KdenliveSettings::setShowrenderparams(false);
187     } else {
188         m_view.advanced_params->setVisible(true);
189         m_view.buttonInfo->setDown(true);
190         KdenliveSettings::setShowrenderparams(true);
191     }
192 }
193
194 void RenderWidget::setDocumentPath(const QString path)
195 {
196     m_projectFolder = path;
197     const QString fileName = m_view.out_file->url().fileName();
198     m_view.out_file->setUrl(KUrl(m_projectFolder + '/' + fileName));
199     parseScriptFiles();
200 }
201
202 void RenderWidget::slotUpdateGuideBox()
203 {
204     m_view.guides_box->setVisible(m_view.render_guide->isChecked());
205 }
206
207 void RenderWidget::slotCheckStartGuidePosition()
208 {
209     if (m_view.guide_start->currentIndex() > m_view.guide_end->currentIndex())
210         m_view.guide_start->setCurrentIndex(m_view.guide_end->currentIndex());
211 }
212
213 void RenderWidget::slotCheckEndGuidePosition()
214 {
215     if (m_view.guide_end->currentIndex() < m_view.guide_start->currentIndex())
216         m_view.guide_end->setCurrentIndex(m_view.guide_start->currentIndex());
217 }
218
219 void RenderWidget::setGuides(QDomElement guidesxml, double duration)
220 {
221     m_view.guide_start->clear();
222     m_view.guide_end->clear();
223     QDomNodeList nodes = guidesxml.elementsByTagName("guide");
224     if (nodes.count() > 0) {
225         m_view.guide_start->addItem(i18n("Render"), "0");
226         m_view.render_guide->setEnabled(true);
227     } else m_view.render_guide->setEnabled(false);
228     for (int i = 0; i < nodes.count(); i++) {
229         QDomElement e = nodes.item(i).toElement();
230         if (!e.isNull()) {
231             m_view.guide_start->addItem(e.attribute("comment"), e.attribute("time").toDouble());
232             m_view.guide_end->addItem(e.attribute("comment"), e.attribute("time").toDouble());
233         }
234     }
235     if (nodes.count() > 0)
236         m_view.guide_end->addItem(i18n("End"), QString::number(duration));
237 }
238
239 // Will be called when the user selects an output file via the file dialog.
240 // File extension will be added automatically.
241 void RenderWidget::slotUpdateButtons(KUrl url)
242 {
243     if (m_view.out_file->url().isEmpty()) m_view.buttonStart->setEnabled(false);
244     else m_view.buttonStart->setEnabled(true);
245     if (url != 0) {
246         QListWidgetItem *item = m_view.size_list->currentItem();
247         QString extension = item->data(ExtensionRole).toString();
248         url = filenameWithExtension(url, extension);
249         m_view.out_file->setUrl(url);
250     }
251 }
252
253 // Will be called when the user changes the output file path in the text line.
254 // File extension must NOT be added, would make editing impossible!
255 void RenderWidget::slotUpdateButtons()
256 {
257     if (m_view.out_file->url().isEmpty()) m_view.buttonStart->setEnabled(false);
258     else m_view.buttonStart->setEnabled(true);
259 }
260
261 void RenderWidget::slotSaveProfile()
262 {
263     //TODO: update to correctly use metagroups
264     Ui::SaveProfile_UI ui;
265     QDialog *d = new QDialog(this);
266     ui.setupUi(d);
267
268     for (int i = 0; i < m_view.destination_list->count(); i++)
269         ui.destination_list->addItem(m_view.destination_list->itemIcon(i), m_view.destination_list->itemText(i), m_view.destination_list->itemData(i, Qt::UserRole));
270
271     ui.destination_list->setCurrentIndex(m_view.destination_list->currentIndex());
272     QString dest = ui.destination_list->itemData(ui.destination_list->currentIndex(), Qt::UserRole).toString();
273
274     QString customGroup = m_view.format_list->currentItem()->text();
275     if (customGroup.isEmpty()) customGroup = i18n("Custom");
276     ui.group_name->setText(customGroup);
277
278     ui.parameters->setText(m_view.advanced_params->toPlainText());
279     ui.extension->setText(m_view.size_list->currentItem()->data(ExtensionRole).toString());
280     ui.profile_name->setFocus();
281     if (d->exec() == QDialog::Accepted && !ui.profile_name->text().simplified().isEmpty()) {
282         QString exportFile = KStandardDirs::locateLocal("appdata", "export/customprofiles.xml");
283         QDomDocument doc;
284         QFile file(exportFile);
285         doc.setContent(&file, false);
286         file.close();
287         QDomElement documentElement;
288         QDomElement profiles = doc.documentElement();
289         if (profiles.isNull() || profiles.tagName() != "profiles") {
290             doc.clear();
291             profiles = doc.createElement("profiles");
292             profiles.setAttribute("version", 1);
293             doc.appendChild(profiles);
294         }
295         int version = profiles.attribute("version", 0).toInt();
296         if (version < 1) {
297             kDebug() << "// OLD profile version";
298             doc.clear();
299             profiles = doc.createElement("profiles");
300             profiles.setAttribute("version", 1);
301             doc.appendChild(profiles);
302         }
303
304         QString newProfileName = ui.profile_name->text().simplified();
305         QString newGroupName = ui.group_name->text().simplified();
306         if (newGroupName.isEmpty()) newGroupName = i18n("Custom");
307         QString newMetaGroupId = ui.destination_list->itemData(ui.destination_list->currentIndex(), Qt::UserRole).toString();
308         QDomNodeList profilelist = doc.elementsByTagName("profile");
309         int i = 0;
310         while (!profilelist.item(i).isNull()) {
311             // make sure a profile with same name doesn't exist
312             documentElement = profilelist.item(i).toElement();
313             QString profileName = documentElement.attribute("name");
314             if (profileName == newProfileName) {
315                 // a profile with that same name already exists
316                 bool ok;
317                 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);
318                 if (!ok) return;
319                 if (profileName == newProfileName) {
320                     profiles.removeChild(profilelist.item(i));
321                     break;
322                 }
323             }
324             i++;
325         }
326
327         QDomElement profileElement = doc.createElement("profile");
328         profileElement.setAttribute("name", newProfileName);
329         profileElement.setAttribute("category", newGroupName);
330         profileElement.setAttribute("destinationid", newMetaGroupId);
331         profileElement.setAttribute("extension", ui.extension->text().simplified());
332         profileElement.setAttribute("args", ui.parameters->toPlainText().simplified());
333         profiles.appendChild(profileElement);
334
335         //QCString save = doc.toString().utf8();
336
337         if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
338             KMessageBox::sorry(this, i18n("Unable to write to file %1", exportFile));
339             delete d;
340             return;
341         }
342         QTextStream out(&file);
343         out << doc.toString();
344         if (file.error() != QFile::NoError) {
345             KMessageBox::error(this, i18n("Cannot write to file %1", exportFile));
346             file.close();
347             delete d;
348             return;
349         }
350         file.close();
351         parseProfiles(newMetaGroupId, newGroupName, newProfileName);
352     }
353     delete d;
354 }
355
356 void RenderWidget::slotEditProfile()
357 {
358     QListWidgetItem *item = m_view.size_list->currentItem();
359     if (!item) return;
360     QString currentGroup = m_view.format_list->currentItem()->text();
361
362     QString params = item->data(ParamsRole).toString();
363     QString extension = item->data(ExtensionRole).toString();
364     QString currentProfile = item->text();
365
366     Ui::SaveProfile_UI ui;
367     QDialog *d = new QDialog(this);
368     ui.setupUi(d);
369
370     for (int i = 0; i < m_view.destination_list->count(); i++)
371         ui.destination_list->addItem(m_view.destination_list->itemIcon(i), m_view.destination_list->itemText(i), m_view.destination_list->itemData(i, Qt::UserRole));
372
373     ui.destination_list->setCurrentIndex(m_view.destination_list->currentIndex());
374     QString dest = ui.destination_list->itemData(ui.destination_list->currentIndex(), Qt::UserRole).toString();
375
376     QString customGroup = m_view.format_list->currentItem()->text();
377     if (customGroup.isEmpty()) customGroup = i18n("Custom");
378     ui.group_name->setText(customGroup);
379
380     ui.profile_name->setText(currentProfile);
381     ui.extension->setText(extension);
382     ui.parameters->setText(params);
383     ui.profile_name->setFocus();
384     d->setWindowTitle(i18n("Edit Profile"));
385     if (d->exec() == QDialog::Accepted) {
386         slotDeleteProfile(false);
387         QString exportFile = KStandardDirs::locateLocal("appdata", "export/customprofiles.xml");
388         QDomDocument doc;
389         QFile file(exportFile);
390         doc.setContent(&file, false);
391         file.close();
392         QDomElement documentElement;
393         QDomElement profiles = doc.documentElement();
394
395         if (profiles.isNull() || profiles.tagName() != "profiles") {
396             doc.clear();
397             profiles = doc.createElement("profiles");
398             profiles.setAttribute("version", 1);
399             doc.appendChild(profiles);
400         }
401
402         int version = profiles.attribute("version", 0).toInt();
403         if (version < 1) {
404             kDebug() << "// OLD profile version";
405             doc.clear();
406             profiles = doc.createElement("profiles");
407             profiles.setAttribute("version", 1);
408             doc.appendChild(profiles);
409         }
410
411         QString newProfileName = ui.profile_name->text().simplified();
412         QString newGroupName = ui.group_name->text().simplified();
413         if (newGroupName.isEmpty()) newGroupName = i18n("Custom");
414         QString newMetaGroupId = ui.destination_list->itemData(ui.destination_list->currentIndex(), Qt::UserRole).toString();
415         QDomNodeList profilelist = doc.elementsByTagName("profile");
416         int i = 0;
417         while (!profilelist.item(i).isNull()) {
418             // make sure a profile with same name doesn't exist
419             documentElement = profilelist.item(i).toElement();
420             QString profileName = documentElement.attribute("name");
421             if (profileName == newProfileName) {
422                 // a profile with that same name already exists
423                 bool ok;
424                 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);
425                 if (!ok) return;
426                 if (profileName == newProfileName) {
427                     profiles.removeChild(profilelist.item(i));
428                     break;
429                 }
430             }
431             i++;
432         }
433
434         QDomElement profileElement = doc.createElement("profile");
435         profileElement.setAttribute("name", newProfileName);
436         profileElement.setAttribute("category", newGroupName);
437         profileElement.setAttribute("destinationid", newMetaGroupId);
438         profileElement.setAttribute("extension", ui.extension->text().simplified());
439         profileElement.setAttribute("args", ui.parameters->toPlainText().simplified());
440         profiles.appendChild(profileElement);
441
442         //QCString save = doc.toString().utf8();
443         delete d;
444         if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
445             KMessageBox::error(this, i18n("Cannot write to file %1", exportFile));
446             return;
447         }
448         QTextStream out(&file);
449         out << doc.toString();
450         if (file.error() != QFile::NoError) {
451             KMessageBox::error(this, i18n("Cannot write to file %1", exportFile));
452             file.close();
453             return;
454         }
455         file.close();
456         parseProfiles(newMetaGroupId, newGroupName, newProfileName);
457     } else delete d;
458 }
459
460 void RenderWidget::slotDeleteProfile(bool refresh)
461 {
462     //TODO: delete a profile installed by KNewStuff the easy way
463     /*
464     QString edit = m_view.size_list->currentItem()->data(EditableRole).toString();
465     if (!edit.endsWith("customprofiles.xml")) {
466         // This is a KNewStuff installed file, process through KNS
467         KNS::Engine engine(0);
468         if (engine.init("kdenlive_render.knsrc")) {
469             KNS::Entry::List entries;
470         }
471         return;
472     }*/
473     QString currentGroup = m_view.format_list->currentItem()->text();
474     QString currentProfile = m_view.size_list->currentItem()->text();
475     QString metaGroupId = m_view.destination_list->itemData(m_view.destination_list->currentIndex(), Qt::UserRole).toString();
476
477     QString exportFile = KStandardDirs::locateLocal("appdata", "export/customprofiles.xml");
478     QDomDocument doc;
479     QFile file(exportFile);
480     doc.setContent(&file, false);
481     file.close();
482
483     QDomElement documentElement;
484     QDomNodeList profiles = doc.elementsByTagName("profile");
485     int i = 0;
486     QString groupName;
487     QString profileName;
488     QString destination;
489
490     while (!profiles.item(i).isNull()) {
491         documentElement = profiles.item(i).toElement();
492         profileName = documentElement.attribute("name");
493         groupName = documentElement.attribute("category");
494         destination = documentElement.attribute("destinationid");
495
496         if (profileName == currentProfile && groupName == currentGroup && destination == metaGroupId) {
497             kDebug() << "// GOT it: " << profileName;
498             doc.documentElement().removeChild(profiles.item(i));
499             break;
500         }
501         i++;
502     }
503
504     if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
505         KMessageBox::sorry(this, i18n("Unable to write to file %1", exportFile));
506         return;
507     }
508     QTextStream out(&file);
509     out << doc.toString();
510     if (file.error() != QFile::NoError) {
511         KMessageBox::error(this, i18n("Cannot write to file %1", exportFile));
512         file.close();
513         return;
514     }
515     file.close();
516     if (refresh) {
517         parseProfiles(metaGroupId, currentGroup);
518         focusFirstVisibleItem();
519     }
520 }
521
522 void RenderWidget::updateButtons()
523 {
524     if (!m_view.size_list->currentItem() || m_view.size_list->currentItem()->isHidden()) {
525         m_view.buttonSave->setEnabled(false);
526         m_view.buttonDelete->setEnabled(false);
527         m_view.buttonEdit->setEnabled(false);
528         m_view.buttonStart->setEnabled(false);
529     } else {
530         m_view.buttonSave->setEnabled(true);
531         m_view.buttonStart->setEnabled(m_view.size_list->currentItem()->flags() & Qt::ItemIsEnabled);
532         QString edit = m_view.size_list->currentItem()->data(EditableRole).toString();
533         if (edit.isEmpty() || !edit.endsWith("customprofiles.xml")) {
534             m_view.buttonDelete->setEnabled(false);
535             m_view.buttonEdit->setEnabled(false);
536         } else {
537             m_view.buttonDelete->setEnabled(true);
538             m_view.buttonEdit->setEnabled(true);
539         }
540     }
541 }
542
543
544 void RenderWidget::focusFirstVisibleItem()
545 {
546     if (m_view.size_list->currentItem() && !m_view.size_list->currentItem()->isHidden()) {
547         updateButtons();
548         return;
549     }
550     for (int ix = 0; ix < m_view.size_list->count(); ix++) {
551         QListWidgetItem *item = m_view.size_list->item(ix);
552         if (item && !item->isHidden()) {
553             m_view.size_list->setCurrentRow(ix);
554             break;
555         }
556     }
557     if (!m_view.size_list->currentItem()) m_view.size_list->setCurrentRow(0);
558     updateButtons();
559 }
560
561 void RenderWidget::slotExport(bool scriptExport)
562 {
563     QListWidgetItem *item = m_view.size_list->currentItem();
564     if (!item) return;
565
566     const QString dest = m_view.out_file->url().path();
567     if (dest.isEmpty()) return;
568     QFile f(dest);
569     if (f.exists()) {
570         if (KMessageBox::warningYesNo(this, i18n("Output file already exists. Do you want to overwrite it?")) != KMessageBox::Yes)
571             return;
572     }
573
574     QString scriptName;
575     if (scriptExport) {
576         bool ok;
577         int ix = 0;
578         QString scriptsFolder = m_projectFolder + "/scripts/";
579         KStandardDirs::makeDir(scriptsFolder);
580         QString path = scriptsFolder + i18n("script") + QString::number(ix).rightJustified(3, '0', false) + ".sh";
581         while (QFile::exists(path)) {
582             ix++;
583             path = scriptsFolder + i18n("script") + QString::number(ix).rightJustified(3, '0', false) + ".sh";
584         }
585         scriptName = QInputDialog::getText(this, i18n("Create Render Script"), i18n("Script name (will be saved in: %1)", scriptsFolder), QLineEdit::Normal, KUrl(path).fileName(), &ok);
586         if (!ok || scriptName.isEmpty()) return;
587         scriptName.prepend(scriptsFolder);
588         QFile f(scriptName);
589         if (f.exists()) {
590             if (KMessageBox::warningYesNo(this, i18n("Script file already exists. Do you want to overwrite it?")) != KMessageBox::Yes)
591                 return;
592         }
593     }
594
595     QStringList overlayargs;
596     if (m_view.tc_overlay->isChecked()) {
597         QString filterFile = KStandardDirs::locate("appdata", "metadata.properties");
598         overlayargs << "meta.attr.timecode=1" << "meta.attr.timecode.markup=#timecode";
599         overlayargs << "-attach" << "data_feed:attr_check" << "-attach";
600         overlayargs << "data_show:" + filterFile << "_fezzik=1" << "dynamic=1";
601     }
602     double startPos = -1;
603     double endPos = -1;
604     if (m_view.render_guide->isChecked()) {
605         startPos = m_view.guide_start->itemData(m_view.guide_start->currentIndex()).toDouble();
606         endPos = m_view.guide_end->itemData(m_view.guide_end->currentIndex()).toDouble();
607     }
608     QString renderArgs = m_view.advanced_params->toPlainText().simplified();
609
610     // Adjust frame scale
611     int width;
612     int height;
613     if (m_view.rescale->isChecked() && m_view.rescale->isEnabled()) {
614         width = m_view.rescale_size->text().section('x', 0, 0).toInt();
615         height = m_view.rescale_size->text().section('x', 1, 1).toInt();
616     } else {
617         width = m_profile.width;
618         height = m_profile.height;
619     }
620     renderArgs.replace("%dar", '@' + QString::number(m_profile.display_aspect_num) + '/' + QString::number(m_profile.display_aspect_den));
621
622     // Adjust scanning
623     if (m_view.scanning_list->currentIndex() == 1) renderArgs.append(" progressive=1");
624     else if (m_view.scanning_list->currentIndex() == 2) renderArgs.append(" progressive=0");
625
626     // disable audio if requested
627     if (!m_view.export_audio->isChecked())
628         renderArgs.append(" an=1 ");
629
630     // Check if the rendering profile is different from project profile,
631     // in which case we need to use the producer_comsumer from MLT
632     bool resizeProfile = false;
633
634     QString std = renderArgs;
635     QString destination = m_view.destination_list->itemData(m_view.destination_list->currentIndex()).toString();
636     if (std.startsWith("s=")) {
637         QString subsize = std.section(' ', 0, 0).toLower();
638         subsize = subsize.section("=", 1, 1);
639         const QString currentSize = QString::number(width) + 'x' + QString::number(height);
640         if (subsize != currentSize) resizeProfile = true;
641     } else if (std.contains(" s=")) {
642         QString subsize = std.section(" s=", 1, 1);
643         subsize = subsize.section(' ', 0, 0).toLower();
644         const QString currentSize = QString::number(width) + 'x' + QString::number(height);
645         if (subsize != currentSize) resizeProfile = true;
646     } else if (destination != "audioonly") {
647         // Add current size parametrer
648         renderArgs.append(QString(" s=%1x%2").arg(width).arg(height));
649     }
650
651     // insert item in running jobs list
652     QTreeWidgetItem *renderItem;
653     QList<QTreeWidgetItem *> existing = m_view.running_jobs->findItems(dest, Qt::MatchExactly, 1);
654     if (!existing.isEmpty()) {
655         renderItem = existing.at(0);
656         if (renderItem->data(1, Qt::UserRole + 2).toInt() == RUNNINGJOB) {
657             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"));
658             return;
659         }
660     } else {
661         renderItem = new QTreeWidgetItem(m_view.running_jobs, QStringList() << QString() << dest << QString());
662         renderItem->setData(1, Qt::UserRole + 2, WAITINGJOB);
663         renderItem->setIcon(0, KIcon("media-playback-pause"));
664         renderItem->setData(1, Qt::UserRole, i18n("Waiting..."));
665     }
666     renderItem->setSizeHint(1, QSize(m_view.running_jobs->columnWidth(1), fontMetrics().height() * 2));
667     renderItem->setData(1, Qt::UserRole + 1, QTime::currentTime());
668     renderItem->setData(1, Qt::UserRole + 2, overlayargs);
669     QStringList renderParameters;
670     renderParameters << dest << item->data(RenderRole).toString() << renderArgs.simplified();
671     renderParameters << QString::number(m_view.render_zone->isChecked()) << QString::number(m_view.play_after->isChecked());
672     renderParameters << QString::number(startPos) << QString::number(endPos) << QString::number(resizeProfile);
673     renderParameters << scriptName;
674     renderItem->setData(1, Qt::UserRole + 3, renderParameters);
675
676     // Set rendering type
677     QString group = m_view.size_list->currentItem()->data(MetaGroupRole).toString();
678     if (group == "dvd" && m_view.open_dvd->isChecked()) {
679         renderItem->setData(0, Qt::UserRole, group);
680         if (renderArgs.contains("profile=")) {
681             // rendering profile contains an MLT profile, so pass it to the running jog item, useful for dvd
682             QString prof = renderArgs.section("profile=", 1, 1);
683             prof = prof.section(' ', 0, 0);
684             kDebug() << "// render profile: " << prof;
685             renderItem->setData(0, Qt::UserRole + 1, prof);
686         }
687     } else if (group == "websites" && m_view.open_browser->isChecked()) {
688         renderItem->setData(0, Qt::UserRole, group);
689         // pass the url
690         QString url = m_view.size_list->currentItem()->data(ExtraRole).toString();
691         renderItem->setData(0, Qt::UserRole + 1, url);
692     }
693
694     checkRenderStatus();
695     if (scriptName.isEmpty()) m_view.tabWidget->setCurrentIndex(1);
696     else {
697         QTimer::singleShot(400, this, SLOT(parseScriptFiles()));
698         m_view.tabWidget->setCurrentIndex(2);
699     }
700 }
701
702 void RenderWidget::checkRenderStatus()
703 {
704     QTreeWidgetItem *item = m_view.running_jobs->topLevelItem(0);
705     while (item) {
706         if (item->data(1, Qt::UserRole + 2).toInt() == RUNNINGJOB) break;
707         else if (item->data(1, Qt::UserRole + 2).toInt() == WAITINGJOB) {
708             item->setData(1, Qt::UserRole + 1, QTime::currentTime());
709             if (item->data(1, Qt::UserRole + 4).isNull())
710                 emit doRender(item->data(1, Qt::UserRole + 3).toStringList(), item->data(1, Qt::UserRole + 2).toStringList());
711             else QProcess::startDetached(item->data(1, Qt::UserRole + 3).toString());
712             break;
713         }
714         item = m_view.running_jobs->itemBelow(item);
715     }
716 }
717
718 void RenderWidget::setProfile(MltVideoProfile profile)
719 {
720     m_profile = profile;
721     //WARNING: this way to tell the video standard is a bit hackish...
722     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);
723     else m_view.format_selection->setCurrentIndex(1);
724     m_view.scanning_list->setCurrentIndex(0);
725     refreshView();
726 }
727
728 void RenderWidget::refreshView()
729 {
730     m_view.size_list->blockSignals(true);
731     QListWidgetItem *sizeItem;
732
733     QString destination;
734     KIcon brokenIcon("dialog-close");
735     if (m_view.destination_list->currentIndex() > 0)
736         destination = m_view.destination_list->itemData(m_view.destination_list->currentIndex()).toString();
737
738
739     if (destination == "dvd") m_view.open_dvd->setVisible(true);
740     else m_view.open_dvd->setVisible(false);
741     if (destination == "websites") m_view.open_browser->setVisible(true);
742     else m_view.open_browser->setVisible(false);
743     if (!destination.isEmpty() && QString("dvd websites audioonly").contains(destination))
744         m_view.rescale->setEnabled(false);
745     else m_view.rescale->setEnabled(true);
746     // hide groups that are not in the correct destination
747     for (int i = 0; i < m_view.format_list->count(); i++) {
748         sizeItem = m_view.format_list->item(i);
749         if (sizeItem->data(MetaGroupRole).toString() == destination) {
750             sizeItem->setHidden(false);
751             //kDebug() << "// SET GRP:: " << sizeItem->text() << ", METY:" << sizeItem->data(MetaGroupRole).toString();
752         } else sizeItem->setHidden(true);
753     }
754
755     // activate first visible item
756     QListWidgetItem * item = m_view.format_list->currentItem();
757     if (!item || item->isHidden()) {
758         for (int i = 0; i < m_view.format_list->count(); i++) {
759             if (!m_view.format_list->item(i)->isHidden()) {
760                 m_view.format_list->setCurrentRow(i);
761                 break;
762             }
763         }
764         item = m_view.format_list->currentItem();
765     }
766     if (!item || item->isHidden()) {
767         m_view.format_list->setEnabled(false);
768         m_view.size_list->setEnabled(false);
769         return;
770     } else {
771         m_view.format_list->setEnabled(true);
772         m_view.size_list->setEnabled(true);
773     }
774     int count = 0;
775     for (int i = 0; i < m_view.format_list->count() && count < 2; i++) {
776         if (!m_view.format_list->isRowHidden(i)) count++;
777     }
778     if (count > 1) m_view.format_list->setVisible(true);
779     else m_view.format_list->setVisible(false);
780     QString std;
781     QString group = item->text();
782     bool firstSelected = false;
783     const QStringList formatsList = KdenliveSettings::supportedformats();
784     const QStringList vcodecsList = KdenliveSettings::videocodecs();
785     const QStringList acodecsList = KdenliveSettings::audiocodecs();
786
787     for (int i = 0; i < m_view.size_list->count(); i++) {
788         sizeItem = m_view.size_list->item(i);
789         if ((sizeItem->data(GroupRole) == group || sizeItem->data(GroupRole).toString().isEmpty()) && sizeItem->data(MetaGroupRole) == destination) {
790             std = sizeItem->data(StandardRole).toString();
791             if (!std.isEmpty()) {
792                 if (std.contains("PAL", Qt::CaseInsensitive)) sizeItem->setHidden(m_view.format_selection->currentIndex() != 0);
793                 else if (std.contains("NTSC", Qt::CaseInsensitive)) sizeItem->setHidden(m_view.format_selection->currentIndex() != 1);
794             } else {
795                 sizeItem->setHidden(false);
796                 if (!firstSelected) m_view.size_list->setCurrentItem(sizeItem);
797                 firstSelected = true;
798             }
799
800             if (!sizeItem->isHidden()) {
801                 // Make sure the selected profile uses an installed avformat codec / format
802                 std = sizeItem->data(ParamsRole).toString();
803
804                 if (!formatsList.isEmpty()) {
805                     QString format;
806                     if (std.startsWith("f=")) format = std.section("f=", 1, 1);
807                     else if (std.contains(" f=")) format = std.section(" f=", 1, 1);
808                     if (!format.isEmpty()) {
809                         format = format.section(' ', 0, 0).toLower();
810                         if (!formatsList.contains(format)) {
811                             kDebug() << "***** UNSUPPORTED F: " << format;
812                             //sizeItem->setHidden(true);
813                             sizeItem->setFlags(Qt::ItemIsSelectable);
814                             sizeItem->setToolTip(i18n("Unsupported video format: %1", format));
815                             sizeItem->setIcon(brokenIcon);
816                         }
817                     }
818                 }
819                 if (!acodecsList.isEmpty() && !sizeItem->isHidden()) {
820                     QString format;
821                     if (std.startsWith("acodec=")) format = std.section("acodec=", 1, 1);
822                     else if (std.contains(" acodec=")) format = std.section(" acodec=", 1, 1);
823                     if (!format.isEmpty()) {
824                         format = format.section(' ', 0, 0).toLower();
825                         if (!acodecsList.contains(format)) {
826                             kDebug() << "*****  UNSUPPORTED ACODEC: " << format;
827                             //sizeItem->setHidden(true);
828                             sizeItem->setFlags(Qt::ItemIsSelectable);
829                             sizeItem->setToolTip(i18n("Unsupported audio codec: %1", format));
830                             sizeItem->setIcon(brokenIcon);
831                         }
832                     }
833                 }
834                 if (!vcodecsList.isEmpty() && !sizeItem->isHidden()) {
835                     QString format;
836                     if (std.startsWith("vcodec=")) format = std.section("vcodec=", 1, 1);
837                     else if (std.contains(" vcodec=")) format = std.section(" vcodec=", 1, 1);
838                     if (!format.isEmpty()) {
839                         format = format.section(' ', 0, 0).toLower();
840                         if (!vcodecsList.contains(format)) {
841                             kDebug() << "*****  UNSUPPORTED VCODEC: " << format;
842                             //sizeItem->setHidden(true);
843                             sizeItem->setFlags(Qt::ItemIsSelectable);
844                             sizeItem->setToolTip(i18n("Unsupported video codec: %1", format));
845                             sizeItem->setIcon(brokenIcon);
846                         }
847                     }
848                 }
849             }
850         } else sizeItem->setHidden(true);
851     }
852     focusFirstVisibleItem();
853     m_view.size_list->blockSignals(false);
854     refreshParams();
855 }
856
857 KUrl RenderWidget::filenameWithExtension(KUrl url, QString extension)
858 {
859     QString path;
860     if (!url.isEmpty()) {
861         path = url.path();
862         int pos = path.lastIndexOf('.') + 1;
863         if (pos == 0) path.append('.' + extension);
864         else path = path.left(pos) + extension;
865
866     } else {
867         path = m_projectFolder + "/untitled." + extension;
868     }
869     return KUrl(path);
870 }
871
872
873 void RenderWidget::refreshParams()
874 {
875     QListWidgetItem *item = m_view.size_list->currentItem();
876     if (!item || item->isHidden()) {
877         m_view.advanced_params->clear();
878         m_view.buttonStart->setEnabled(false);
879         return;
880     }
881     QString params = item->data(ParamsRole).toString();
882     QString extension = item->data(ExtensionRole).toString();
883     m_view.advanced_params->setPlainText(params);
884     QString destination = m_view.destination_list->itemData(m_view.destination_list->currentIndex()).toString();
885     if (params.contains(" s=") || destination == "audioonly") {
886         // profile has a fixed size, do not allow resize
887         m_view.rescale->setEnabled(false);
888         m_view.rescale_size->setEnabled(false);
889     } else {
890         m_view.rescale->setEnabled(true);
891         m_view.rescale_size->setEnabled(true);
892     }
893     KUrl url = filenameWithExtension(m_view.out_file->url(), extension);
894     m_view.out_file->setUrl(url);
895 //     if (!url.isEmpty()) {
896 //         QString path = url.path();
897 //         int pos = path.lastIndexOf('.') + 1;
898 //  if (pos == 0) path.append('.' + extension);
899 //         else path = path.left(pos) + extension;
900 //         m_view.out_file->setUrl(KUrl(path));
901 //     } else {
902 //         m_view.out_file->setUrl(KUrl(QDir::homePath() + "/untitled." + extension));
903 //     }
904     m_view.out_file->setFilter("*." + extension);
905     QString edit = item->data(EditableRole).toString();
906     if (edit.isEmpty() || !edit.endsWith("customprofiles.xml")) {
907         m_view.buttonDelete->setEnabled(false);
908         m_view.buttonEdit->setEnabled(false);
909     } else {
910         m_view.buttonDelete->setEnabled(true);
911         m_view.buttonEdit->setEnabled(true);
912     }
913
914     m_view.buttonStart->setEnabled(m_view.size_list->currentItem()->flags() & Qt::ItemIsEnabled);
915 }
916
917 void RenderWidget::reloadProfiles()
918 {
919     parseProfiles();
920 }
921
922 void RenderWidget::parseProfiles(QString meta, QString group, QString profile)
923 {
924     m_view.size_list->clear();
925     m_view.format_list->clear();
926     m_view.destination_list->clear();
927     m_view.destination_list->addItem(KIcon("video-x-generic"), i18n("File rendering"));
928     m_view.destination_list->addItem(KIcon("media-optical"), i18n("DVD"), "dvd");
929     m_view.destination_list->addItem(KIcon("audio-x-generic"), i18n("Audio only"), "audioonly");
930     m_view.destination_list->addItem(KIcon("applications-internet"), i18n("Web sites"), "websites");
931     m_view.destination_list->addItem(KIcon("applications-multimedia"), i18n("Media players"), "mediaplayers");
932     m_view.destination_list->addItem(KIcon("drive-harddisk"), i18n("Lossless / HQ"), "lossless");
933     m_view.destination_list->addItem(KIcon("pda"), i18n("Mobile devices"), "mobile");
934
935     QString exportFile = KStandardDirs::locate("appdata", "export/profiles.xml");
936     parseFile(exportFile, false);
937
938
939     QString exportFolder = KStandardDirs::locateLocal("appdata", "export/");
940     QDir directory = QDir(exportFolder);
941     QStringList filter;
942     filter << "*.xml";
943     QStringList fileList = directory.entryList(filter, QDir::Files);
944     // We should parse customprofiles.xml in last position, so that user profiles
945     // can also override profiles installed by KNewStuff
946     fileList.removeAll("customprofiles.xml");
947     foreach(const QString &filename, fileList)
948     parseFile(exportFolder + '/' + filename, true);
949     if (QFile::exists(exportFolder + "/customprofiles.xml")) parseFile(exportFolder + "/customprofiles.xml", true);
950
951     if (!meta.isEmpty()) {
952         m_view.destination_list->blockSignals(true);
953         m_view.destination_list->setCurrentIndex(m_view.destination_list->findData(meta));
954         m_view.destination_list->blockSignals(false);
955     }
956     refreshView();
957     QList<QListWidgetItem *> child;
958     if (!group.isEmpty()) child = m_view.format_list->findItems(group, Qt::MatchExactly);
959     if (!child.isEmpty()) {
960         for (int i = 0; i < child.count(); i++) {
961             if (child.at(i)->data(MetaGroupRole).toString() == meta) {
962                 m_view.format_list->setCurrentItem(child.at(i));
963                 break;
964             }
965         }
966     }
967     child.clear();
968     if (!profile.isEmpty()) child = m_view.size_list->findItems(profile, Qt::MatchExactly);
969     if (!child.isEmpty()) m_view.size_list->setCurrentItem(child.at(0));
970 }
971
972 void RenderWidget::parseFile(QString exportFile, bool editable)
973 {
974     kDebug() << "// Parsing file: " << exportFile;
975     kDebug() << "------------------------------";
976     QDomDocument doc;
977     QFile file(exportFile);
978     doc.setContent(&file, false);
979     file.close();
980     QDomElement documentElement;
981     QDomElement profileElement;
982     QString extension;
983     QListWidgetItem *item;
984     QDomNodeList groups = doc.elementsByTagName("group");
985
986     if (editable || groups.count() == 0) {
987         QDomElement profiles = doc.documentElement();
988         if (editable && profiles.attribute("version", 0).toInt() < 1) {
989             kDebug() << "// OLD profile version";
990             // this is an old profile version, update it
991             QDomDocument newdoc;
992             QDomElement newprofiles = newdoc.createElement("profiles");
993             newprofiles.setAttribute("version", 1);
994             newdoc.appendChild(newprofiles);
995             QDomNodeList profilelist = doc.elementsByTagName("profile");
996             for (int i = 0; i < profilelist.count(); i++) {
997                 QString category = i18n("Custom");
998                 QString extension;
999                 QDomNode parent = profilelist.at(i).parentNode();
1000                 if (!parent.isNull()) {
1001                     QDomElement parentNode = parent.toElement();
1002                     if (parentNode.hasAttribute("name")) category = parentNode.attribute("name");
1003                     extension = parentNode.attribute("extension");
1004                 }
1005                 profilelist.at(i).toElement().setAttribute("category", category);
1006                 if (!extension.isEmpty()) profilelist.at(i).toElement().setAttribute("extension", extension);
1007                 QDomNode n = profilelist.at(i).cloneNode();
1008                 newprofiles.appendChild(newdoc.importNode(n, true));
1009             }
1010             if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
1011                 KMessageBox::sorry(this, i18n("Unable to write to file %1", exportFile));
1012                 return;
1013             }
1014             QTextStream out(&file);
1015             out << newdoc.toString();
1016             file.close();
1017             parseFile(exportFile, editable);
1018             return;
1019         }
1020
1021         QDomNode node = doc.elementsByTagName("profile").at(0);
1022         if (node.isNull()) {
1023             kDebug() << "// Export file: " << exportFile << " IS BROKEN";
1024             return;
1025         }
1026         int count = 1;
1027         while (!node.isNull()) {
1028             QDomElement profile = node.toElement();
1029             QString profileName = profile.attribute("name");
1030             QString standard = profile.attribute("standard");
1031             QString params = profile.attribute("args");
1032             QString category = profile.attribute("category", i18n("Custom"));
1033             QString dest = profile.attribute("destinationid");
1034             QString prof_extension = profile.attribute("extension");
1035             if (!prof_extension.isEmpty()) extension = prof_extension;
1036
1037             QList <QListWidgetItem *> list = m_view.format_list->findItems(category, Qt::MatchExactly);
1038             bool exists = false;
1039             for (int j = 0; j < list.count(); j++) {
1040                 if (list.at(j)->data(MetaGroupRole) == dest) {
1041                     exists = true;
1042                     break;
1043                 }
1044             }
1045             if (!exists) {
1046                 item = new QListWidgetItem(category, m_view.format_list);
1047                 item->setData(MetaGroupRole, dest);
1048             }
1049
1050             // Check if item with same name already exists and replace it,
1051             // allowing to override default profiles
1052
1053             list = m_view.size_list->findItems(profileName, Qt::MatchExactly);
1054
1055             for (int j = 0; j < list.count(); j++) {
1056                 if (list.at(j)->data(MetaGroupRole) == dest) {
1057                     QListWidgetItem *duplicate = list.takeAt(j);
1058                     delete duplicate;
1059                     j--;
1060                 }
1061             }
1062
1063             item = new QListWidgetItem(profileName, m_view.size_list);
1064             //kDebug() << "// ADDINg item with name: " << profileName << ", GRP" << category << ", DEST:" << dest ;
1065             item->setData(GroupRole, category);
1066             item->setData(MetaGroupRole, dest);
1067             item->setData(ExtensionRole, extension);
1068             item->setData(RenderRole, "avformat");
1069             item->setData(StandardRole, standard);
1070             item->setData(ParamsRole, params);
1071             if (profile.hasAttribute("url")) item->setData(ExtraRole, profile.attribute("url"));
1072             if (editable) {
1073                 item->setData(EditableRole, exportFile);
1074                 if (exportFile.endsWith("customprofiles.xml")) item->setIcon(KIcon("emblem-favorite"));
1075                 else item->setIcon(KIcon("applications-internet"));
1076             }
1077             node = doc.elementsByTagName("profile").at(count);
1078             count++;
1079         }
1080         return;
1081     }
1082
1083     int i = 0;
1084     QString groupName;
1085     QString profileName;
1086
1087     QString prof_extension;
1088     QString renderer;
1089     QString params;
1090     QString standard;
1091     KIcon icon;
1092
1093     while (!groups.item(i).isNull()) {
1094         documentElement = groups.item(i).toElement();
1095         QDomNode gname = documentElement.elementsByTagName("groupname").at(0);
1096         QString metagroupName;
1097         QString metagroupId;
1098         if (!gname.isNull()) {
1099             metagroupName = gname.firstChild().nodeValue();
1100             metagroupId = gname.toElement().attribute("id");
1101             if (!metagroupName.isEmpty() && !m_view.destination_list->contains(metagroupName)) {
1102                 if (metagroupId == "dvd") icon = KIcon("media-optical");
1103                 else if (metagroupId == "audioonly") icon = KIcon("audio-x-generic");
1104                 else if (metagroupId == "websites") icon = KIcon("applications-internet");
1105                 else if (metagroupId == "mediaplayers") icon = KIcon("applications-multimedia");
1106                 else if (metagroupId == "lossless") icon = KIcon("drive-harddisk");
1107                 else if (metagroupId == "mobile") icon = KIcon("pda");
1108                 m_view.destination_list->addItem(icon, i18n(metagroupName.toUtf8().data()), metagroupId);
1109             }
1110         }
1111         groupName = documentElement.attribute("name", i18n("Custom"));
1112         extension = documentElement.attribute("extension", QString());
1113         renderer = documentElement.attribute("renderer", QString());
1114         QList <QListWidgetItem *> list = m_view.format_list->findItems(groupName, Qt::MatchExactly);
1115         bool exists = false;
1116         for (int j = 0; j < list.count(); j++) {
1117             if (list.at(j)->data(MetaGroupRole) == metagroupId) {
1118                 exists = true;
1119                 break;
1120             }
1121         }
1122         if (!exists) {
1123             item = new QListWidgetItem(groupName, m_view.format_list);
1124             item->setData(MetaGroupRole, metagroupId);
1125         }
1126
1127         QDomNode n = groups.item(i).firstChild();
1128         while (!n.isNull()) {
1129             if (n.toElement().tagName() != "profile") {
1130                 n = n.nextSibling();
1131                 continue;
1132             }
1133             profileElement = n.toElement();
1134             profileName = profileElement.attribute("name");
1135             standard = profileElement.attribute("standard");
1136             params = profileElement.attribute("args");
1137             prof_extension = profileElement.attribute("extension");
1138             if (!prof_extension.isEmpty()) extension = prof_extension;
1139             item = new QListWidgetItem(profileName, m_view.size_list);
1140             item->setData(GroupRole, groupName);
1141             item->setData(MetaGroupRole, metagroupId);
1142             item->setData(ExtensionRole, extension);
1143             item->setData(RenderRole, renderer);
1144             item->setData(StandardRole, standard);
1145             item->setData(ParamsRole, params);
1146             if (profileElement.hasAttribute("url")) item->setData(ExtraRole, profileElement.attribute("url"));
1147             if (editable) item->setData(EditableRole, exportFile);
1148             n = n.nextSibling();
1149         }
1150
1151         i++;
1152     }
1153 }
1154
1155 void RenderWidget::setRenderJob(const QString &dest, int progress)
1156 {
1157     QTreeWidgetItem *item;
1158     QList<QTreeWidgetItem *> existing = m_view.running_jobs->findItems(dest, Qt::MatchExactly, 1);
1159     if (!existing.isEmpty()) item = existing.at(0);
1160     else {
1161         item = new QTreeWidgetItem(m_view.running_jobs, QStringList() << QString() << dest << QString());
1162         item->setSizeHint(1, QSize(m_view.running_jobs->columnWidth(1), fontMetrics().height() * 2));
1163         if (progress == 0) {
1164             item->setData(1, Qt::UserRole + 2, WAITINGJOB);
1165             item->setIcon(0, KIcon("media-playback-pause"));
1166             item->setData(1, Qt::UserRole, i18n("Waiting..."));
1167         }
1168     }
1169     item->setData(2, Qt::UserRole, progress);
1170     item->setData(1, Qt::UserRole + 2, RUNNINGJOB);
1171     if (progress == 0) {
1172         item->setIcon(0, KIcon("system-run"));
1173         item->setSizeHint(1, QSize(m_view.running_jobs->columnWidth(1), fontMetrics().height() * 2));
1174         item->setData(1, Qt::UserRole + 1, QTime::currentTime());
1175         slotCheckJob();
1176     } else {
1177         QTime startTime = item->data(1, Qt::UserRole + 1).toTime();
1178         int seconds = startTime.secsTo(QTime::currentTime());;
1179         const QString t = i18n("Estimated time %1", QTime().addSecs(seconds * (100 - progress) / progress).toString("hh:mm:ss"));
1180         item->setData(1, Qt::UserRole, t);
1181     }
1182 }
1183
1184 void RenderWidget::setRenderStatus(const QString &dest, int status, const QString &error)
1185 {
1186     QTreeWidgetItem *item;
1187     QList<QTreeWidgetItem *> existing = m_view.running_jobs->findItems(dest, Qt::MatchExactly, 1);
1188     if (!existing.isEmpty()) item = existing.at(0);
1189     else {
1190         item = new QTreeWidgetItem(m_view.running_jobs, QStringList() << QString() << dest << QString());
1191         item->setSizeHint(1, QSize(m_view.running_jobs->columnWidth(1), fontMetrics().height() * 2));
1192     }
1193     item->setData(1, Qt::UserRole + 2, FINISHEDJOB);
1194     if (status == -1) {
1195         // Job finished successfully
1196         item->setIcon(0, KIcon("dialog-ok"));
1197         item->setData(2, Qt::UserRole, 100);
1198         QTime startTime = item->data(1, Qt::UserRole + 1).toTime();
1199         int seconds = startTime.secsTo(QTime::currentTime());
1200         const QTime tm = QTime().addSecs(seconds);
1201         const QString t = i18n("Rendering finished in %1", tm.toString("hh:mm:ss"));
1202         item->setData(1, Qt::UserRole, t);
1203         QString itemGroup = item->data(0, Qt::UserRole).toString();
1204         if (itemGroup == "dvd") {
1205             emit openDvdWizard(item->text(1), item->data(0, Qt::UserRole + 1).toString());
1206         } else if (itemGroup == "websites") {
1207             QString url = item->data(0, Qt::UserRole + 1).toString();
1208             if (!url.isEmpty()) new KRun(url, this);
1209         }
1210     } else if (status == -2) {
1211         // Rendering crashed
1212         item->setData(1, Qt::UserRole, i18n("Rendering crashed"));
1213         item->setIcon(0, KIcon("dialog-close"));
1214         item->setData(2, Qt::UserRole, 100);
1215         m_view.error_log->append(i18n("<strong>Rendering of %1 crashed</strong><br />", dest));
1216         m_view.error_log->append(error);
1217         m_view.error_log->append("<hr />");
1218         m_view.error_box->setVisible(true);
1219     } else if (status == -3) {
1220         // User aborted job
1221         item->setData(1, Qt::UserRole, i18n("Rendering aborted"));
1222         item->setIcon(0, KIcon("dialog-cancel"));
1223         item->setData(2, Qt::UserRole, 100);
1224     }
1225     slotCheckJob();
1226     checkRenderStatus();
1227 }
1228
1229 void RenderWidget::slotAbortCurrentJob()
1230 {
1231     QTreeWidgetItem *current = m_view.running_jobs->currentItem();
1232     if (current) {
1233         if (current->data(1, Qt::UserRole + 2).toInt() == RUNNINGJOB)
1234             emit abortProcess(current->text(1));
1235         else {
1236             delete current;
1237             slotCheckJob();
1238         }
1239     }
1240 }
1241
1242 void RenderWidget::slotCheckJob()
1243 {
1244     bool activate = false;
1245     QTreeWidgetItem *current = m_view.running_jobs->currentItem();
1246     if (current) {
1247         if (current->data(1, Qt::UserRole + 2).toInt() == RUNNINGJOB)
1248             m_view.abort_job->setText(i18n("Abort Job"));
1249         else m_view.abort_job->setText(i18n("Remove Job"));
1250         activate = true;
1251     }
1252     m_view.abort_job->setEnabled(activate);
1253 }
1254
1255 void RenderWidget::slotCLeanUpJobs()
1256 {
1257     int ix = 0;
1258     QTreeWidgetItem *current = m_view.running_jobs->topLevelItem(ix);
1259     while (current) {
1260         if (current->data(1, Qt::UserRole + 2).toInt() == FINISHEDJOB)
1261             delete current;
1262         else ix++;
1263         current = m_view.running_jobs->topLevelItem(ix);
1264     }
1265     slotCheckJob();
1266 }
1267
1268 void RenderWidget::parseScriptFiles()
1269 {
1270     QStringList scriptsFilter;
1271     scriptsFilter << "*.sh";
1272     m_view.scripts_list->clear();
1273
1274     QTreeWidgetItem *item;
1275     // List the project scripts
1276     QStringList scriptFiles = QDir(m_projectFolder + "/scripts").entryList(scriptsFilter, QDir::Files);
1277     for (int i = 0; i < scriptFiles.size(); ++i) {
1278         KUrl scriptpath(m_projectFolder + "/scripts/" + scriptFiles.at(i));
1279         item = new QTreeWidgetItem(m_view.scripts_list, QStringList() << scriptpath.fileName());
1280         QString target;
1281         QFile file(scriptpath.path());
1282         if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
1283             while (!file.atEnd()) {
1284                 QByteArray line = file.readLine();
1285                 if (line.startsWith("TARGET=")) {
1286                     target = QString(line).section("TARGET=", 1);
1287                     target.remove(QChar('"'));
1288                     break;
1289                 }
1290             }
1291             file.close();
1292         }
1293         item->setSizeHint(0, QSize(m_view.scripts_list->columnWidth(0), fontMetrics().height() * 2));
1294         item->setData(0, Qt::UserRole, target.simplified());
1295         item->setData(0, Qt::UserRole + 1, scriptpath.path());
1296     }
1297     bool activate = false;
1298     QTreeWidgetItem *script = m_view.scripts_list->topLevelItem(0);
1299     if (script) {
1300         script->setSelected(true);
1301         m_view.scripts_list->setCurrentItem(script);
1302         activate = true;
1303     }
1304 //    m_view.start_script->setEnabled(activate);
1305 //    m_view.delete_script->setEnabled(activate);
1306 }
1307
1308 void RenderWidget::slotCheckScript()
1309 {
1310     bool activate = false;
1311     QTreeWidgetItemIterator it(m_view.scripts_list);
1312     if (*it) activate = true;
1313     m_view.start_script->setEnabled(activate);
1314     m_view.delete_script->setEnabled(activate);
1315 }
1316
1317 void RenderWidget::slotStartScript()
1318 {
1319     QTreeWidgetItem *item = m_view.scripts_list->currentItem();
1320     if (item) {
1321         QString destination = item->data(0, Qt::UserRole).toString();
1322         QString path = item->data(0, Qt::UserRole + 1).toString();
1323         // Insert new job in queue
1324         QTreeWidgetItem *renderItem;
1325         QList<QTreeWidgetItem *> existing = m_view.running_jobs->findItems(destination, Qt::MatchExactly, 1);
1326         if (!existing.isEmpty()) {
1327             renderItem = existing.at(0);
1328             if (renderItem->data(1, Qt::UserRole + 2).toInt() == RUNNINGJOB) {
1329                 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"));
1330                 return;
1331             }
1332         } else renderItem = new QTreeWidgetItem(m_view.running_jobs, QStringList() << QString() << destination << QString());
1333         renderItem->setData(1, Qt::UserRole + 2, WAITINGJOB);
1334         renderItem->setIcon(0, KIcon("media-playback-pause"));
1335         renderItem->setData(1, Qt::UserRole, i18n("Waiting..."));
1336         renderItem->setSizeHint(1, QSize(m_view.running_jobs->columnWidth(1), fontMetrics().height() * 2));
1337         renderItem->setData(1, Qt::UserRole + 1, QTime::currentTime());
1338         renderItem->setData(1, Qt::UserRole + 3, path);
1339         renderItem->setData(1, Qt::UserRole + 4, '1');
1340         checkRenderStatus();
1341         m_view.tabWidget->setCurrentIndex(1);
1342     }
1343 }
1344
1345 void RenderWidget::slotDeleteScript()
1346 {
1347     QTreeWidgetItem *item = m_view.scripts_list->currentItem();
1348     if (item) {
1349         QString path = item->data(0, Qt::UserRole + 1).toString();
1350         KIO::NetAccess::del(path + ".westley", this);
1351         KIO::NetAccess::del(path, this);
1352         parseScriptFiles();
1353     }
1354 }
1355
1356 void RenderWidget::slotGenerateScript()
1357 {
1358     slotExport(true);
1359 }
1360
1361 void RenderWidget::slotHideLog()
1362 {
1363     m_view.error_box->setVisible(false);
1364 }