1 ///////////////////////////////////////////////////////////////////////////////
2 // Simple x264 Launcher
3 // Copyright (C) 2004-2014 LoRd_MuldeR <MuldeR2@GMX.de>
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation; either version 2 of the License, or
8 // (at your option) any later version.
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License along
16 // with this program; if not, write to the Free Software Foundation, Inc.,
17 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 // http://www.gnu.org/licenses/gpl-2.0.txt
20 ///////////////////////////////////////////////////////////////////////////////
22 #include "win_addJob.h"
23 #include "uic_win_addJob.h"
26 #include "model_options.h"
27 #include "model_preferences.h"
28 #include "model_sysinfo.h"
29 #include "model_recently.h"
31 #include "win_editor.h"
35 #include <QCloseEvent>
36 #include <QMessageBox>
37 #include <QFileDialog>
38 #include <QDesktopServices>
41 #include <QInputDialog>
48 #define ARRAY_SIZE(ARRAY) (sizeof((ARRAY))/sizeof((ARRAY[0])))
49 #define VALID_DIR(PATH) ((!(PATH).isEmpty()) && QFileInfo(PATH).exists() && QFileInfo(PATH).isDir())
51 #define REMOVE_USAFED_ITEM \
53 for(int i = 0; i < ui->cbxTemplate->count(); i++) \
55 const OptionsModel* temp = reinterpret_cast<const OptionsModel*>(ui->cbxTemplate->itemData(i).value<const void*>()); \
58 ui->cbxTemplate->blockSignals(true); \
59 ui->cbxTemplate->removeItem(i); \
60 ui->cbxTemplate->blockSignals(false); \
66 #define ADD_CONTEXTMENU_ACTION(WIDGET, ICON, TEXT, SLOTNAME) \
68 QAction *_action = new QAction((ICON), (TEXT), this); \
69 _action->setData(QVariant::fromValue<void*>(WIDGET)); \
70 WIDGET->addAction(_action); \
71 connect(_action, SIGNAL(triggered(bool)), this, SLOT(SLOTNAME())); \
74 #define ADD_CONTEXTMENU_SEPARATOR(WIDGET) \
76 QAction *_action = new QAction(this); \
77 _action->setSeparator(true); \
78 WIDGET->addAction(_action); \
81 #define BLOCK_SIGNALS(FLAG) do \
83 ui->cbxEncoderType->blockSignals(FLAG); \
84 ui->cbxEncoderArch->blockSignals(FLAG); \
85 ui->cbxEncoderVariant->blockSignals(FLAG); \
86 ui->cbxRateControlMode->blockSignals(FLAG); \
87 ui->spinQuantizer->blockSignals(FLAG); \
88 ui->spinBitrate->blockSignals(FLAG); \
89 ui->cbxPreset->blockSignals(FLAG); \
90 ui->cbxTuning->blockSignals(FLAG); \
91 ui->cbxProfile->blockSignals(FLAG); \
92 ui->editCustomX264Params->blockSignals(FLAG); \
93 ui->editCustomAvs2YUVParams->blockSignals(FLAG); \
97 Q_DECLARE_METATYPE(const void*)
99 ///////////////////////////////////////////////////////////////////////////////
101 ///////////////////////////////////////////////////////////////////////////////
103 class StringValidator : public QValidator
106 StringValidator(QLabel *notifier, QLabel *icon)
108 m_notifier(notifier), m_icon(icon)
114 virtual State validate(QString &input, int &pos) const = 0;
116 virtual void fixup(QString &input) const
118 input = input.simplified();
122 QLabel *const m_notifier, *const m_icon;
124 bool checkParam(const QString &input, const QString ¶m, const bool doubleMinus) const
126 static const char c[20] = {' ', '*', '?', '<', '>', '/', '\\', '"', '\'', '!', '+', '#', '&', '%', '=', ',', ';', '.', 'ยด', '`'};
127 const QString prefix = doubleMinus ? QLatin1String("--") : QLatin1String("-");
130 if(param.length() > 1)
132 flag = flag || input.endsWith(QString("%1%2").arg(prefix, param), Qt::CaseInsensitive);
133 for(size_t i = 0; i < sizeof(c); i++)
135 flag = flag || input.contains(QString("%1%2%3").arg(prefix, param, QChar::fromLatin1(c[i])), Qt::CaseInsensitive);
140 flag = flag || input.startsWith(QString("-%1").arg(param));
141 for(size_t i = 0; i < sizeof(c); i++)
143 flag = flag || input.contains(QString("%1-%2").arg(QChar::fromLatin1(c[i]), param), Qt::CaseSensitive);
146 if((flag) && (m_notifier))
148 m_notifier->setText(tr("Invalid parameter: %1").arg((param.length() > 1) ? QString("%1%2").arg(prefix, param) : QString("-%1").arg(param)));
153 const bool &setStatus(const bool &flag, const QString &toolName) const
159 if(m_notifier->isHidden()) m_notifier->show();
160 if(m_icon) { if(m_icon->isHidden()) m_icon->show(); }
161 if(QWidget *w = m_notifier->topLevelWidget()->focusWidget())
163 QToolTip::showText(static_cast<QWidget*>(w->parent())->mapToGlobal(w->pos()), QString("<nobr>%1</nobr>").arg(tr("<b>Warning:</b> You entered a parameter that is incomaptible with using %1 from a GUI.<br>Please note that the GUI will automatically set <i>this</i> parameter for you (if required).").arg(toolName)), m_notifier, QRect());
171 if(m_notifier->isVisible()) m_notifier->hide();
172 if(m_icon) { if(m_icon->isVisible()) m_icon->hide(); }
173 QToolTip::hideText();
180 class StringValidatorX264 : public StringValidator
183 StringValidatorX264(QLabel *notifier, QLabel *icon) : StringValidator(notifier, icon) {}
185 virtual State validate(QString &input, int &pos) const
187 static const char* p[] = {"B", "o", "h", "p", "q", /*"fps", "frames",*/ "preset", "tune", "profile",
188 "stdin", "crf", "bitrate", "qp", "pass", "stats", "output", "help","quiet", NULL};
190 bool invalid = false;
192 for(size_t i = 0; p[i] && (!invalid); i++)
194 invalid = invalid || checkParam(input, QString::fromLatin1(p[i]), true);
197 return setStatus(invalid, "x264") ? QValidator::Intermediate : QValidator::Acceptable;
201 class StringValidatorAvs2YUV : public StringValidator
204 StringValidatorAvs2YUV(QLabel *notifier, QLabel *icon) : StringValidator(notifier, icon) {}
206 virtual State validate(QString &input, int &pos) const
208 static const char* p[] = {"o", "frames", "seek", "raw", "hfyu", "slave", NULL};
210 bool invalid = false;
212 for(size_t i = 0; p[i] && (!invalid); i++)
214 invalid = invalid || checkParam(input, QString::fromLatin1(p[i]), false);
217 return setStatus(invalid, "Avs2YUV") ? QValidator::Intermediate : QValidator::Acceptable;
221 ///////////////////////////////////////////////////////////////////////////////
222 // Constructor & Destructor
223 ///////////////////////////////////////////////////////////////////////////////
225 AddJobDialog::AddJobDialog(QWidget *parent, OptionsModel *const options, RecentlyUsed *const recentlyUsed, const SysinfoModel *const sysinfo, const PreferencesModel *const preferences)
229 m_recentlyUsed(recentlyUsed),
231 m_preferences(preferences),
232 m_defaults(new OptionsModel(sysinfo)),
233 ui(new Ui::AddJobDialog())
235 //Init the dialog, from the .ui file
237 setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint));
240 ui->buttonSaveTemplate->setMaximumHeight(20);
241 ui->buttonDeleteTemplate->setMaximumHeight(20);
242 resize(width(), minimumHeight());
243 setMinimumSize(size());
244 setMaximumHeight(height());
246 //Hide optional controls
247 ui->checkBoxApplyToAll->setVisible(false);
249 //Monitor combobox changes
250 connect(ui->cbxEncoderType, SIGNAL(currentIndexChanged(int)), this, SLOT(encoderIndexChanged(int)));
251 connect(ui->cbxEncoderVariant, SIGNAL(currentIndexChanged(int)), this, SLOT(variantIndexChanged(int)));
252 connect(ui->cbxRateControlMode, SIGNAL(currentIndexChanged(int)), this, SLOT(modeIndexChanged(int)));
255 connect(ui->buttonBrowseSource, SIGNAL(clicked()), this, SLOT(browseButtonClicked()));
256 connect(ui->buttonBrowseOutput, SIGNAL(clicked()), this, SLOT(browseButtonClicked()));
257 connect(ui->buttonSaveTemplate, SIGNAL(clicked()), this, SLOT(saveTemplateButtonClicked()));
258 connect(ui->buttonDeleteTemplate, SIGNAL(clicked()), this, SLOT(deleteTemplateButtonClicked()));
261 ui->editCustomX264Params->installEventFilter(this);
262 ui->editCustomX264Params->setValidator(new StringValidatorX264(ui->labelNotificationX264, ui->iconNotificationX264));
263 ui->editCustomX264Params->clear();
264 ui->editCustomAvs2YUVParams->installEventFilter(this);
265 ui->editCustomAvs2YUVParams->setValidator(new StringValidatorAvs2YUV(ui->labelNotificationAvs2YUV, ui->iconNotificationAvs2YUV));
266 ui->editCustomAvs2YUVParams->clear();
268 //Install event filter
269 ui->labelHelpScreenX264->installEventFilter(this);
270 ui->labelHelpScreenAvs2YUV->installEventFilter(this);
272 //Monitor for options changes
273 connect(ui->cbxEncoderType, SIGNAL(currentIndexChanged(int)), this, SLOT(configurationChanged()));
274 connect(ui->cbxEncoderArch, SIGNAL(currentIndexChanged(int)), this, SLOT(configurationChanged()));
275 connect(ui->cbxEncoderVariant, SIGNAL(currentIndexChanged(int)), this, SLOT(configurationChanged()));
276 connect(ui->cbxRateControlMode, SIGNAL(currentIndexChanged(int)), this, SLOT(configurationChanged()));
277 connect(ui->spinQuantizer, SIGNAL(valueChanged(double)), this, SLOT(configurationChanged()));
278 connect(ui->spinBitrate, SIGNAL(valueChanged(int)), this, SLOT(configurationChanged()));
279 connect(ui->cbxPreset, SIGNAL(currentIndexChanged(int)), this, SLOT(configurationChanged()));
280 connect(ui->cbxTuning, SIGNAL(currentIndexChanged(int)), this, SLOT(configurationChanged()));
281 connect(ui->cbxProfile, SIGNAL(currentIndexChanged(int)), this, SLOT(configurationChanged()));
282 connect(ui->editCustomX264Params, SIGNAL(textChanged(QString)), this, SLOT(configurationChanged()));
283 connect(ui->editCustomAvs2YUVParams, SIGNAL(textChanged(QString)), this, SLOT(configurationChanged()));
285 //Create context menus
286 ADD_CONTEXTMENU_ACTION(ui->editCustomX264Params, QIcon(":/buttons/page_edit.png"), tr("Open the Text-Editor"), editorActionTriggered);
287 ADD_CONTEXTMENU_ACTION(ui->editCustomAvs2YUVParams, QIcon(":/buttons/page_edit.png"), tr("Open the Text-Editor"), editorActionTriggered);
288 ADD_CONTEXTMENU_SEPARATOR(ui->editCustomX264Params);
289 ADD_CONTEXTMENU_SEPARATOR(ui->editCustomAvs2YUVParams);
290 ADD_CONTEXTMENU_ACTION(ui->editCustomX264Params, QIcon(":/buttons/page_copy.png"), tr("Copy to Clipboard"), copyActionTriggered);
291 ADD_CONTEXTMENU_ACTION(ui->editCustomAvs2YUVParams, QIcon(":/buttons/page_copy.png"), tr("Copy to Clipboard"), copyActionTriggered);
292 ADD_CONTEXTMENU_ACTION(ui->editCustomX264Params, QIcon(":/buttons/page_paste.png"), tr("Paste from Clipboard"), pasteActionTriggered);
293 ADD_CONTEXTMENU_ACTION(ui->editCustomAvs2YUVParams, QIcon(":/buttons/page_paste.png"), tr("Paste from Clipboard"), pasteActionTriggered);
295 //Setup template selector
297 connect(ui->cbxTemplate, SIGNAL(currentIndexChanged(int)), this, SLOT(templateSelected()));
300 AddJobDialog::~AddJobDialog(void)
303 for(int i = 0; i < ui->cbxTemplate->model()->rowCount(); i++)
305 if(ui->cbxTemplate->itemText(i).startsWith("<") || ui->cbxTemplate->itemText(i).endsWith(">"))
309 const OptionsModel *item = reinterpret_cast<const OptionsModel*>(ui->cbxTemplate->itemData(i).value<const void*>());
310 ui->cbxTemplate->setItemData(i, QVariant::fromValue<const void*>(NULL));
315 if(const QValidator *tmp = ui->editCustomX264Params->validator())
317 ui->editCustomX264Params->setValidator(NULL);
320 if(const QValidator *tmp = ui->editCustomAvs2YUVParams->validator())
322 ui->editCustomAvs2YUVParams->setValidator(NULL);
326 X264_DELETE(m_defaults);
330 ///////////////////////////////////////////////////////////////////////////////
332 ///////////////////////////////////////////////////////////////////////////////
334 void AddJobDialog::showEvent(QShowEvent *event)
336 QDialog::showEvent(event);
339 if((!ui->editSource->text().isEmpty()) && ui->editOutput->text().isEmpty())
341 QString outPath = generateOutputFileName(QDir::fromNativeSeparators(ui->editSource->text()), m_recentlyUsed->outputDirectory(), m_recentlyUsed->filterIndex(), m_preferences->getSaveToSourcePath());
342 ui->editOutput->setText(QDir::toNativeSeparators(outPath));
343 ui->buttonAccept->setFocus();
346 ui->labelNotificationX264->hide();
347 ui->iconNotificationX264->hide();
348 ui->labelNotificationAvs2YUV->hide();
349 ui->iconNotificationAvs2YUV->hide();
351 //Enable drag&drop support for this window, required for Qt v4.8.4+
352 setAcceptDrops(true);
355 bool AddJobDialog::eventFilter(QObject *o, QEvent *e)
357 if((o == ui->labelHelpScreenX264) && (e->type() == QEvent::MouseButtonPress))
359 OptionsModel options(m_sysinfo); saveOptions(&options);
360 HelpDialog *helpScreen = new HelpDialog(this, false, m_sysinfo, &options, m_preferences);
362 X264_DELETE(helpScreen);
364 else if((o == ui->labelHelpScreenAvs2YUV) && (e->type() == QEvent::MouseButtonPress))
366 HelpDialog *helpScreen = new HelpDialog(this, false, m_sysinfo, m_defaults, m_preferences);
368 X264_DELETE(helpScreen);
370 else if((o == ui->editCustomX264Params) && (e->type() == QEvent::FocusOut))
372 ui->editCustomX264Params->setText(ui->editCustomX264Params->text().simplified());
374 else if((o == ui->editCustomAvs2YUVParams) && (e->type() == QEvent::FocusOut))
376 ui->editCustomAvs2YUVParams->setText(ui->editCustomAvs2YUVParams->text().simplified());
381 void AddJobDialog::dragEnterEvent(QDragEnterEvent *event)
383 bool accept[2] = {false, false};
385 foreach(const QString &fmt, event->mimeData()->formats())
387 accept[0] = accept[0] || fmt.contains("text/uri-list", Qt::CaseInsensitive);
388 accept[1] = accept[1] || fmt.contains("FileNameW", Qt::CaseInsensitive);
391 if(accept[0] && accept[1])
393 event->acceptProposedAction();
397 void AddJobDialog::dropEvent(QDropEvent *event)
400 QList<QUrl> urls = event->mimeData()->urls();
404 QDragEnterEvent dragEvent(event->pos(), event->proposedAction(), event->mimeData(), Qt::NoButton, Qt::NoModifier);
405 if(qApp->notify(parent(), &dragEvent))
407 qApp->notify(parent(), event);
412 while((!urls.isEmpty()) && droppedFile.isEmpty())
414 QUrl currentUrl = urls.takeFirst();
415 QFileInfo file(currentUrl.toLocalFile());
416 if(file.exists() && file.isFile())
418 qDebug("AddJobDialog::dropEvent: %s", file.canonicalFilePath().toUtf8().constData());
419 droppedFile = file.canonicalFilePath();
423 if(!droppedFile.isEmpty())
425 const QString outFileName = generateOutputFileName(droppedFile, currentOutputPath(), currentOutputIndx(), m_preferences->getSaveToSourcePath());
426 ui->editSource->setText(QDir::toNativeSeparators(droppedFile));
427 ui->editOutput->setText(QDir::toNativeSeparators(outFileName));
431 ///////////////////////////////////////////////////////////////////////////////
433 ///////////////////////////////////////////////////////////////////////////////
435 void AddJobDialog::encoderIndexChanged(int index)
437 const bool isX265 = (index > 0);
438 const bool noProf = isX265 || (ui->cbxEncoderVariant->currentIndex() > 0);
440 ui->cbxEncoderVariant->setItemText(1, isX265 ? tr("16-Bit") : tr("10-Bit"));
441 ui->labelProfile->setEnabled(!noProf);
442 ui->cbxProfile->setEnabled(!noProf);
443 if(noProf) ui->cbxProfile->setCurrentIndex(0);
446 void AddJobDialog::variantIndexChanged(int index)
448 const bool noProf = (index > 0) || (ui->cbxEncoderType->currentIndex() > 0);
450 ui->labelProfile->setEnabled(!noProf);
451 ui->cbxProfile->setEnabled(!noProf);
452 if(noProf) ui->cbxProfile->setCurrentIndex(0);
455 void AddJobDialog::modeIndexChanged(int index)
457 ui->spinQuantizer->setEnabled(index == 0 || index == 1);
458 ui->spinBitrate->setEnabled(index == 2 || index == 3);
461 void AddJobDialog::accept(void)
464 if(ui->cbxEncoderType->currentIndex() == OptionsModel::EncType_X265)
466 QMessageBox::warning(this, tr("x265"), tr("Sorry, x265 support not implemented yet!"));
467 ui->cbxEncoderType->setCurrentIndex(OptionsModel::EncType_X264);
471 //Check 64-Bit support
472 if((ui->cbxEncoderArch->currentIndex() == OptionsModel::EncArch_x64) && (!m_sysinfo->hasX64Support()))
474 QMessageBox::warning(this, tr("64-Bit unsupported!"), tr("Sorry, this computer does <b>not</b> support 64-Bit encoders!"));
475 ui->cbxEncoderArch->setCurrentIndex(OptionsModel::EncArch_x32);
479 //Selection complete?
480 if(ui->editSource->text().trimmed().isEmpty())
482 QMessageBox::warning(this, tr("Not Found!"), tr("Please select a valid source file first!"));
485 if(ui->editOutput->text().trimmed().isEmpty())
487 QMessageBox::warning(this, tr("Not Selected!"), tr("<nobr>Please select a valid output file first!</nobr>"));
492 QFileInfo sourceFile = QFileInfo(this->sourceFile());
493 if(!(sourceFile.exists() && sourceFile.isFile()))
495 QMessageBox::warning(this, tr("Not Found!"), tr("<nobr>The selected source file could not be found!</nobr>"));
499 //Does output file already exist?
500 QFileInfo outputFile = QFileInfo(this->outputFile());
501 if(outputFile.exists() && outputFile.isFile())
503 int ret = QMessageBox::question(this, tr("Already Exists!"), tr("<nobr>Output file already exists! Overwrite?</nobr>"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
504 if(ret != QMessageBox::Yes) return;
506 if(outputFile.exists() && (!outputFile.isFile()))
508 QMessageBox::warning(this, tr("Not a File!"), tr("<nobr>Selected output file does not appear to be a valid file!</nobr>"));
512 //Is destination dir writable?
513 QFileInfo outputDir = QFileInfo(outputFile.absolutePath());
514 if(!(outputDir.exists() && outputDir.isDir() && outputDir.isWritable()))
516 QMessageBox::warning(this, tr("Not Writable!"), tr("<nobr>Output directory does not exist or is not writable!</nobr>"));
520 //Custom parameters okay?
521 if(!ui->editCustomX264Params->hasAcceptableInput())
523 int ret = QMessageBox::warning(this, tr("Invalid Params"), tr("<nobr>Your custom parameters are invalid and will be discarded!</nobr>"), QMessageBox::Ignore | QMessageBox::Cancel, QMessageBox::Cancel);
524 if(ret != QMessageBox::Ignore) return;
527 //Update recently used
528 m_recentlyUsed->setFilterIndex(currentOutputIndx());
529 m_recentlyUsed->setSourceDirectory(currentSourcePath());
530 m_recentlyUsed->setOutputDirectory(currentOutputPath());
531 RecentlyUsed::saveRecentlyUsed(m_recentlyUsed);
534 saveOptions(m_options);
538 void AddJobDialog::browseButtonClicked(void)
540 if(QObject::sender() == ui->buttonBrowseSource)
542 QString filePath = QFileDialog::getOpenFileName(this, tr("Open Source File"), currentSourcePath(true), getInputFilterLst(), NULL, QFileDialog::DontUseNativeDialog);
543 if(!(filePath.isNull() || filePath.isEmpty()))
545 QString destFile = generateOutputFileName(filePath, currentOutputPath(), currentOutputIndx(), m_preferences->getSaveToSourcePath());
546 ui->editSource->setText(QDir::toNativeSeparators(filePath));
547 ui->editOutput->setText(QDir::toNativeSeparators(destFile));
550 else if(QObject::sender() == ui->buttonBrowseOutput)
552 QString selectedType = getFilterStr(currentOutputIndx());
553 QString filePath = QFileDialog::getSaveFileName(this, tr("Choose Output File"), currentOutputPath(true), getFilterLst(), &selectedType, QFileDialog::DontUseNativeDialog | QFileDialog::DontConfirmOverwrite);
555 if(!(filePath.isNull() || filePath.isEmpty()))
557 if(getFilterIdx(QFileInfo(filePath).suffix()) < 0)
560 QRegExp regExp("\\(\\*\\.(\\w+)\\)");
561 if(regExp.lastIndexIn(selectedType) >= 0)
563 tempIndex = getFilterIdx(regExp.cap(1));
567 tempIndex = m_recentlyUsed->filterIndex();
569 filePath = QString("%1.%2").arg(filePath, getFilterExt(tempIndex));
571 ui->editOutput->setText(QDir::toNativeSeparators(filePath));
576 void AddJobDialog::configurationChanged(void)
578 const OptionsModel* options = reinterpret_cast<const OptionsModel*>(ui->cbxTemplate->itemData(ui->cbxTemplate->currentIndex()).value<const void*>());
581 ui->cbxTemplate->blockSignals(true);
582 ui->cbxTemplate->insertItem(0, tr("<Unsaved Configuration>"), QVariant::fromValue<const void*>(NULL));
583 ui->cbxTemplate->setCurrentIndex(0);
584 ui->cbxTemplate->blockSignals(false);
588 void AddJobDialog::templateSelected(void)
590 const OptionsModel* options = reinterpret_cast<const OptionsModel*>(ui->cbxTemplate->itemData(ui->cbxTemplate->currentIndex()).value<const void*>());
593 qDebug("Loading options!");
595 restoreOptions(options);
599 encoderIndexChanged(ui->cbxEncoderType->currentIndex());
600 variantIndexChanged(ui->cbxEncoderVariant->currentIndex());
601 modeIndexChanged(ui->cbxRateControlMode->currentIndex());
604 void AddJobDialog::saveTemplateButtonClicked(void)
606 qDebug("Saving template");
607 QString name = tr("New Template");
610 while(OptionsModel::templateExists(name))
612 name = tr("New Template (%1)").arg(QString::number(n++));
615 OptionsModel *options = new OptionsModel(m_sysinfo);
616 saveOptions(options);
618 if(options->equals(m_defaults))
620 QMessageBox::warning (this, tr("Oups"), tr("<nobr>It makes no sense to save the default settings!</nobr>"));
621 ui->cbxTemplate->blockSignals(true);
622 ui->cbxTemplate->setCurrentIndex(0);
623 ui->cbxTemplate->blockSignals(false);
625 X264_DELETE(options);
629 for(int i = 0; i < ui->cbxTemplate->count(); i++)
631 const QString tempName = ui->cbxTemplate->itemText(i);
632 if(tempName.contains('<') || tempName.contains('>'))
636 const OptionsModel* test = reinterpret_cast<const OptionsModel*>(ui->cbxTemplate->itemData(i).value<const void*>());
639 if(options->equals(test))
641 QMessageBox::warning (this, tr("Oups"), tr("<nobr>There already is a template for the current settings!</nobr>"));
642 ui->cbxTemplate->blockSignals(true);
643 ui->cbxTemplate->setCurrentIndex(i);
644 ui->cbxTemplate->blockSignals(false);
646 X264_DELETE(options);
655 name = QInputDialog::getText(this, tr("Save Template"), tr("Please enter the name of the template:").leftJustified(144, ' '), QLineEdit::Normal, name, &ok).simplified();
658 X264_DELETE(options);
661 if(name.contains('<') || name.contains('>') || name.contains('\\') || name.contains('/') || name.contains('"'))
663 QMessageBox::warning (this, tr("Invalid Name"), tr("<nobr>Sorry, the name you have entered is invalid!</nobr>"));
664 while(name.contains('<')) name.remove('<');
665 while(name.contains('>')) name.remove('>');
666 while(name.contains('\\')) name.remove('\\');
667 while(name.contains('/')) name.remove('/');
668 while(name.contains('"')) name.remove('"');
669 name = name.simplified();
672 if(OptionsModel::templateExists(name))
674 int ret = QMessageBox::warning (this, tr("Already Exists"), tr("<nobr>A template of that name already exists! Overwrite?</nobr>"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
675 if(ret != QMessageBox::Yes)
683 if(!OptionsModel::saveTemplate(options, name))
685 QMessageBox::critical(this, tr("Save Failed"), tr("Sorry, the template could not be saved!"));
686 X264_DELETE(options);
690 int index = ui->cbxTemplate->model()->rowCount();
691 ui->cbxTemplate->blockSignals(true);
692 for(int i = 0; i < ui->cbxTemplate->count(); i++)
694 if(ui->cbxTemplate->itemText(i).compare(name, Qt::CaseInsensitive) == 0)
696 index = -1; //Do not append new template
697 const OptionsModel *oldItem = reinterpret_cast<const OptionsModel*>(ui->cbxTemplate->itemData(i).value<const void*>());
698 ui->cbxTemplate->setItemData(i, QVariant::fromValue<const void*>(options));
699 ui->cbxTemplate->setCurrentIndex(i);
700 X264_DELETE(oldItem);
705 ui->cbxTemplate->insertItem(index, name, QVariant::fromValue<const void*>(options));
706 ui->cbxTemplate->setCurrentIndex(index);
708 ui->cbxTemplate->blockSignals(false);
713 void AddJobDialog::deleteTemplateButtonClicked(void)
715 const int index = ui->cbxTemplate->currentIndex();
716 QString name = ui->cbxTemplate->itemText(index);
718 if(name.contains('<') || name.contains('>') || name.contains('\\') || name.contains('/'))
720 QMessageBox::warning (this, tr("Invalid Item"), tr("Sorry, the selected item cannot be deleted!"));
724 int ret = QMessageBox::question (this, tr("Delete Template"), tr("<nobr>Do you really want to delete the selected template?</nobr>"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
725 if(ret != QMessageBox::Yes)
731 OptionsModel::deleteTemplate(name);
732 const OptionsModel *item = reinterpret_cast<const OptionsModel*>(ui->cbxTemplate->itemData(index).value<const void*>());
733 ui->cbxTemplate->removeItem(index);
737 void AddJobDialog::editorActionTriggered(void)
740 if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
742 QLineEdit *lineEdit = reinterpret_cast<QLineEdit*>(action->data().value<void*>());
744 EditorDialog *editor = new EditorDialog(this);
745 editor->setEditText(lineEdit->text());
747 if(editor->exec() == QDialog::Accepted)
749 lineEdit->setText(editor->getEditText());
756 void AddJobDialog::copyActionTriggered(void)
758 if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
760 QClipboard *clipboard = QApplication::clipboard();
761 QLineEdit *lineEdit = reinterpret_cast<QLineEdit*>(action->data().value<void*>());
762 QString text = lineEdit->hasSelectedText() ? lineEdit->selectedText() : lineEdit->text();
763 clipboard->setText(text);
767 void AddJobDialog::pasteActionTriggered(void)
769 if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
771 QClipboard *clipboard = QApplication::clipboard();
772 QLineEdit *lineEdit = reinterpret_cast<QLineEdit*>(action->data().value<void*>());
773 QString text = clipboard->text();
774 if(!text.isEmpty()) lineEdit->setText(text);
778 ///////////////////////////////////////////////////////////////////////////////
780 ///////////////////////////////////////////////////////////////////////////////
782 QString AddJobDialog::sourceFile(void)
784 return QDir::fromNativeSeparators(ui->editSource->text());
787 QString AddJobDialog::outputFile(void)
789 return QDir::fromNativeSeparators(ui->editOutput->text());
792 bool AddJobDialog::runImmediately(void)
794 return ui->checkBoxRun->isChecked();
797 bool AddJobDialog::applyToAll(void)
799 return ui->checkBoxApplyToAll->isChecked();
802 void AddJobDialog::setRunImmediately(bool run)
804 ui->checkBoxRun->setChecked(run);
807 void AddJobDialog::setSourceFile(const QString &path)
809 ui->editSource->setText(QDir::toNativeSeparators(path));
812 void AddJobDialog::setOutputFile(const QString &path)
814 ui->editOutput->setText(QDir::toNativeSeparators(path));}
816 void AddJobDialog::setSourceEditable(const bool editable)
818 ui->buttonBrowseSource->setEnabled(editable);
821 void AddJobDialog::setApplyToAllVisible(const bool visible)
823 ui->checkBoxApplyToAll->setVisible(visible);
826 ///////////////////////////////////////////////////////////////////////////////
828 ///////////////////////////////////////////////////////////////////////////////
830 void AddJobDialog::loadTemplateList(void)
832 ui->cbxTemplate->addItem(tr("<Default>"), QVariant::fromValue<const void*>(m_defaults));
833 ui->cbxTemplate->setCurrentIndex(0);
835 QMap<QString, OptionsModel*> templates = OptionsModel::loadAllTemplates(m_sysinfo);
836 QStringList templateNames = templates.keys();
837 templateNames.sort();
839 for(QStringList::ConstIterator current = templateNames.constBegin(); current != templateNames.constEnd(); current++)
841 OptionsModel *currentTemplate = templates.take(*current);
842 ui->cbxTemplate->addItem(*current, QVariant::fromValue<const void*>(currentTemplate));
843 if(currentTemplate->equals(m_options))
845 ui->cbxTemplate->setCurrentIndex(ui->cbxTemplate->count() - 1);
849 if((ui->cbxTemplate->currentIndex() == 0) && (!m_options->equals(m_defaults)))
851 qWarning("Not the default -> recently used!");
852 ui->cbxTemplate->insertItem(1, tr("<Recently Used>"), QVariant::fromValue<const void*>(m_options));
853 ui->cbxTemplate->setCurrentIndex(1);
857 void AddJobDialog::updateComboBox(QComboBox *cbox, const QString &text)
860 if(QAbstractItemModel *model = cbox->model())
862 for(int i = 0; i < cbox->model()->rowCount(); i++)
864 if(model->data(model->index(i, 0, QModelIndex())).toString().compare(text, Qt::CaseInsensitive) == 0)
871 cbox->setCurrentIndex(index);
874 void AddJobDialog::restoreOptions(const OptionsModel *options)
878 ui->cbxEncoderType->setCurrentIndex(options->encType());
879 ui->cbxEncoderArch->setCurrentIndex(options->encArch());
880 ui->cbxEncoderVariant->setCurrentIndex(options->encVariant());
881 ui->cbxRateControlMode->setCurrentIndex(options->rcMode());
882 ui->spinQuantizer->setValue(options->quantizer());
883 ui->spinBitrate->setValue(options->bitrate());
884 updateComboBox(ui->cbxPreset, options->preset());
885 updateComboBox(ui->cbxTuning, options->tune());
886 updateComboBox(ui->cbxProfile, options->profile());
887 ui->editCustomX264Params->setText(options->customEncParams());
888 ui->editCustomAvs2YUVParams->setText(options->customAvs2YUV());
890 BLOCK_SIGNALS(false);
893 void AddJobDialog::saveOptions(OptionsModel *options)
895 options->setEncType(static_cast<OptionsModel::EncType>(ui->cbxEncoderType->currentIndex()));
896 options->setEncArch(static_cast<OptionsModel::EncArch>(ui->cbxEncoderArch->currentIndex()));
897 options->setEncVariant(static_cast<OptionsModel::EncVariant>(ui->cbxEncoderVariant->currentIndex()));
898 options->setRCMode(static_cast<OptionsModel::RCMode>(ui->cbxRateControlMode->currentIndex()));
899 options->setQuantizer(ui->spinQuantizer->value());
900 options->setBitrate(ui->spinBitrate->value());
901 options->setPreset(ui->cbxPreset->model()->data(ui->cbxPreset->model()->index(ui->cbxPreset->currentIndex(), 0)).toString());
902 options->setTune(ui->cbxTuning->model()->data(ui->cbxTuning->model()->index(ui->cbxTuning->currentIndex(), 0)).toString());
903 options->setProfile(ui->cbxProfile->model()->data(ui->cbxProfile->model()->index(ui->cbxProfile->currentIndex(), 0)).toString());
904 options->setCustomEncParams(ui->editCustomX264Params->hasAcceptableInput() ? ui->editCustomX264Params->text().simplified() : QString());
905 options->setCustomAvs2YUV(ui->editCustomAvs2YUVParams->hasAcceptableInput() ? ui->editCustomAvs2YUVParams->text().simplified() : QString());
908 QString AddJobDialog::currentSourcePath(const bool bWithName)
910 QString path = m_recentlyUsed->sourceDirectory();
911 QString currentSourceFile = this->sourceFile();
913 if(!currentSourceFile.isEmpty())
915 QString currentSourceDir = QFileInfo(currentSourceFile).absolutePath();
916 if(VALID_DIR(currentSourceDir))
918 path = currentSourceDir;
922 path.append("/").append(QFileInfo(currentSourceFile).fileName());
929 QString AddJobDialog::currentOutputPath(const bool bWithName)
931 QString path = m_recentlyUsed->outputDirectory();
932 QString currentOutputFile = this->outputFile();
934 if(!currentOutputFile.isEmpty())
936 QString currentOutputDir = QFileInfo(currentOutputFile).absolutePath();
937 if(VALID_DIR(currentOutputDir))
939 path = currentOutputDir;
943 path.append("/").append(QFileInfo(currentOutputFile).fileName());
950 int AddJobDialog::currentOutputIndx(void)
952 int index = m_recentlyUsed->filterIndex();
953 QString currentOutputFile = this->outputFile();
955 if(!currentOutputFile.isEmpty())
957 const QString currentOutputExtn = QFileInfo(currentOutputFile).suffix();
958 const int tempIndex = getFilterIdx(currentOutputExtn);
968 ///////////////////////////////////////////////////////////////////////////////
970 ///////////////////////////////////////////////////////////////////////////////
972 QString AddJobDialog::generateOutputFileName(const QString &sourceFilePath, const QString &destinationDirectory, const int filterIndex, const bool saveToSourceDir)
974 QString name = QFileInfo(sourceFilePath).completeBaseName();
975 QString path = saveToSourceDir ? QFileInfo(sourceFilePath).canonicalPath() : destinationDirectory;
976 QString fext = getFilterExt(filterIndex);
980 RecentlyUsed defaults;
981 path = defaults.outputDirectory();
984 QString outPath = QString("%1/%2.%3").arg(path, name, fext);
987 while(QFileInfo(outPath).exists())
989 outPath = QString("%1/%2 (%3).%4").arg(path, name, QString::number(n++), fext);
995 /* ------------------------------------------------------------------------- */
997 QString AddJobDialog::getFilterExt(const int filterIndex)
999 const int count = ARRAY_SIZE(X264_FILE_TYPE_FILTERS);
1001 if((filterIndex >= 0) && (filterIndex < count))
1003 return QString::fromLatin1(X264_FILE_TYPE_FILTERS[filterIndex].pcExt);
1006 return QString::fromLatin1(X264_FILE_TYPE_FILTERS[0].pcExt);
1009 int AddJobDialog::getFilterIdx(const QString &fileExt)
1011 const int count = ARRAY_SIZE(X264_FILE_TYPE_FILTERS);
1013 for(int i = 0; i < count; i++)
1015 if(fileExt.compare(QString::fromLatin1(X264_FILE_TYPE_FILTERS[i].pcExt), Qt::CaseInsensitive) == 0)
1024 QString AddJobDialog::getFilterStr(const int filterIndex)
1026 const int count = ARRAY_SIZE(X264_FILE_TYPE_FILTERS);
1028 if((filterIndex >= 0) && (filterIndex < count))
1030 return QString("%1 (*.%2)").arg(QString::fromLatin1(X264_FILE_TYPE_FILTERS[filterIndex].pcStr), QString::fromLatin1(X264_FILE_TYPE_FILTERS[filterIndex].pcExt));
1033 return QString("%1 (*.%2)").arg(QString::fromLatin1(X264_FILE_TYPE_FILTERS[0].pcStr), QString::fromLatin1(X264_FILE_TYPE_FILTERS[0].pcExt));
1036 QString AddJobDialog::getFilterLst(void)
1038 QStringList filters;
1039 const int count = ARRAY_SIZE(X264_FILE_TYPE_FILTERS);
1041 for(int i = 0; i < count; i++)
1043 filters << QString("%1 (*.%2)").arg(QString::fromLatin1(X264_FILE_TYPE_FILTERS[i].pcStr), QString::fromLatin1(X264_FILE_TYPE_FILTERS[i].pcExt));
1046 return filters.join(";;");
1049 QString AddJobDialog::getInputFilterLst(void)
1058 {"Avisynth Scripts", "avs"},
1059 {"VapourSynth Scripts", "vpy"},
1060 {"Matroska Files", "mkv"},
1061 {"MPEG-4 Part 14 Container", "mp4"},
1062 {"Audio Video Interleaved", "avi"},
1063 {"Flash Video", "flv"},
1064 {"YUV4MPEG2 Stream", "y4m"},
1065 {"Uncompresses YUV Data", "yuv"},
1068 const int count = ARRAY_SIZE(s_filters);
1071 for(size_t index = 0; index < count; index++)
1074 allTypes += QString((index > 0) ? " *.%1" : "*.%1").arg(QString::fromLatin1(s_filters[index].fext));
1077 QStringList filters;
1078 filters << QString("All supported files (%1)").arg(allTypes);
1080 for(size_t index = 0; index < count; index++)
1082 filters << QString("%1 (*.%2)").arg(QString::fromLatin1(s_filters[index].name), QString::fromLatin1(s_filters[index].fext));
1085 filters << QString("All files (*.*)");
1086 return filters.join(";;");