Members of the KDE Community are recommended to subscribe to the kde-community mailing list at https://mail.kde.org/mailman/listinfo/kde-community to allow them to participate in important discussions and receive other important announcements

renderwidget.cpp 117 KB
Newer Older
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/***************************************************************************
 *   Copyright (C) 2008 by Jean-Baptiste Mardelle (jb@kdenlive.org)        *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA          *
 ***************************************************************************/

20

21 22 23
#include "renderwidget.h"
#include "kdenlivesettings.h"
#include "ui_saveprofile_ui.h"
24
#include "timecode.h"
Vincent Pinon's avatar
Vincent Pinon committed
25
#include "dialogs/profilesdialog.h"
26
#include "utils/KoIconUtils.h"
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
27

28
#include "klocalizedstring.h"
29
#include <KMessageBox>
30
#include <KRun>
31
#include <KColorScheme>
32
#include <KNotification>
33

34
#include <QDebug>
35 36 37 38 39
#include <QDomDocument>
#include <QTreeWidgetItem>
#include <QListWidgetItem>
#include <QHeaderView>
#include <QInputDialog>
40
#include <QProcess>
41
#include <QDBusConnectionInterface>
42
#include <QThread>
43
#include <QScriptEngine>
44
#include <QKeyEvent>
45
#include <QTimer>
46
#include <QStandardPaths>
47
#include <QDir>
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
48

Vincent Pinon's avatar
Vincent Pinon committed
49
#include <locale>
50 51 52
#ifdef Q_OS_MAC
#include <xlocale.h>
#endif
53

54 55

// Render profiles roles
56 57 58 59 60 61 62 63 64 65 66
enum {GroupRole = Qt::UserRole,
      ExtensionRole,
      StandardRole,
      RenderRole,
      ParamsRole,
      EditableRole,
      MetaGroupRole,
      ExtraRole,
      BitratesRole,
      DefaultBitrateRole,
      AudioBitratesRole,
67 68
      DefaultAudioBitrateRole,
      ErrorRole
69
     };
70

71 72 73
// Render job roles
const int ParametersRole = Qt::UserRole + 1;
const int TimeRole = Qt::UserRole + 2;
74 75
const int ProgressRole = Qt::UserRole + 3;
const int ExtraInfoRole = Qt::UserRole + 5;
76

77 78
const int DirectRenderType = QTreeWidgetItem::Type;
const int ScriptRenderType = QTreeWidgetItem::UserType;
79 80


81
// Running job status
82 83 84 85 86 87 88 89
enum JOBSTATUS {
    WAITINGJOB = 0,
    STARTINGJOB,
    RUNNINGJOB,
    FINISHEDJOB,
    FAILEDJOB,
    ABORTEDJOB
};
90 91


Laurent Montel's avatar
Laurent Montel committed
92 93
RenderJobItem::RenderJobItem(QTreeWidget * parent, const QStringList & strings, int type)
    : QTreeWidgetItem(parent, strings, type),
94 95
    m_status(-1)
{
96
    setSizeHint(1, QSize(parent->columnWidth(1), parent->fontMetrics().height() * 3));
97 98 99 100 101
    setStatus(WAITINGJOB);
}

void RenderJobItem::setStatus(int status)
{
Laurent Montel's avatar
Laurent Montel committed
102 103
    if (m_status == status)
        return;
104 105 106
    m_status = status;
    switch (status) {
        case WAITINGJOB:
107
            setIcon(0, KoIconUtils::themedIcon(QStringLiteral("media-playback-pause")));
108 109 110 111
            setData(1, Qt::UserRole, i18n("Waiting..."));
            break;
        case FINISHEDJOB:
            setData(1, Qt::UserRole, i18n("Rendering finished"));
112
            setIcon(0, KoIconUtils::themedIcon(QStringLiteral("dialog-ok")));
113
            setData(1, ProgressRole, 100);
114 115 116
            break;
        case FAILEDJOB:
            setData(1, Qt::UserRole, i18n("Rendering crashed"));
117
            setIcon(0, KoIconUtils::themedIcon(QStringLiteral("dialog-close")));
118
            setData(1, ProgressRole, 100);
119 120 121
            break;
        case ABORTEDJOB:
            setData(1, Qt::UserRole, i18n("Rendering aborted"));
122
            setIcon(0, KoIconUtils::themedIcon(QStringLiteral("dialog-cancel")));
123
            setData(1, ProgressRole, 100);
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
        default:
            break;
    }
}

int RenderJobItem::status() const
{
    return m_status;
}

void RenderJobItem::setMetadata(const QString &data)
{
    m_data = data;
}

const QString RenderJobItem::metadata() const
{
    return m_data;
}
143 144


Laurent Montel's avatar
Laurent Montel committed
145
RenderWidget::RenderWidget(const QString &projectfolder, bool enableProxy, const MltVideoProfile &profile, QWidget * parent) :
146
        QDialog(parent),
147
        m_projectFolder(projectfolder),
148
        m_profile(profile),
149
        m_blockProcessing(false)
150
{
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
151
    m_view.setupUi(this);
152 153 154
    int size = style()->pixelMetric(QStyle::PM_SmallIconSize);
    QSize iconSize(size, size);
    
155
    setWindowTitle(i18n("Rendering"));
156 157 158 159 160 161
    m_view.buttonDelete->setIconSize(iconSize);
    m_view.buttonEdit->setIconSize(iconSize);
    m_view.buttonSave->setIconSize(iconSize);
    m_view.buttonInfo->setIconSize(iconSize);
    m_view.buttonFavorite->setIconSize(iconSize);
    
162
    m_view.buttonDelete->setIcon(KoIconUtils::themedIcon(QStringLiteral("trash-empty")));
163 164 165
    m_view.buttonDelete->setToolTip(i18n("Delete profile"));
    m_view.buttonDelete->setEnabled(false);

166
    m_view.buttonEdit->setIcon(KoIconUtils::themedIcon(QStringLiteral("document-properties")));
167 168 169
    m_view.buttonEdit->setToolTip(i18n("Edit profile"));
    m_view.buttonEdit->setEnabled(false);

170
    m_view.buttonSave->setIcon(KoIconUtils::themedIcon(QStringLiteral("document-new")));
171 172
    m_view.buttonSave->setToolTip(i18n("Create new profile"));

173 174
    m_view.buttonInfo->setIcon(KoIconUtils::themedIcon(QStringLiteral("help-about")));
    m_view.hide_log->setIcon(KoIconUtils::themedIcon(QStringLiteral("go-down")));
175

176
    m_view.buttonFavorite->setIcon(KoIconUtils::themedIcon(QStringLiteral("favorite")));
177
    m_view.buttonFavorite->setToolTip(i18n("Copy profile to favorites"));
178
    
179 180
    m_view.show_all_profiles->setToolTip(i18n("Show profiles with different framerate"));
    
181
    m_view.advanced_params->setMaximumHeight(QFontMetrics(font()).lineSpacing() * 5);
182 183 184
    
    m_view.buttonRender->setEnabled(false);
    m_view.buttonGenerateScript->setEnabled(false);
185
    setRescaleEnabled(false);
186 187 188 189 190 191 192 193
    m_view.guides_box->setVisible(false);
    m_view.open_dvd->setVisible(false);
    m_view.create_chapter->setVisible(false);
    m_view.open_browser->setVisible(false);
    m_view.error_box->setVisible(false);
    m_view.tc_type->setEnabled(false);
    m_view.checkTwoPass->setEnabled(false);
    
194 195
    if (KdenliveSettings::showrenderparams()) {
        m_view.buttonInfo->setDown(true);
Laurent Montel's avatar
Laurent Montel committed
196 197 198
    } else {
        m_view.advanced_params->hide();
    }
199
    
200
    m_view.proxy_render->setHidden(!enableProxy);
201

202 203
    KColorScheme scheme(palette().currentColorGroup(), KColorScheme::Window, KSharedConfig::openConfig(KdenliveSettings::colortheme()));
    QColor bg = scheme.background(KColorScheme::NegativeBackground).color();
204
    m_view.errorBox->setStyleSheet(QStringLiteral("QGroupBox { background-color: rgb(%1, %2, %3); border-radius: 5px;}; ").arg(bg.red()).arg(bg.green()).arg(bg.blue()));
205
    int height = QFontInfo(font()).pixelSize();
206
    m_view.errorIcon->setPixmap(KoIconUtils::themedIcon(QStringLiteral("dialog-warning")).pixmap(height, height));
207 208 209 210 211 212 213 214
    m_view.errorBox->setHidden(true);

    m_infoMessage = new KMessageWidget;
    QGridLayout *s =  static_cast <QGridLayout*> (m_view.tab->layout());
    s->addWidget(m_infoMessage, 16, 0, 1, -1);
    m_infoMessage->setCloseButtonVisible(false);
    m_infoMessage->hide();

215 216 217 218
    m_view.encoder_threads->setMaximum(QThread::idealThreadCount());
    m_view.encoder_threads->setValue(KdenliveSettings::encodethreads());
    connect(m_view.encoder_threads, SIGNAL(valueChanged(int)), this, SLOT(slotUpdateEncodeThreads(int)));

219 220 221
    m_view.rescale_keep->setChecked(KdenliveSettings::rescalekeepratio());
    connect(m_view.rescale_width, SIGNAL(valueChanged(int)), this, SLOT(slotUpdateRescaleWidth(int)));
    connect(m_view.rescale_height, SIGNAL(valueChanged(int)), this, SLOT(slotUpdateRescaleHeight(int)));
222
    m_view.rescale_keep->setIcon(KoIconUtils::themedIcon(QStringLiteral("edit-link")));
223 224
    m_view.rescale_keep->setToolTip(i18n("Preserve aspect ratio"));
    connect(m_view.rescale_keep, SIGNAL(clicked()), this, SLOT(slotSwitchAspectRatio()));
225

226 227 228
    connect(m_view.buttonRender, SIGNAL(clicked()), this, SLOT(slotPrepareExport()));
    connect(m_view.buttonGenerateScript, SIGNAL(clicked()), this, SLOT(slotGenerateScript()));

229 230 231 232
    m_view.abort_job->setEnabled(false);
    m_view.start_script->setEnabled(false);
    m_view.delete_script->setEnabled(false);

233 234
    m_view.format_list->setAlternatingRowColors(true);
    m_view.size_list->setAlternatingRowColors(true);
235

236 237 238
    connect(m_view.export_audio, SIGNAL(stateChanged(int)), this, SLOT(slotUpdateAudioLabel(int)));
    m_view.export_audio->setCheckState(Qt::PartiallyChecked);

239
    parseProfiles();
240
    parseScriptFiles();
241 242
    m_view.running_jobs->setUniformRowHeights(false);
    m_view.scripts_list->setUniformRowHeights(false);
243 244
    connect(m_view.start_script, SIGNAL(clicked()), this, SLOT(slotStartScript()));
    connect(m_view.delete_script, SIGNAL(clicked()), this, SLOT(slotDeleteScript()));
245 246
    connect(m_view.scripts_list, SIGNAL(itemSelectionChanged()), this, SLOT(slotCheckScript()));
    connect(m_view.running_jobs, SIGNAL(itemSelectionChanged()), this, SLOT(slotCheckJob()));
Laurent Montel's avatar
Laurent Montel committed
247
    connect(m_view.running_jobs, SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)), this, SLOT(slotPlayRendering(QTreeWidgetItem*,int)));
248

249 250
    connect(m_view.buttonInfo, SIGNAL(clicked()), this, SLOT(showInfoPanel()));

251
    connect(m_view.buttonSave, SIGNAL(clicked()), this, SLOT(slotSaveProfile()));
252
    connect(m_view.buttonEdit, SIGNAL(clicked()), this, SLOT(slotEditProfile()));
253
    connect(m_view.buttonDelete, SIGNAL(clicked()), this, SLOT(slotDeleteProfile()));
254 255
    connect(m_view.buttonFavorite, SIGNAL(clicked()), this, SLOT(slotCopyToFavorites()));

256
    connect(m_view.abort_job, SIGNAL(clicked()), this, SLOT(slotAbortCurrentJob()));
257
    connect(m_view.start_job, SIGNAL(clicked()), this, SLOT(slotStartCurrentJob()));
258 259 260
    connect(m_view.clean_up, SIGNAL(clicked()), this, SLOT(slotCLeanUpJobs()));
    connect(m_view.hide_log, SIGNAL(clicked()), this, SLOT(slotHideLog()));

261 262
    connect(m_view.buttonClose, SIGNAL(clicked()), this, SLOT(hide()));
    connect(m_view.buttonClose2, SIGNAL(clicked()), this, SLOT(hide()));
263
    connect(m_view.buttonClose3, SIGNAL(clicked()), this, SLOT(hide()));
264
    connect(m_view.rescale, SIGNAL(toggled(bool)), this, SLOT(setRescaleEnabled(bool)));
265
    connect(m_view.destination_list, SIGNAL(activated(int)), this, SLOT(refreshCategory()));
Laurent Montel's avatar
Laurent Montel committed
266
    connect(m_view.out_file, SIGNAL(textChanged(QString)), this, SLOT(slotUpdateButtons()));
267
    connect(m_view.out_file, SIGNAL(urlSelected(QUrl)), this, SLOT(slotUpdateButtons(QUrl)));
268 269
    connect(m_view.format_list, SIGNAL(currentRowChanged(int)), this, SLOT(refreshView()));
    connect(m_view.size_list, SIGNAL(currentRowChanged(int)), this, SLOT(refreshParams()));
270
    connect(m_view.show_all_profiles, SIGNAL(stateChanged(int)), this, SLOT(refreshView()));
271

Laurent Montel's avatar
Laurent Montel committed
272
    connect(m_view.size_list, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(slotEditItem(QListWidgetItem*)));
273

274 275 276 277 278 279 280
    connect(m_view.render_guide, SIGNAL(clicked(bool)), this, SLOT(slotUpdateGuideBox()));
    connect(m_view.render_zone, SIGNAL(clicked(bool)), this, SLOT(slotUpdateGuideBox()));
    connect(m_view.render_full, SIGNAL(clicked(bool)), this, SLOT(slotUpdateGuideBox()));

    connect(m_view.guide_end, SIGNAL(activated(int)), this, SLOT(slotCheckStartGuidePosition()));
    connect(m_view.guide_start, SIGNAL(activated(int)), this, SLOT(slotCheckEndGuidePosition()));

281
    connect(m_view.tc_overlay, SIGNAL(toggled(bool)), m_view.tc_type, SLOT(setEnabled(bool)));
282

283 284
    m_view.splitter->setStretchFactor(1, 5);
    m_view.splitter->setStretchFactor(0, 2);
285

286
    m_view.out_file->setMode(KFile::File);
287
    m_view.out_file->setFocusPolicy(Qt::ClickFocus);
288

289
    m_view.running_jobs->setHeaderLabels(QStringList() << QString() << i18n("File"));
290 291
    m_jobsDelegate = new RenderViewDelegate(this);
    m_view.running_jobs->setItemDelegate(m_jobsDelegate);
292

293
    QHeaderView *header = m_view.running_jobs->header();
294
    header->setSectionResizeMode(0, QHeaderView::Fixed);
295
    header->resizeSection(0, 30);
296
    header->setSectionResizeMode(1, QHeaderView::Interactive);
297

298
    m_view.scripts_list->setHeaderLabels(QStringList() << QString() << i18n("Script Files"));
299 300
    m_scriptsDelegate = new RenderViewDelegate(this);
    m_view.scripts_list->setItemDelegate(m_scriptsDelegate);
301
    header = m_view.scripts_list->header();
302
    header->setSectionResizeMode(0, QHeaderView::Fixed);
303
    header->resizeSection(0, 30);
304

Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
305
    // Find path for Kdenlive renderer
306
    m_renderer = QCoreApplication::applicationDirPath() + QStringLiteral("/kdenlive_render");
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
307
    if (!QFile::exists(m_renderer)) {
308
        m_renderer = QStandardPaths::findExecutable(QStringLiteral("kdenlive_render"));
Laurent Montel's avatar
Laurent Montel committed
309
        if (m_renderer.isEmpty())
310
            m_renderer = QStringLiteral("kdenlive_render");
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
311 312
    }

313
    QDBusConnectionInterface* interface = QDBusConnection::sessionBus().interface();
314
    if (!interface || (!interface->isServiceRegistered(QStringLiteral("org.kde.ksmserver")) && !interface->isServiceRegistered(QStringLiteral("org.gnome.SessionManager"))))
315 316
        m_view.shutdown->setEnabled(false);

317
    focusFirstVisibleItem();
318
    adjustSize();
319 320 321 322 323 324
}

QSize RenderWidget::sizeHint() const
{
    // Make sure the widget has minimum size on opening
    return QSize(200, 200);
325 326
}

327 328 329 330 331 332 333 334
RenderWidget::~RenderWidget()
{
    m_view.running_jobs->blockSignals(true);
    m_view.scripts_list->blockSignals(true);
    m_view.running_jobs->clear();
    m_view.scripts_list->clear();
    delete m_jobsDelegate;
    delete m_scriptsDelegate;
335
    delete m_infoMessage;
336 337
}

338 339
void RenderWidget::slotEditItem(QListWidgetItem *item)
{
Laurent Montel's avatar
Laurent Montel committed
340 341 342
    const QString edit = item->data(EditableRole).toString();
    if (edit.isEmpty() || !edit.endsWith(QLatin1String("customprofiles.xml")))
        slotSaveProfile();
343 344 345
    else slotEditProfile();
}

346 347
void RenderWidget::showInfoPanel()
{
348 349 350 351 352 353 354 355 356
    if (m_view.advanced_params->isVisible()) {
        m_view.advanced_params->setVisible(false);
        m_view.buttonInfo->setDown(false);
        KdenliveSettings::setShowrenderparams(false);
    } else {
        m_view.advanced_params->setVisible(true);
        m_view.buttonInfo->setDown(true);
        KdenliveSettings::setShowrenderparams(true);
    }
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
357 358
}

359
void RenderWidget::setDocumentPath(const QString &path)
360
{
361
    if (m_view.out_file->url().adjusted(QUrl::RemoveFilename).path() == QUrl::fromLocalFile(m_projectFolder).adjusted(QUrl::RemoveFilename).path()) {
362
        const QString fileName = m_view.out_file->url().fileName();
363
        m_view.out_file->setUrl(QUrl(path + fileName));
364
    }
365
    m_projectFolder = path;
366
    parseScriptFiles();
367

368 369
}

370 371
void RenderWidget::slotUpdateGuideBox()
{
372 373 374
    m_view.guides_box->setVisible(m_view.render_guide->isChecked());
}

375 376
void RenderWidget::slotCheckStartGuidePosition()
{
377 378 379 380
    if (m_view.guide_start->currentIndex() > m_view.guide_end->currentIndex())
        m_view.guide_start->setCurrentIndex(m_view.guide_end->currentIndex());
}

381 382
void RenderWidget::slotCheckEndGuidePosition()
{
383 384 385 386
    if (m_view.guide_end->currentIndex() < m_view.guide_start->currentIndex())
        m_view.guide_end->setCurrentIndex(m_view.guide_start->currentIndex());
}

387
void RenderWidget::setGuides(QMap <double, QString> guidesData, double duration)
388
{
389 390
    m_view.guide_start->clear();
    m_view.guide_end->clear();
391
    if (!guidesData.isEmpty()) {
392
        m_view.guide_start->addItem(i18n("Beginning"), "0");
393
        m_view.render_guide->setEnabled(true);
394 395 396 397 398
        m_view.create_chapter->setEnabled(true);
    } else {
        m_view.render_guide->setEnabled(false);
        m_view.create_chapter->setEnabled(false);
    }
399
    double fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
400 401 402 403 404 405 406
    QMapIterator<double, QString> i(guidesData);
    while (i.hasNext()) {
        i.next();
        GenTime pos = GenTime(i.key());
        const QString guidePos = Timecode::getStringTimecode(pos.frames(fps), fps);
        m_view.guide_start->addItem(i.value() + '/' + guidePos, i.key());
        m_view.guide_end->addItem(i.value() + '/' + guidePos, i.key());
407
    }
408
    if (!guidesData.isEmpty())
409 410 411
        m_view.guide_end->addItem(i18n("End"), QString::number(duration));
}

412
/**
Simon Eugster's avatar
Simon Eugster committed
413 414 415
 * Will be called when the user selects an output file via the file dialog.
 * File extension will be added automatically.
 */
416
void RenderWidget::slotUpdateButtons(const QUrl &url)
417
{
418 419 420 421
    if (m_view.out_file->url().isEmpty()) {
        m_view.buttonGenerateScript->setEnabled(false);
        m_view.buttonRender->setEnabled(false);
    } else {
422 423
        updateButtons(); // This also checks whether the selected format is available
    }
424
    if (url.isValid()) {
425
        QListWidgetItem *item = m_view.size_list->currentItem();
426
        if (!item) {
427 428
            m_view.buttonRender->setEnabled(false);
            m_view.buttonGenerateScript->setEnabled(false);
429 430
            return;
        }
Laurent Montel's avatar
Laurent Montel committed
431 432
        const QString extension = item->data(ExtensionRole).toString();
        m_view.out_file->setUrl(filenameWithExtension(url, extension));
433 434 435
    }
}

Simon Eugster's avatar
Simon Eugster committed
436 437 438 439
/**
 * Will be called when the user changes the output file path in the text line.
 * File extension must NOT be added, would make editing impossible!
 */
440 441
void RenderWidget::slotUpdateButtons()
{
442 443 444 445 446 447
    if (m_view.out_file->url().isEmpty()) {
        m_view.buttonRender->setEnabled(false);
        m_view.buttonGenerateScript->setEnabled(false);
    } else {
        updateButtons(); // This also checks whether the selected format is available
    }
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
448 449
}

450 451
void RenderWidget::slotSaveProfile()
{
452
    Ui::SaveProfile_UI ui;
453
    QPointer<QDialog> d = new QDialog(this);
454
    ui.setupUi(d);
455

456
    for (int i = 0; i < m_view.destination_list->count(); ++i)
457
        ui.destination_list->addItem(m_view.destination_list->itemIcon(i), m_view.destination_list->itemText(i), m_view.destination_list->itemData(i, Qt::UserRole));
458 459

    ui.destination_list->setCurrentIndex(m_view.destination_list->currentIndex());
460
    QString dest = ui.destination_list->itemData(ui.destination_list->currentIndex(), Qt::UserRole).toString();
461

462
    QString customGroup;
463
    QStringList arguments = m_view.advanced_params->toPlainText().split(' ', QString::SkipEmptyParts);
464
    if (!arguments.isEmpty()) {
465
        ui.parameters->setText(arguments.join(QStringLiteral(" ")));
466
    }
467
    ui.profile_name->setFocus();
468
    QListWidgetItem *item = m_view.size_list->currentItem();
469 470
    if (item) {
        // Duplicate current item settings
471 472 473 474
        QListWidgetItem *groupItem = m_view.format_list->currentItem();
        if (groupItem) {
            customGroup = groupItem->text();
        }
475
        ui.extension->setText(item->data(ExtensionRole).toString());
476 477
        if (ui.parameters->toPlainText().contains(QStringLiteral("%bitrate")) || ui.parameters->toPlainText().contains(QStringLiteral("%quality"))) {
            if (ui.parameters->toPlainText().contains(QStringLiteral("%quality"))) {
478 479 480 481 482 483 484 485
                ui.vbitrates_label->setText(i18n("Qualities"));
                ui.default_vbitrate_label->setText(i18n("Default quality"));
            } else {
                ui.vbitrates_label->setText(i18n("Bitrates"));
                ui.default_vbitrate_label->setText(i18n("Default bitrate"));
            }
            if ( item && item->data(BitratesRole).canConvert(QVariant::StringList) && item->data(BitratesRole).toStringList().count()) {
                QStringList bitrates = item->data(BitratesRole).toStringList();
486
                ui.vbitrates_list->setText(bitrates.join(QStringLiteral(",")));
487 488 489
                if (item->data(DefaultBitrateRole).canConvert(QVariant::String))
                    ui.default_vbitrate->setValue(item->data(DefaultBitrateRole).toInt());
            }
490
        }
491
        else ui.vbitrates->setHidden(true);
492 493
        if (ui.parameters->toPlainText().contains(QStringLiteral("%audiobitrate")) || ui.parameters->toPlainText().contains(QStringLiteral("%audioquality"))) {
            if (ui.parameters->toPlainText().contains(QStringLiteral("%audioquality"))) {
494 495 496 497 498 499 500 501
                ui.abitrates_label->setText(i18n("Qualities"));
                ui.default_abitrate_label->setText(i18n("Default quality"));
            } else {
                ui.abitrates_label->setText(i18n("Bitrates"));
                ui.default_abitrate_label->setText(i18n("Default bitrate"));
            }
            if ( item && item->data(AudioBitratesRole).canConvert(QVariant::StringList) && item->data(AudioBitratesRole).toStringList().count()) {
                QStringList bitrates = item->data(AudioBitratesRole).toStringList();
502
                ui.abitrates_list->setText(bitrates.join(QStringLiteral(",")));
503 504 505
                if (item->data(DefaultAudioBitrateRole).canConvert(QVariant::String))
                    ui.default_abitrate->setValue(item->data(DefaultAudioBitrateRole).toInt());
            }
506
        }
507
        else ui.abitrates->setHidden(true);
508
    }
509 510
    if (customGroup.isEmpty()) customGroup = i18nc("Group Name", "Custom");
    ui.group_name->setText(customGroup);
511

512
    if (d->exec() == QDialog::Accepted && !ui.profile_name->text().simplified().isEmpty()) {
513 514
        QString newProfileName = ui.profile_name->text().simplified();
        QString newGroupName = ui.group_name->text().simplified();
Yuri Chornoivan's avatar
Yuri Chornoivan committed
515
        if (newGroupName.isEmpty()) newGroupName = i18nc("Group Name", "Custom");
516
        QString newMetaGroupId = ui.destination_list->itemData(ui.destination_list->currentIndex(), Qt::UserRole).toString();
517 518

        QDomDocument doc;
519 520 521 522 523
        QDomElement profileElement = doc.createElement(QStringLiteral("profile"));
        profileElement.setAttribute(QStringLiteral("name"), newProfileName);
        profileElement.setAttribute(QStringLiteral("category"), newGroupName);
        profileElement.setAttribute(QStringLiteral("destinationid"), newMetaGroupId);
        profileElement.setAttribute(QStringLiteral("extension"), ui.extension->text().simplified());
524
        QString args = ui.parameters->toPlainText().simplified();
525 526
        profileElement.setAttribute(QStringLiteral("args"), args);
        if (args.contains(QStringLiteral("%bitrate"))) {
527
            // profile has a variable bitrate
528 529 530 531 532
            profileElement.setAttribute(QStringLiteral("defaultbitrate"), QString::number(ui.default_vbitrate->value()));
            profileElement.setAttribute(QStringLiteral("bitrates"), ui.vbitrates_list->text());
        } else if (args.contains(QStringLiteral("%quality"))) {
            profileElement.setAttribute(QStringLiteral("defaultquality"), QString::number(ui.default_vbitrate->value()));
            profileElement.setAttribute(QStringLiteral("qualities"), ui.vbitrates_list->text());
533
        }
534

535
        if (args.contains(QStringLiteral("%audiobitrate"))) {
536
            // profile has a variable bitrate
537 538 539
            profileElement.setAttribute(QStringLiteral("defaultaudiobitrate"), QString::number(ui.default_abitrate->value()));
            profileElement.setAttribute(QStringLiteral("audiobitrates"), ui.abitrates_list->text());
        } else if (args.contains(QStringLiteral("%audioquality"))) {
540
            // profile has a variable bitrate
541 542
            profileElement.setAttribute(QStringLiteral("defaultaudioquality"), QString::number(ui.default_abitrate->value()));
            profileElement.setAttribute(QStringLiteral("audioqualities"), ui.abitrates_list->text());
543
        }
544 545 546
        doc.appendChild(profileElement);
        saveProfile(doc.documentElement());

547 548 549 550 551 552
        parseProfiles(newMetaGroupId, newGroupName, newProfileName);
    }
    delete d;
}


553
void RenderWidget::saveProfile(const QDomElement &newprofile)
554
{
555 556
    QDir dir(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/export/");
    if (!dir.exists()) {
557
        dir.mkpath(QStringLiteral("."));
558
    }
559
    QString exportFile = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/export/customprofiles.xml";
560
    QDomDocument doc;
561
    QFile file(dir.absoluteFilePath(QStringLiteral("customprofiles.xml")));
562 563 564 565
    doc.setContent(&file, false);
    file.close();
    QDomElement documentElement;
    QDomElement profiles = doc.documentElement();
566
    if (profiles.isNull() || profiles.tagName() != QLatin1String("profiles")) {
567
        doc.clear();
568 569
        profiles = doc.createElement(QStringLiteral("profiles"));
        profiles.setAttribute(QStringLiteral("version"), 1);
570 571
        doc.appendChild(profiles);
    }
572
    int version = profiles.attribute(QStringLiteral("version"), 0).toInt();
573
    if (version < 1) {
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
574
        //qDebug() << "// OLD profile version";
575
        doc.clear();
576 577
        profiles = doc.createElement(QStringLiteral("profiles"));
        profiles.setAttribute(QStringLiteral("version"), 1);
578 579
        doc.appendChild(profiles);
    }
580

581

582
    QDomNodeList profilelist = doc.elementsByTagName(QStringLiteral("profile"));
583 584 585 586
    int i = 0;
    while (!profilelist.item(i).isNull()) {
        // make sure a profile with same name doesn't exist
        documentElement = profilelist.item(i).toElement();
587 588
        QString profileName = documentElement.attribute(QStringLiteral("name"));
        if (profileName == newprofile.attribute(QStringLiteral("name"))) {
589 590
            // a profile with that same name already exists
            bool ok;
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
591
            QString 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, profileName, &ok);
592 593 594 595
            if (!ok) return;
            if (profileName == newProfileName) {
                profiles.removeChild(profilelist.item(i));
                break;
596 597
            }
        }
598
        ++i;
599
    }
600

601
    profiles.appendChild(newprofile);
602

603
    //QCString save = doc.toString().utf8();
604

605
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
606
        KMessageBox::sorry(this, i18n("Unable to write to file %1", dir.absoluteFilePath("customprofiles.xml")));
607 608 609 610 611
        return;
    }
    QTextStream out(&file);
    out << doc.toString();
    if (file.error() != QFile::NoError) {
612
        KMessageBox::error(this, i18n("Cannot write to file %1", dir.absoluteFilePath("customprofiles.xml")));
613
        file.close();
614 615 616
        return;
    }
    file.close();
617 618 619 620 621
}

void RenderWidget::slotCopyToFavorites()
{
    QListWidgetItem *item = m_view.size_list->currentItem();
Laurent Montel's avatar
Laurent Montel committed
622 623
    if (!item)
        return;
624 625 626 627 628 629
    QString currentGroup = m_view.format_list->currentItem()->text();

    QString params = item->data(ParamsRole).toString();
    QString extension = item->data(ExtensionRole).toString();
    QString currentProfile = item->text();
    QDomDocument doc;
630 631 632 633 634 635 636
    QDomElement profileElement = doc.createElement(QStringLiteral("profile"));
    profileElement.setAttribute(QStringLiteral("name"), currentProfile);
    profileElement.setAttribute(QStringLiteral("category"), i18nc("Category Name", "Custom"));
    profileElement.setAttribute(QStringLiteral("destinationid"), QStringLiteral("favorites"));
    profileElement.setAttribute(QStringLiteral("extension"), extension);
    profileElement.setAttribute(QStringLiteral("args"), params);
    if (params.contains(QStringLiteral("%bitrate"))) {
637
        // profile has a variable bitrate
638 639 640 641 642
        profileElement.setAttribute(QStringLiteral("defaultbitrate"), item->data(DefaultBitrateRole).toString());
        profileElement.setAttribute(QStringLiteral("bitrates"), item->data(BitratesRole).toStringList().join(QStringLiteral(",")));
    } else if (params.contains(QStringLiteral("%quality"))) {
        profileElement.setAttribute(QStringLiteral("defaultquality"), item->data(DefaultBitrateRole).toString());
        profileElement.setAttribute(QStringLiteral("qualities"), item->data(BitratesRole).toStringList().join(QStringLiteral(",")));
643
    }
644
    if (params.contains(QStringLiteral("%audiobitrate"))) {
645
        // profile has a variable bitrate
646 647 648
        profileElement.setAttribute(QStringLiteral("defaultaudiobitrate"), item->data(DefaultAudioBitrateRole).toString());
        profileElement.setAttribute(QStringLiteral("audiobitrates"), item->data(AudioBitratesRole).toStringList().join(QStringLiteral(",")));
    } else if (params.contains(QStringLiteral("%audioquality"))) {
649
        // profile has a variable bitrate
650 651
        profileElement.setAttribute(QStringLiteral("defaultaudioquality"), item->data(DefaultAudioBitrateRole).toString());
        profileElement.setAttribute(QStringLiteral("audioqualities"), item->data(AudioBitratesRole).toStringList().join(QStringLiteral(",")));
652
    }
653 654 655
    doc.appendChild(profileElement);
    saveProfile(doc.documentElement());
    parseProfiles(m_view.destination_list->itemData(m_view.destination_list->currentIndex(), Qt::UserRole).toString(), currentGroup, currentProfile);
656 657
}

658 659
void RenderWidget::slotEditProfile()
{
660 661 662 663 664 665 666 667 668
    QListWidgetItem *item = m_view.size_list->currentItem();
    if (!item) return;
    QString currentGroup = m_view.format_list->currentItem()->text();

    QString params = item->data(ParamsRole).toString();
    QString extension = item->data(ExtensionRole).toString();
    QString currentProfile = item->text();

    Ui::SaveProfile_UI ui;
669
    QPointer<QDialog> d = new QDialog(this);
670
    ui.setupUi(d);
671

672
    for (int i = 0; i < m_view.destination_list->count(); ++i)
673 674 675 676 677 678
        ui.destination_list->addItem(m_view.destination_list->itemIcon(i), m_view.destination_list->itemText(i), m_view.destination_list->itemData(i, Qt::UserRole));

    ui.destination_list->setCurrentIndex(m_view.destination_list->currentIndex());
    QString dest = ui.destination_list->itemData(ui.destination_list->currentIndex(), Qt::UserRole).toString();

    QString customGroup = m_view.format_list->currentItem()->text();
Yuri Chornoivan's avatar
Yuri Chornoivan committed
679
    if (customGroup.isEmpty()) customGroup = i18nc("Group Name", "Custom");
680 681
    ui.group_name->setText(customGroup);

682 683 684 685
    ui.profile_name->setText(currentProfile);
    ui.extension->setText(extension);
    ui.parameters->setText(params);
    ui.profile_name->setFocus();
686 687
    if (ui.parameters->toPlainText().contains(QStringLiteral("%bitrate")) || ui.parameters->toPlainText().contains(QStringLiteral("%quality"))) {
        if (ui.parameters->toPlainText().contains(QStringLiteral("%quality"))) {
688 689 690 691 692 693
            ui.vbitrates_label->setText(i18n("Qualities"));
            ui.default_vbitrate_label->setText(i18n("Default quality"));
        } else {
            ui.vbitrates_label->setText(i18n("Bitrates"));
            ui.default_vbitrate_label->setText(i18n("Default bitrate"));
        }
694 695
        if ( item->data(BitratesRole).canConvert(QVariant::StringList) && item->data(BitratesRole).toStringList().count()) {
            QStringList bitrates = item->data(BitratesRole).toStringList();
696
            ui.vbitrates_list->setText(bitrates.join(QStringLiteral(",")));
697 698 699
            if (item->data(DefaultBitrateRole).canConvert(QVariant::String))
                ui.default_vbitrate->setValue(item->data(DefaultBitrateRole).toInt());
        }
Laurent Montel's avatar
Laurent Montel committed
700 701
    } else {
        ui.vbitrates->setHidden(true);
702
    }
Laurent Montel's avatar
Laurent Montel committed
703

704 705
    if (ui.parameters->toPlainText().contains(QStringLiteral("%audiobitrate")) || ui.parameters->toPlainText().contains(QStringLiteral("%audioquality"))) {
        if (ui.parameters->toPlainText().contains(QStringLiteral("%audioquality"))) {
706 707 708 709 710 711 712
            ui.abitrates_label->setText(i18n("Qualities"));
            ui.default_abitrate_label->setText(i18n("Default quality"));
        } else {
            ui.abitrates_label->setText(i18n("Bitrates"));
            ui.default_abitrate_label->setText(i18n("Default bitrate"));
        }
        if ( item->data(AudioBitratesRole).canConvert(QVariant::StringList) && item->data(AudioBitratesRole).toStringList().count()) {
713
            QStringList bitrates = item->data(AudioBitratesRole).toStringList();
714
            ui.abitrates_list->setText(bitrates.join(QStringLiteral(",")));
715 716 717 718 719
            if (item->data(DefaultAudioBitrateRole).canConvert(QVariant::String))
                ui.default_abitrate->setValue(item->data(DefaultAudioBitrateRole).toInt());
        }
    }
    else ui.abitrates->setHidden(true);
720
    d->setWindowTitle(i18n("Edit Profile"));
721
    if (d->exec() == QDialog::Accepted) {
722
        slotDeleteProfile(false);
723
        QString exportFile = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/export/customprofiles.xml";
724 725 726 727 728
        QDomDocument doc;
        QFile file(exportFile);
        doc.setContent(&file, false);
        file.close();
        QDomElement documentElement;
729 730
        QDomElement profiles = doc.documentElement();

731
        if (profiles.isNull() || profiles.tagName() != QLatin1String("profiles")) {
732
            doc.clear();
733 734
            profiles = doc.createElement(QStringLiteral("profiles"));
            profiles.setAttribute(QStringLiteral("version"), 1);
735 736 737
            doc.appendChild(profiles);
        }

738
        int version = profiles.attribute(QStringLiteral("version"), 0).toInt();
739
        if (version < 1) {
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
740
            //qDebug() << "// OLD profile version";
741
            doc.clear();
742 743
            profiles = doc.createElement(QStringLiteral("profiles"));
            profiles.setAttribute(QStringLiteral("version"), 1);
744
            doc.appendChild(profiles);
745 746 747 748
        }

        QString newProfileName = ui.profile_name->text().simplified();
        QString newGroupName = ui.group_name->text().simplified();
Yuri Chornoivan's avatar
Yuri Chornoivan committed
749
        if (newGroupName.isEmpty()) newGroupName = i18nc("Group Name", "Custom");
750
        QString newMetaGroupId = ui.destination_list->itemData(ui.destination_list->currentIndex(), Qt::UserRole).toString();
751
        QDomNodeList profilelist = doc.elementsByTagName(QStringLiteral("profile"));
752 753 754 755
        int i = 0;
        while (!profilelist.item(i).isNull()) {
            // make sure a profile with same name doesn't exist
            documentElement = profilelist.item(i).toElement();
756
            QString profileName = documentElement.attribute(QStringLiteral("name"));
757 758 759
            if (profileName == newProfileName) {
                // a profile with that same name already exists
                bool ok;
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
760
                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);
761 762 763
                if (!ok) return;
                if (profileName == newProfileName) {
                    profiles.removeChild(profilelist.item(i));
764 765 766
                    break;
                }
            }
767
            ++i;
768
        }
769

770 771 772 773 774
        QDomElement profileElement = doc.createElement(QStringLiteral("profile"));
        profileElement.setAttribute(QStringLiteral("name"), newProfileName);
        profileElement.setAttribute(QStringLiteral("category"), newGroupName);
        profileElement.setAttribute(QStringLiteral("destinationid"), newMetaGroupId);
        profileElement.setAttribute(QStringLiteral("extension"), ui.extension->text().simplified());
775
        QString args = ui.parameters->toPlainText().simplified();
776 777
        profileElement.setAttribute(QStringLiteral("args"), args);
        if (args.contains(QStringLiteral("%bitrate"))) {
778
            // profile has a variable bitrate
779 780 781 782 783
            profileElement.setAttribute(QStringLiteral("defaultbitrate"), QString::number(ui.default_vbitrate->value()));
            profileElement.setAttribute(QStringLiteral("bitrates"), ui.vbitrates_list->text());
        } else if(args.contains(QStringLiteral("%quality"))) {
            profileElement.setAttribute(QStringLiteral("defaultquality"), QString::number(ui.default_vbitrate->value()));
            profileElement.setAttribute(QStringLiteral("qualities"), ui.vbitrates_list->text());
784
        }
785
        if (args.contains(QStringLiteral("%audiobitrate"))) {
786
            // profile has a variable bitrate
787 788 789 790 791
            profileElement.setAttribute(QStringLiteral("defaultaudiobitrate"), QString::number(ui.default_abitrate->value()));
            profileElement.setAttribute(QStringLiteral("audiobitrates"), ui.abitrates_list->text());
        } else if (args.contains(QStringLiteral("%audioquality"))) {
            profileElement.setAttribute(QStringLiteral("defaultaudioquality"), QString::number(ui.default_abitrate->value()));
            profileElement.setAttribute(QStringLiteral("audioqualities"), ui.abitrates_list->text());
792 793
        }

794
        profiles.appendChild(profileElement);
795 796

        //QCString save = doc.toString().utf8();
797
        delete d;
798
        if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
799
            KMessageBox::error(this, i18n("Cannot write to file %1", exportFile));
800 801 802 803
            return;
        }
        QTextStream out(&file);
        out << doc.toString();
804 805 806 807 808
        if (file.error() != QFile::NoError) {
            KMessageBox::error(this, i18n("Cannot write to file %1", exportFile));
            file.close();
            return;
        }
809
        file.close();
810
        parseProfiles(newMetaGroupId, newGroupName, newProfileName);
811
    } else delete d;
812 813
}

814 815
void RenderWidget::slotDeleteProfile(bool refresh)
{
816 817 818
    //TODO: delete a profile installed by KNewStuff the easy way
    /*
    QString edit = m_view.size_list->currentItem()->data(EditableRole).toString();
819
    if (!edit.endsWith(QLatin1String("customprofiles.xml"))) {
820
        // This is a KNewStuff installed file, process through KNS
821 822 823 824 825 826
        KNS::Engine engine(0);
        if (engine.init("kdenlive_render.knsrc")) {
            KNS::Entry::List entries;
        }
        return;
    }*/
827 828
    QString currentGroup = m_view.format_list->currentItem()->text();
    QString currentProfile = m_view.size_list->currentItem()->text();
829
    QString metaGroupId = m_view.destination_list->itemData(m_view.destination_list->currentIndex(), Qt::UserRole).toString();
830

831
    QString exportFile = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/export/customprofiles.xml";
832 833 834 835 836 837
    QDomDocument doc;
    QFile file(exportFile);
    doc.setContent(&file, false);
    file.close();

    QDomElement documentElement;
838
    QDomNodeList profiles = doc.elementsByTagName(QStringLiteral("profile"));
839
    int i = 0;
840 841 842
    QString groupName;
    QString profileName;
    QString destination;
843

844 845
    while (!profiles.item(i).isNull()) {
        documentElement = profiles.item(i).toElement();
846 847 848
        profileName = documentElement.attribute(QStringLiteral("name"));
        groupName = documentElement.attribute(QStringLiteral("category"));
        destination = documentElement.attribute(QStringLiteral("destinationid"));
849 850

        if (profileName == currentProfile && groupName == currentGroup && destination == metaGroupId) {
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
851
            //qDebug() << "// GOT it: " << profileName;
852
            doc.documentElement().removeChild(profiles.item(i));
853 854
            break;
        }
855
        ++i;
856 857 858 859 860 861 862 863
    }

    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        KMessageBox::sorry(this, i18n("Unable to write to file %1", exportFile));
        return;
    }
    QTextStream out(&file);
    out << doc.toString();
864 865 866 867 868
    if (file.error() != QFile::NoError) {
        KMessageBox::error(this, i18n("Cannot write to file %1", exportFile));
        file.close();
        return;
    }
869
    file.close();
870 871 872 873
    if (refresh) {
        parseProfiles(metaGroupId, currentGroup);
        focusFirstVisibleItem();
    }
874 875
}

876 877
void RenderWidget::updateButtons()
{
878 879 880 881
    if (!m_view.size_list->currentItem() || m_view.size_list->currentItem()->isHidden()) {
        m_view.buttonSave->setEnabled(false);
        m_view.buttonDelete->setEnabled(false);
        m_view.buttonEdit->setEnabled(false);
882 883
        m_view.buttonRender->setEnabled(false);
        m_view.buttonGenerateScript->setEnabled(false);
884 885
    } else {
        m_view.buttonSave->setEnabled(true);
886 887
        m_view.buttonRender->setEnabled(m_view.size_list->currentItem()->data(ErrorRole).isNull());
        m_view.buttonGenerateScript->setEnabled(m_view.size_list->currentItem()->data(ErrorRole).isNull());
888
        QString edit = m_view.size_list->currentItem()->data(EditableRole).toString();
889
        if (edit.isEmpty() || !edit.endsWith(QLatin1String("customprofiles.xml"))) {
890 891 892
            m_view.buttonDelete->setEnabled(false);
            m_view.buttonEdit->setEnabled(false);
        } else {