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