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