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