renderwidget.cpp 113 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 35
#include <qglobal.h>
#include <qstring.h>
36
#include <QDebug>
37 38 39 40
#include <QDomDocument>
#include <QTreeWidgetItem>
#include <QHeaderView>
#include <QInputDialog>
41
#include <QProcess>
42
#include <QDBusConnectionInterface>
43
#include <QThread>
44
#include <QScriptEngine>
45
#include <QKeyEvent>
46
#include <QTimer>
47
#include <QStandardPaths>
48
#include <QDir>
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
49

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

55 56

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

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

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


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


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

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


Laurent Montel's avatar
Laurent Montel committed
146
RenderWidget::RenderWidget(const QString &projectfolder, bool enableProxy, const MltVideoProfile &profile, QWidget * parent) :
147
        QDialog(parent),
148
        m_projectFolder(projectfolder),
149
        m_profile(profile),
150
        m_blockProcessing(false)
151
{
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
152
    m_view.setupUi(this);
153 154
    int size = style()->pixelMetric(QStyle::PM_SmallIconSize);
    QSize iconSize(size, size);
155

156
    setWindowTitle(i18n("Rendering"));
157 158 159 160
    m_view.buttonDelete->setIconSize(iconSize);
    m_view.buttonEdit->setIconSize(iconSize);
    m_view.buttonSave->setIconSize(iconSize);
    m_view.buttonFavorite->setIconSize(iconSize);
161

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-edit")));
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
    m_view.hide_log->setIcon(KoIconUtils::themedIcon(QStringLiteral("go-down")));
174

175
    m_view.buttonFavorite->setIcon(KoIconUtils::themedIcon(QStringLiteral("favorite")));
176
    m_view.buttonFavorite->setToolTip(i18n("Copy profile to favorites"));
177

178
    m_view.advanced_params->setMaximumHeight(QFontMetrics(font()).lineSpacing() * 5);
179

180 181 182 183 184 185 186 187 188 189 190 191
    m_view.optionsGroup->setVisible(m_view.options->isChecked());
    connect(m_view.options, SIGNAL(toggled(bool)), m_view.optionsGroup, SLOT(setVisible(bool)));
    m_view.videoLabel->setVisible(m_view.options->isChecked());
    connect(m_view.options, SIGNAL(toggled(bool)), m_view.videoLabel, SLOT(setVisible(bool)));
    m_view.video->setVisible(m_view.options->isChecked());
    connect(m_view.options, SIGNAL(toggled(bool)), m_view.video, SLOT(setVisible(bool)));
    m_view.audioLabel->setVisible(m_view.options->isChecked());
    connect(m_view.options, SIGNAL(toggled(bool)), m_view.audioLabel, SLOT(setVisible(bool)));
    m_view.audio->setVisible(m_view.options->isChecked());
    connect(m_view.options, SIGNAL(toggled(bool)), m_view.audio, SLOT(setVisible(bool)));
    connect(m_view.quality, SIGNAL(valueChanged(int)), this, SLOT(adjustAVQualities(int)));
    connect(m_view.video, SIGNAL(valueChanged(int)), this, SLOT(adjustQuality(int)));
192
    connect(m_view.speed, SIGNAL(valueChanged(int)), this, SLOT(adjustSpeed(int)));
193

194 195
    m_view.buttonRender->setEnabled(false);
    m_view.buttonGenerateScript->setEnabled(false);
196
    setRescaleEnabled(false);
197 198 199 200 201 202 203
    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);
204
    m_view.proxy_render->setHidden(!enableProxy);
205

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

    m_infoMessage = new KMessageWidget;
214
    m_view.info->addWidget(m_infoMessage);
215 216 217
    m_infoMessage->setCloseButtonVisible(false);
    m_infoMessage->hide();

218 219 220 221
    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)));

222 223 224
    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)));
225
    m_view.rescale_keep->setIcon(KoIconUtils::themedIcon(QStringLiteral("edit-link")));
226 227
    m_view.rescale_keep->setToolTip(i18n("Preserve aspect ratio"));
    connect(m_view.rescale_keep, SIGNAL(clicked()), this, SLOT(slotSwitchAspectRatio()));
228

229 230 231
    connect(m_view.buttonRender, SIGNAL(clicked()), this, SLOT(slotPrepareExport()));
    connect(m_view.buttonGenerateScript, SIGNAL(clicked()), this, SLOT(slotGenerateScript()));

232 233 234 235
    m_view.abort_job->setEnabled(false);
    m_view.start_script->setEnabled(false);
    m_view.delete_script->setEnabled(false);

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
    connect(m_view.buttonSave, SIGNAL(clicked()), this, SLOT(slotSaveProfile()));
250
    connect(m_view.buttonEdit, SIGNAL(clicked()), this, SLOT(slotEditProfile()));
251
    connect(m_view.buttonDelete, SIGNAL(clicked()), this, SLOT(slotDeleteProfile()));
252 253
    connect(m_view.buttonFavorite, SIGNAL(clicked()), this, SLOT(slotCopyToFavorites()));

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

259 260
    connect(m_view.buttonClose, SIGNAL(clicked()), this, SLOT(hide()));
    connect(m_view.buttonClose2, SIGNAL(clicked()), this, SLOT(hide()));
261
    connect(m_view.buttonClose3, SIGNAL(clicked()), this, SLOT(hide()));
262
    connect(m_view.rescale, SIGNAL(toggled(bool)), this, SLOT(setRescaleEnabled(bool)));
Laurent Montel's avatar
Laurent Montel committed
263
    connect(m_view.out_file, SIGNAL(textChanged(QString)), this, SLOT(slotUpdateButtons()));
264
    connect(m_view.out_file, SIGNAL(urlSelected(QUrl)), this, SLOT(slotUpdateButtons(QUrl)));
265

266 267
    connect(m_view.formats, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)), this, SLOT(refreshParams()));
    connect(m_view.formats, SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)), this, SLOT(slotEditItem(QTreeWidgetItem*)));
268

269 270 271 272 273 274 275
    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()));

276
    connect(m_view.tc_overlay, SIGNAL(toggled(bool)), m_view.tc_type, SLOT(setEnabled(bool)));
277

278 279
    //m_view.splitter->setStretchFactor(1, 5);
    //m_view.splitter->setStretchFactor(0, 2);
280

281
    m_view.out_file->setMode(KFile::File);
282
    m_view.out_file->setFocusPolicy(Qt::ClickFocus);
283

284
    m_view.running_jobs->setHeaderLabels(QStringList() << QString() << i18n("File"));
285 286
    m_jobsDelegate = new RenderViewDelegate(this);
    m_view.running_jobs->setItemDelegate(m_jobsDelegate);
287

288
    QHeaderView *header = m_view.running_jobs->header();
289
    header->setSectionResizeMode(0, QHeaderView::Fixed);
290
    header->resizeSection(0, 30);
291
    header->setSectionResizeMode(1, QHeaderView::Interactive);
292

293
    m_view.scripts_list->setHeaderLabels(QStringList() << QString() << i18n("Script Files"));
294 295
    m_scriptsDelegate = new RenderViewDelegate(this);
    m_view.scripts_list->setItemDelegate(m_scriptsDelegate);
296
    header = m_view.scripts_list->header();
297
    header->setSectionResizeMode(0, QHeaderView::Fixed);
298
    header->resizeSection(0, 30);
299

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

308
    QDBusConnectionInterface* interface = QDBusConnection::sessionBus().interface();
309
    if (!interface || (!interface->isServiceRegistered(QStringLiteral("org.kde.ksmserver")) && !interface->isServiceRegistered(QStringLiteral("org.gnome.SessionManager"))))
310 311
        m_view.shutdown->setEnabled(false);

312
    focusFirstVisibleItem();
313
    adjustSize();
314 315 316 317 318 319
}

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

322 323 324 325 326 327 328 329
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;
330
    delete m_infoMessage;
331 332
}

333
void RenderWidget::slotEditItem(QTreeWidgetItem *item)
334
{
335 336 337 338
    if (item->parent() == NULL) {
        // This is a top level item - group - don't edit
        return;
    }
339
    const QString edit = item->data(0, EditableRole).toString();
Laurent Montel's avatar
Laurent Montel committed
340 341
    if (edit.isEmpty() || !edit.endsWith(QLatin1String("customprofiles.xml")))
        slotSaveProfile();
342 343 344
    else slotEditProfile();
}

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

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

365 366
}

367 368
void RenderWidget::slotUpdateGuideBox()
{
369 370 371
    m_view.guides_box->setVisible(m_view.render_guide->isChecked());
}

372 373
void RenderWidget::slotCheckStartGuidePosition()
{
374 375 376 377
    if (m_view.guide_start->currentIndex() > m_view.guide_end->currentIndex())
        m_view.guide_start->setCurrentIndex(m_view.guide_end->currentIndex());
}

378 379
void RenderWidget::slotCheckEndGuidePosition()
{
380 381 382 383
    if (m_view.guide_end->currentIndex() < m_view.guide_start->currentIndex())
        m_view.guide_end->setCurrentIndex(m_view.guide_start->currentIndex());
}

384
void RenderWidget::setGuides(QMap <double, QString> guidesData, double duration)
385
{
386 387
    m_view.guide_start->clear();
    m_view.guide_end->clear();
388
    if (!guidesData.isEmpty()) {
389
        m_view.guide_start->addItem(i18n("Beginning"), "0");
390
        m_view.render_guide->setEnabled(true);
391 392 393 394 395
        m_view.create_chapter->setEnabled(true);
    } else {
        m_view.render_guide->setEnabled(false);
        m_view.create_chapter->setEnabled(false);
    }
396
    double fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
397 398 399 400 401 402 403
    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());
404
    }
405
    if (!guidesData.isEmpty())
406 407 408
        m_view.guide_end->addItem(i18n("End"), QString::number(duration));
}

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

Simon Eugster's avatar
Simon Eugster committed
433 434 435 436
/**
 * 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!
 */
437 438
void RenderWidget::slotUpdateButtons()
{
439 440 441 442 443 444
    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
445 446
}

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

453
    QString customGroup;
454
    QStringList arguments = m_view.advanced_params->toPlainText().split(' ', QString::SkipEmptyParts);
455
    if (!arguments.isEmpty()) {
456
        ui.parameters->setText(arguments.join(QStringLiteral(" ")));
457
    }
458
    ui.profile_name->setFocus();
459 460
    QTreeWidgetItem *item = m_view.formats->currentItem();
    if (item && item->parent()) { //not a category
461
        // Duplicate current item settings
462 463
        customGroup = item->parent()->text(0);
        ui.extension->setText(item->data(0, ExtensionRole).toString());
464 465
        if (ui.parameters->toPlainText().contains(QStringLiteral("%bitrate")) || ui.parameters->toPlainText().contains(QStringLiteral("%quality"))) {
            if (ui.parameters->toPlainText().contains(QStringLiteral("%quality"))) {
466 467 468 469 470 471
                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"));
            }
472 473
            if (item->data(0, BitratesRole).canConvert(QVariant::StringList) && item->data(0, BitratesRole).toStringList().count()) {
                QStringList bitrates = item->data(0, BitratesRole).toStringList();
474
                ui.vbitrates_list->setText(bitrates.join(QStringLiteral(",")));
475 476
                if (item->data(0, DefaultBitrateRole).canConvert(QVariant::String))
                    ui.default_vbitrate->setValue(item->data(0, DefaultBitrateRole).toInt());
477
            }
478
        }
479
        else ui.vbitrates->setHidden(true);
480 481
        if (ui.parameters->toPlainText().contains(QStringLiteral("%audiobitrate")) || ui.parameters->toPlainText().contains(QStringLiteral("%audioquality"))) {
            if (ui.parameters->toPlainText().contains(QStringLiteral("%audioquality"))) {
482 483 484 485 486 487
                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"));
            }
488 489
            if ( item && item->data(0, AudioBitratesRole).canConvert(QVariant::StringList) && item->data(0, AudioBitratesRole).toStringList().count()) {
                QStringList bitrates = item->data(0, AudioBitratesRole).toStringList();
490
                ui.abitrates_list->setText(bitrates.join(QStringLiteral(",")));
491 492
                if (item->data(0, DefaultAudioBitrateRole).canConvert(QVariant::String))
                    ui.default_abitrate->setValue(item->data(0, DefaultAudioBitrateRole).toInt());
493
            }
494
        }
495
        else ui.abitrates->setHidden(true);
496 497 498 499 500

        if (item->data(0, SpeedsRole).canConvert(QVariant::StringList) && item->data(0, SpeedsRole).toStringList().count()) {
            QStringList speeds = item->data(0, SpeedsRole).toStringList();
            ui.speeds_list->setText(speeds.join('\n'));
        }
501
    }
502

503 504
    if (customGroup.isEmpty()) customGroup = i18nc("Group Name", "Custom");
    ui.group_name->setText(customGroup);
505

506
    if (d->exec() == QDialog::Accepted && !ui.profile_name->text().simplified().isEmpty()) {
507 508
        QString newProfileName = ui.profile_name->text().simplified();
        QString newGroupName = ui.group_name->text().simplified();
Yuri Chornoivan's avatar
Yuri Chornoivan committed
509
        if (newGroupName.isEmpty()) newGroupName = i18nc("Group Name", "Custom");
510 511

        QDomDocument doc;
512 513 514 515
        QDomElement profileElement = doc.createElement(QStringLiteral("profile"));
        profileElement.setAttribute(QStringLiteral("name"), newProfileName);
        profileElement.setAttribute(QStringLiteral("category"), newGroupName);
        profileElement.setAttribute(QStringLiteral("extension"), ui.extension->text().simplified());
516
        QString args = ui.parameters->toPlainText().simplified();
517 518
        profileElement.setAttribute(QStringLiteral("args"), args);
        if (args.contains(QStringLiteral("%bitrate"))) {
519
            // profile has a variable bitrate
520 521 522 523 524
            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());
525
        }
526

527
        if (args.contains(QStringLiteral("%audiobitrate"))) {
528
            // profile has a variable bitrate
529 530 531
            profileElement.setAttribute(QStringLiteral("defaultaudiobitrate"), QString::number(ui.default_abitrate->value()));
            profileElement.setAttribute(QStringLiteral("audiobitrates"), ui.abitrates_list->text());
        } else if (args.contains(QStringLiteral("%audioquality"))) {
532
            // profile has a variable bitrate
533 534
            profileElement.setAttribute(QStringLiteral("defaultaudioquality"), QString::number(ui.default_abitrate->value()));
            profileElement.setAttribute(QStringLiteral("audioqualities"), ui.abitrates_list->text());
535
        }
536
        if (!ui.speeds_list->toPlainText().isEmpty()) {
537 538
            profileElement.setAttribute(QStringLiteral("speeds"), ui.speeds_list->toPlainText().replace('\n', ';').simplified());
        }
539

540 541 542
        doc.appendChild(profileElement);
        saveProfile(doc.documentElement());

543
        parseProfiles();
544 545 546 547 548
    }
    delete d;
}


549
bool RenderWidget::saveProfile(QDomElement newprofile)
550
{
551 552
    QDir dir(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/export/");
    if (!dir.exists()) {
553
        dir.mkpath(QStringLiteral("."));
554
    }
555
    QString exportFile = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/export/customprofiles.xml";
556
    QDomDocument doc;
557
    QFile file(dir.absoluteFilePath(QStringLiteral("customprofiles.xml")));
558 559 560 561
    doc.setContent(&file, false);
    file.close();
    QDomElement documentElement;
    QDomElement profiles = doc.documentElement();
562
    if (profiles.isNull() || profiles.tagName() != QLatin1String("profiles")) {
563
        doc.clear();
564 565
        profiles = doc.createElement(QStringLiteral("profiles"));
        profiles.setAttribute(QStringLiteral("version"), 1);
566 567
        doc.appendChild(profiles);
    }
568
    int version = profiles.attribute(QStringLiteral("version"), 0).toInt();
569 570
    if (version < 1) {
        doc.clear();
571 572
        profiles = doc.createElement(QStringLiteral("profiles"));
        profiles.setAttribute(QStringLiteral("version"), 1);
573 574
        doc.appendChild(profiles);
    }
575

576

577
    QDomNodeList profilelist = doc.elementsByTagName(QStringLiteral("profile"));
578 579 580
    QString newProfileName = newprofile.attribute(QStringLiteral("name"));
    // Check existing profiles
    QStringList existingProfileNames;
581 582 583
    int i = 0;
    while (!profilelist.item(i).isNull()) {
        documentElement = profilelist.item(i).toElement();
584
        QString profileName = documentElement.attribute(QStringLiteral("name"));
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599
        existingProfileNames << profileName;
        i++;
    }
    // Check if a profile with that same name already exists
    bool ok;
    while (existingProfileNames.contains(newProfileName)) {
        QString updatedProfileName = 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);
        if (!ok) return false;
        if (updatedProfileName == newProfileName) {
            // remove previous profile
            profiles.removeChild(profilelist.item(existingProfileNames.indexOf(newProfileName)));
            break;
        } else {
            newProfileName = updatedProfileName;
            newprofile.setAttribute(QStringLiteral("name"), newProfileName);
600
        }
601
    }
602

603
    profiles.appendChild(newprofile);
604

605
    //QCString save = doc.toString().utf8();
606

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

void RenderWidget::slotCopyToFavorites()
{
624 625
    QTreeWidgetItem *item = m_view.formats->currentItem();
    if (!item || !item->parent())
Laurent Montel's avatar
Laurent Montel committed
626
        return;
627
    QString currentGroup = item->parent()->text(0);
628

629 630 631
    QString params = item->data(0, ParamsRole).toString();
    QString extension = item->data(0, ExtensionRole).toString();
    QString currentProfile = item->text(0);
632
    QDomDocument doc;
633 634 635 636 637 638 639
    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"))) {
640
        // profile has a variable bitrate
641 642
        profileElement.setAttribute(QStringLiteral("defaultbitrate"), item->data(0, DefaultBitrateRole).toString());
        profileElement.setAttribute(QStringLiteral("bitrates"), item->data(0, BitratesRole).toStringList().join(QStringLiteral(",")));
643
    } else if (params.contains(QStringLiteral("%quality"))) {
644 645
        profileElement.setAttribute(QStringLiteral("defaultquality"), item->data(0, DefaultBitrateRole).toString());
        profileElement.setAttribute(QStringLiteral("qualities"), item->data(0, BitratesRole).toStringList().join(QStringLiteral(",")));
646
    }
647
    if (params.contains(QStringLiteral("%audiobitrate"))) {
648
        // profile has a variable bitrate
649 650
        profileElement.setAttribute(QStringLiteral("defaultaudiobitrate"), item->data(0, DefaultAudioBitrateRole).toString());
        profileElement.setAttribute(QStringLiteral("audiobitrates"), item->data(0, AudioBitratesRole).toStringList().join(QStringLiteral(",")));
651
    } else if (params.contains(QStringLiteral("%audioquality"))) {
652
        // profile has a variable bitrate
653 654 655
        profileElement.setAttribute(QStringLiteral("defaultaudioquality"), item->data(0, DefaultAudioBitrateRole).toString());
        profileElement.setAttribute(QStringLiteral("audioqualities"), item->data(0, AudioBitratesRole).toStringList().join(QStringLiteral(",")));
    }
656
    if (item->data(0, SpeedsRole).canConvert(QVariant::StringList) && item->data(0, SpeedsRole).toStringList().count()) {
657 658
        // profile has a variable speed
        profileElement.setAttribute(QStringLiteral("speeds"), item->data(0, SpeedsRole).toStringList().join(QStringLiteral(";")));
659
    }
660
    doc.appendChild(profileElement);
661
    if (saveProfile(doc.documentElement())) {
662
        parseProfiles(profileElement.attribute(QStringLiteral("name")));
663
    }
664 665
}

666 667
void RenderWidget::slotEditProfile()
{
668 669 670
    QTreeWidgetItem *item = m_view.formats->currentItem();
    if (!item || !item->parent()) return;
    QString currentGroup = item->parent()->text(0);
671

672
    QString params = item->data(0, ParamsRole).toString();
673 674

    Ui::SaveProfile_UI ui;
675
    QPointer<QDialog> d = new QDialog(this);
676
    ui.setupUi(d);
677

678
    QString customGroup = item->parent()->text(0);
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
    ui.profile_name->setText(item->text(0));
    ui.extension->setText(item->data(0, ExtensionRole).toString());
684 685
    ui.parameters->setText(params);
    ui.profile_name->setFocus();
686 687
    if (params.contains(QStringLiteral("%bitrate")) || ui.parameters->toPlainText().contains(QStringLiteral("%quality"))) {
        if (params.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(0, BitratesRole).canConvert(QVariant::StringList) && item->data(0, BitratesRole).toStringList().count()) {
            QStringList bitrates = item->data(0, BitratesRole).toStringList();
696
            ui.vbitrates_list->setText(bitrates.join(QStringLiteral(",")));
697 698
            if (item->data(0, DefaultBitrateRole).canConvert(QVariant::String))
                ui.default_vbitrate->setValue(item->data(0, DefaultBitrateRole).toInt());
699
        }
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 (params.contains(QStringLiteral("%audiobitrate")) || ui.parameters->toPlainText().contains(QStringLiteral("%audioquality"))) {
        if (params.contains(QStringLiteral("%audioquality"))) {
706 707 708 709 710 711
            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"));
        }
712 713
        if ( item->data(0, AudioBitratesRole).canConvert(QVariant::StringList) && item->data(0, AudioBitratesRole).toStringList().count()) {
            QStringList bitrates = item->data(0, AudioBitratesRole).toStringList();
714
            ui.abitrates_list->setText(bitrates.join(QStringLiteral(",")));
715 716
            if (item->data(0, DefaultAudioBitrateRole).canConvert(QVariant::String))
                ui.default_abitrate->setValue(item->data(0, DefaultAudioBitrateRole).toInt());
717 718 719
        }
    }
    else ui.abitrates->setHidden(true);
720 721 722 723 724 725

    if ( item->data(0, SpeedsRole).canConvert(QVariant::StringList) && item->data(0, SpeedsRole).toStringList().count()) {
        QStringList speeds = item->data(0, SpeedsRole).toStringList();
        ui.speeds_list->setText(speeds.join('\n'));
    }

726
    d->setWindowTitle(i18n("Edit Profile"));
727

728
    if (d->exec() == QDialog::Accepted) {
729
        slotDeleteProfile(false);
730
        QString exportFile = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/export/customprofiles.xml";
731 732 733 734 735
        QDomDocument doc;
        QFile file(exportFile);
        doc.setContent(&file, false);
        file.close();
        QDomElement documentElement;
736 737
        QDomElement profiles = doc.documentElement();

738
        if (profiles.isNull() || profiles.tagName() != QLatin1String("profiles")) {
739
            doc.clear();
740 741
            profiles = doc.createElement(QStringLiteral("profiles"));
            profiles.setAttribute(QStringLiteral("version"), 1);
742 743 744
            doc.appendChild(profiles);
        }

745
        int version = profiles.attribute(QStringLiteral("version"), 0).toInt();
746 747
        if (version < 1) {
            doc.clear();
748 749
            profiles = doc.createElement(QStringLiteral("profiles"));
            profiles.setAttribute(QStringLiteral("version"), 1);
750
            doc.appendChild(profiles);
751 752 753 754
        }

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

775 776 777 778
        QDomElement profileElement = doc.createElement(QStringLiteral("profile"));
        profileElement.setAttribute(QStringLiteral("name"), newProfileName);
        profileElement.setAttribute(QStringLiteral("category"), newGroupName);
        profileElement.setAttribute(QStringLiteral("extension"), ui.extension->text().simplified());
779
        QString args = ui.parameters->toPlainText().simplified();
780 781
        profileElement.setAttribute(QStringLiteral("args"), args);
        if (args.contains(QStringLiteral("%bitrate"))) {
782
            // profile has a variable bitrate
783 784 785 786 787
            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());
788
        }
789
        if (args.contains(QStringLiteral("%audiobitrate"))) {
790
            // profile has a variable bitrate
791 792 793 794 795
            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());
796 797
        }

798
        if (!ui.speeds_list->toPlainText().isEmpty()) {
799 800 801
            // profile has a variable speed
            profileElement.setAttribute(QStringLiteral("speeds"), ui.speeds_list->toPlainText().replace('\n', ';').simplified());
        }
802

803
        profiles.appendChild(profileElement);
804 805

        //QCString save = doc.toString().utf8();
806
        delete d;
807
        if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
808
            KMessageBox::error(this, i18n("Cannot write to file %1", exportFile));
809 810 811 812
            return;
        }
        QTextStream out(&file);
        out << doc.toString();
813 814 815 816 817
        if (file.error() != QFile::NoError) {
            KMessageBox::error(this, i18n("Cannot write to file %1", exportFile));
            file.close();
            return;
        }
818
        file.close();
819
        parseProfiles();
820
    } else delete d;
821 822
}

823 824
void RenderWidget::slotDeleteProfile(bool refresh)
{
825 826
    //TODO: delete a profile installed by KNewStuff the easy way
    /*
827
    QString edit = m_view.formats->currentItem()->data(EditableRole).toString();
828
    if (!edit.endsWith(QLatin1String("customprofiles.xml"))) {
829
        // This is a KNewStuff installed file, process through KNS
830 831 832 833 834 835
        KNS::Engine engine(0);
        if (engine.init("kdenlive_render.knsrc")) {
            KNS::Entry::List entries;
        }
        return;
    }*/
836 837 838 839
    QTreeWidgetItem *item = m_view.formats->currentItem();
    if (!item || !item->parent()) return;
    QString currentProfile = item->text(0);
    QString currentGroup = item->parent()->text(0);
840

841
    QString exportFile = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/export/customprofiles.xml";
842 843 844 845 846 847
    QDomDocument doc;
    QFile file(exportFile);
    doc.setContent(&file, false);
    file.close();

    QDomElement documentElement;
848
    QDomNodeList profiles = doc.elementsByTagName(QStringLiteral("profile"));
849
    int i = 0;
850 851 852
    QString profileName;
    while (!profiles.item(i).isNull()) {
        documentElement = profiles.item(i).toElement();
853
        profileName = documentElement.attribute(QStringLiteral("name"));
854
        if (profileName == currentProfile) {
855
            doc.documentElement().removeChild(profiles.item(i));
856 857
            break;
        }
858
        ++i;
859 860 861 862 863 864 865 866
    }