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