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