OSDN Git Service

Select the 64-Bit encoder by default on 64-Bit systems.
[x264-launcher/x264-launcher.git] / src / win_addJob.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Simple x264 Launcher
3 // Copyright (C) 2004-2014 LoRd_MuldeR <MuldeR2@GMX.de>
4 //
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.
9 //
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.
14 //
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.
18 //
19 // http://www.gnu.org/licenses/gpl-2.0.txt
20 ///////////////////////////////////////////////////////////////////////////////
21
22 #include "win_addJob.h"
23 #include "uic_win_addJob.h"
24
25 #include "global.h"
26 #include "model_options.h"
27 #include "model_preferences.h"
28 #include "model_sysinfo.h"
29 #include "model_recently.h"
30 #include "win_help.h"
31 #include "win_editor.h"
32
33 #include <QDate>
34 #include <QTimer>
35 #include <QCloseEvent>
36 #include <QMessageBox>
37 #include <QFileDialog>
38 #include <QDesktopServices>
39 #include <QValidator>
40 #include <QDir>
41 #include <QInputDialog>
42 #include <QSettings>
43 #include <QUrl>
44 #include <QAction>
45 #include <QClipboard>
46 #include <QToolTip>
47
48 #define ARRAY_SIZE(ARRAY) (sizeof((ARRAY))/sizeof((ARRAY[0])))
49 #define VALID_DIR(PATH) ((!(PATH).isEmpty()) && QFileInfo(PATH).exists() && QFileInfo(PATH).isDir())
50
51 #define REMOVE_USAFED_ITEM \
52 { \
53         for(int i = 0; i < ui->cbxTemplate->count(); i++) \
54         { \
55                 const OptionsModel* temp = reinterpret_cast<const OptionsModel*>(ui->cbxTemplate->itemData(i).value<const void*>()); \
56                 if(temp == NULL) \
57                 { \
58                         ui->cbxTemplate->blockSignals(true); \
59                         ui->cbxTemplate->removeItem(i); \
60                         ui->cbxTemplate->blockSignals(false); \
61                         break; \
62                 } \
63         } \
64 }
65
66 #define ADD_CONTEXTMENU_ACTION(WIDGET, ICON, TEXT, SLOTNAME) \
67 { \
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())); \
72 }
73
74 #define ADD_CONTEXTMENU_SEPARATOR(WIDGET) \
75 { \
76         QAction *_action = new QAction(this); \
77         _action->setSeparator(true); \
78         WIDGET->addAction(_action); \
79
80
81 #define BLOCK_SIGNALS(FLAG) do \
82 { \
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); \
94 } \
95 while(0)
96
97 Q_DECLARE_METATYPE(const void*)
98
99 ///////////////////////////////////////////////////////////////////////////////
100 // Validator
101 ///////////////////////////////////////////////////////////////////////////////
102
103 class StringValidator : public QValidator
104 {
105 public:
106         StringValidator(QLabel *notifier, QLabel *icon)
107         :
108                 m_notifier(notifier), m_icon(icon)
109         {
110                 m_notifier->hide();
111                 m_icon->hide();
112         }
113         
114         virtual State validate(QString &input, int &pos) const = 0;
115
116         virtual void fixup(QString &input) const
117         {
118                 input = input.simplified();
119         }
120
121 protected:
122         QLabel *const m_notifier, *const m_icon;
123
124         bool checkParam(const QString &input, const QString &param, const bool doubleMinus) const
125         {
126                 static const char c[20] = {' ', '*', '?', '<', '>', '/', '\\', '"', '\'', '!', '+', '#', '&', '%', '=', ',', ';', '.', 'ยด', '`'};
127                 const QString prefix = doubleMinus ? QLatin1String("--") : QLatin1String("-");
128                 
129                 bool flag = false;
130                 if(param.length() > 1)
131                 {
132                         flag = flag || input.endsWith(QString("%1%2").arg(prefix, param), Qt::CaseInsensitive);
133                         for(size_t i = 0; i < sizeof(c); i++)
134                         {
135                                 flag = flag || input.contains(QString("%1%2%3").arg(prefix, param, QChar::fromLatin1(c[i])), Qt::CaseInsensitive);
136                         }
137                 }
138                 else
139                 {
140                         flag = flag || input.startsWith(QString("-%1").arg(param));
141                         for(size_t i = 0; i < sizeof(c); i++)
142                         {
143                                 flag = flag || input.contains(QString("%1-%2").arg(QChar::fromLatin1(c[i]), param), Qt::CaseSensitive);
144                         }
145                 }
146                 if((flag) && (m_notifier))
147                 {
148                         m_notifier->setText(tr("Invalid parameter: %1").arg((param.length() > 1) ? QString("%1%2").arg(prefix, param) : QString("-%1").arg(param)));
149                 }
150                 return flag;
151         }
152
153         const bool &setStatus(const bool &flag, const QString &toolName) const
154         {
155                 if(flag)
156                 {
157                         if(m_notifier)
158                         {
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())
162                                 {
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());
164                                 }
165                         }
166                 }
167                 else
168                 {
169                         if(m_notifier)
170                         {
171                                 if(m_notifier->isVisible()) m_notifier->hide();
172                                 if(m_icon) { if(m_icon->isVisible()) m_icon->hide(); }
173                                 QToolTip::hideText();
174                         }
175                 }
176                 return flag;
177         }
178 };
179
180 class StringValidatorX264 : public StringValidator
181 {
182 public:
183         StringValidatorX264(QLabel *notifier, QLabel *icon) : StringValidator(notifier, icon) {}
184
185         virtual State validate(QString &input, int &pos) const
186         {
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};
189
190                 bool invalid = false;
191
192                 for(size_t i = 0; p[i] && (!invalid); i++)
193                 {
194                         invalid = invalid || checkParam(input, QString::fromLatin1(p[i]), true);
195                 }
196
197                 return setStatus(invalid, "x264") ? QValidator::Intermediate : QValidator::Acceptable;
198         }
199 };
200
201 class StringValidatorAvs2YUV : public StringValidator
202 {
203 public:
204         StringValidatorAvs2YUV(QLabel *notifier, QLabel *icon) : StringValidator(notifier, icon) {}
205
206         virtual State validate(QString &input, int &pos) const
207         {
208                 static const char* p[] = {"o", "frames", "seek", "raw", "hfyu", "slave", NULL};
209
210                 bool invalid = false;
211
212                 for(size_t i = 0; p[i] && (!invalid); i++)
213                 {
214                         invalid = invalid || checkParam(input, QString::fromLatin1(p[i]), false);
215                 }
216                 
217                 return setStatus(invalid, "Avs2YUV") ? QValidator::Intermediate : QValidator::Acceptable;
218         }
219 };
220
221 ///////////////////////////////////////////////////////////////////////////////
222 // Constructor & Destructor
223 ///////////////////////////////////////////////////////////////////////////////
224
225 AddJobDialog::AddJobDialog(QWidget *parent, OptionsModel *const options, RecentlyUsed *const recentlyUsed, const SysinfoModel *const sysinfo, const PreferencesModel *const preferences)
226 :
227         QDialog(parent),
228         m_options(options),
229         m_recentlyUsed(recentlyUsed),
230         m_sysinfo(sysinfo),
231         m_preferences(preferences),
232         m_defaults(new OptionsModel(sysinfo)),
233         ui(new Ui::AddJobDialog())
234 {
235         //Init the dialog, from the .ui file
236         ui->setupUi(this);
237         setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint));
238         
239         //Fix dialog size
240         ui->buttonSaveTemplate->setMaximumHeight(20);
241         ui->buttonDeleteTemplate->setMaximumHeight(20);
242         resize(width(), minimumHeight());
243         setMinimumSize(size());
244         setMaximumHeight(height());
245
246         //Hide optional controls
247         ui->checkBoxApplyToAll->setVisible(false);
248
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)));
253
254         //Activate buttons
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()));
259
260         //Setup validator
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();
267
268         //Install event filter
269         ui->labelHelpScreenX264->installEventFilter(this);
270         ui->labelHelpScreenAvs2YUV->installEventFilter(this);
271
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()));
284
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);
294
295         //Setup template selector
296         loadTemplateList();
297         connect(ui->cbxTemplate, SIGNAL(currentIndexChanged(int)), this, SLOT(templateSelected()));
298 }
299
300 AddJobDialog::~AddJobDialog(void)
301 {
302         //Free templates
303         for(int i = 0; i < ui->cbxTemplate->model()->rowCount(); i++)
304         {
305                 if(ui->cbxTemplate->itemText(i).startsWith("<") || ui->cbxTemplate->itemText(i).endsWith(">"))
306                 {
307                         continue;
308                 }
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));
311                 X264_DELETE(item);
312         }
313
314         //Free validators
315         if(const QValidator *tmp = ui->editCustomX264Params->validator())
316         {
317                 ui->editCustomX264Params->setValidator(NULL);
318                 X264_DELETE(tmp);
319         }
320         if(const QValidator *tmp = ui->editCustomAvs2YUVParams->validator())
321         {
322                 ui->editCustomAvs2YUVParams->setValidator(NULL);
323                 X264_DELETE(tmp);
324         }
325
326         X264_DELETE(m_defaults);
327         delete ui;
328 }
329
330 ///////////////////////////////////////////////////////////////////////////////
331 // Events
332 ///////////////////////////////////////////////////////////////////////////////
333
334 void AddJobDialog::showEvent(QShowEvent *event)
335 {
336         QDialog::showEvent(event);
337         templateSelected();
338
339         if((!ui->editSource->text().isEmpty()) && ui->editOutput->text().isEmpty())
340         {
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();
344         }
345
346         ui->labelNotificationX264->hide();
347         ui->iconNotificationX264->hide();
348         ui->labelNotificationAvs2YUV->hide();
349         ui->iconNotificationAvs2YUV->hide();
350
351         //Enable drag&drop support for this window, required for Qt v4.8.4+
352         setAcceptDrops(true);
353 }
354
355 bool AddJobDialog::eventFilter(QObject *o, QEvent *e)
356 {
357         if((o == ui->labelHelpScreenX264) && (e->type() == QEvent::MouseButtonPress))
358         {
359                 OptionsModel options(m_sysinfo); saveOptions(&options);
360                 HelpDialog *helpScreen = new HelpDialog(this, false, m_sysinfo, &options, m_preferences);
361                 helpScreen->exec();
362                 X264_DELETE(helpScreen);
363         }
364         else if((o == ui->labelHelpScreenAvs2YUV) && (e->type() == QEvent::MouseButtonPress))
365         {
366                 HelpDialog *helpScreen = new HelpDialog(this, false, m_sysinfo, m_defaults, m_preferences);
367                 helpScreen->exec();
368                 X264_DELETE(helpScreen);
369         }
370         else if((o == ui->editCustomX264Params) && (e->type() == QEvent::FocusOut))
371         {
372                 ui->editCustomX264Params->setText(ui->editCustomX264Params->text().simplified());
373         }
374         else if((o == ui->editCustomAvs2YUVParams) && (e->type() == QEvent::FocusOut))
375         {
376                 ui->editCustomAvs2YUVParams->setText(ui->editCustomAvs2YUVParams->text().simplified());
377         }
378         return false;
379 }
380
381 void AddJobDialog::dragEnterEvent(QDragEnterEvent *event)
382 {
383         bool accept[2] = {false, false};
384
385         foreach(const QString &fmt, event->mimeData()->formats())
386         {
387                 accept[0] = accept[0] || fmt.contains("text/uri-list", Qt::CaseInsensitive);
388                 accept[1] = accept[1] || fmt.contains("FileNameW", Qt::CaseInsensitive);
389         }
390
391         if(accept[0] && accept[1])
392         {
393                 event->acceptProposedAction();
394         }
395 }
396
397 void AddJobDialog::dropEvent(QDropEvent *event)
398 {
399         QString droppedFile;
400         QList<QUrl> urls = event->mimeData()->urls();
401
402         if(urls.count() > 1)
403         {
404                 QDragEnterEvent dragEvent(event->pos(), event->proposedAction(), event->mimeData(), Qt::NoButton, Qt::NoModifier);
405                 if(qApp->notify(parent(), &dragEvent))
406                 {
407                         qApp->notify(parent(), event);
408                         reject(); return;
409                 }
410         }
411
412         while((!urls.isEmpty()) && droppedFile.isEmpty())
413         {
414                 QUrl currentUrl = urls.takeFirst();
415                 QFileInfo file(currentUrl.toLocalFile());
416                 if(file.exists() && file.isFile())
417                 {
418                         qDebug("AddJobDialog::dropEvent: %s", file.canonicalFilePath().toUtf8().constData());
419                         droppedFile = file.canonicalFilePath();
420                 }
421         }
422         
423         if(!droppedFile.isEmpty())
424         {
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));
428         }
429 }
430
431 ///////////////////////////////////////////////////////////////////////////////
432 // Slots
433 ///////////////////////////////////////////////////////////////////////////////
434
435 void AddJobDialog::encoderIndexChanged(int index)
436 {
437         const bool isX265 = (index > 0);
438         const bool noProf = isX265 || (ui->cbxEncoderVariant->currentIndex() > 0);
439
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);
444 }
445
446 void AddJobDialog::variantIndexChanged(int index)
447 {
448         const bool noProf = (index > 0) || (ui->cbxEncoderType->currentIndex() > 0);
449
450         ui->labelProfile->setEnabled(!noProf);
451         ui->cbxProfile->setEnabled(!noProf);
452         if(noProf) ui->cbxProfile->setCurrentIndex(0);
453 }
454
455 void AddJobDialog::modeIndexChanged(int index)
456 {
457         ui->spinQuantizer->setEnabled(index == 0 || index == 1);
458         ui->spinBitrate->setEnabled(index == 2 || index == 3);
459 }
460
461 void AddJobDialog::accept(void)
462 {
463         //FIXME
464         if(ui->cbxEncoderType->currentIndex() == OptionsModel::EncType_X265)
465         {
466                 QMessageBox::warning(this, tr("x265"), tr("Sorry, x265 support not implemented yet!"));
467                 ui->cbxEncoderType->setCurrentIndex(OptionsModel::EncType_X264);
468                 return;
469         }
470
471         //Check 64-Bit support
472         if((ui->cbxEncoderArch->currentIndex() == OptionsModel::EncArch_x64) && (!m_sysinfo->hasX64Support()))
473         {
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);
476                 return;
477         }
478         
479         //Selection complete?
480         if(ui->editSource->text().trimmed().isEmpty())
481         {
482                 QMessageBox::warning(this, tr("Not Found!"), tr("Please select a valid source file first!"));
483                 return;
484         }
485         if(ui->editOutput->text().trimmed().isEmpty())
486         {
487                 QMessageBox::warning(this, tr("Not Selected!"), tr("<nobr>Please select a valid output file first!</nobr>"));
488                 return;
489         }
490
491         //Does source exist?
492         QFileInfo sourceFile = QFileInfo(this->sourceFile());
493         if(!(sourceFile.exists() && sourceFile.isFile()))
494         {
495                 QMessageBox::warning(this, tr("Not Found!"), tr("<nobr>The selected source file could not be found!</nobr>"));
496                 return;
497         }
498
499         //Does output file already exist?
500         QFileInfo outputFile = QFileInfo(this->outputFile());
501         if(outputFile.exists() && outputFile.isFile())
502         {
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;
505         }
506         if(outputFile.exists() && (!outputFile.isFile()))
507         {
508                 QMessageBox::warning(this, tr("Not a File!"), tr("<nobr>Selected output file does not appear to be a valid file!</nobr>"));
509                 return;
510         }
511
512         //Is destination dir writable?
513         QFileInfo outputDir = QFileInfo(outputFile.absolutePath());
514         if(!(outputDir.exists() && outputDir.isDir() && outputDir.isWritable()))
515         {
516                 QMessageBox::warning(this, tr("Not Writable!"), tr("<nobr>Output directory does not exist or is not writable!</nobr>"));
517                 return;
518         }
519
520         //Custom parameters okay?
521         if(!ui->editCustomX264Params->hasAcceptableInput())
522         {
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;
525         }
526
527         //Update recently used
528         m_recentlyUsed->setFilterIndex(currentOutputIndx());
529         m_recentlyUsed->setSourceDirectory(currentSourcePath());
530         m_recentlyUsed->setOutputDirectory(currentOutputPath());
531         RecentlyUsed::saveRecentlyUsed(m_recentlyUsed);
532
533         //Save options
534         saveOptions(m_options);
535         QDialog::accept();
536 }
537
538 void AddJobDialog::browseButtonClicked(void)
539 {
540         if(QObject::sender() == ui->buttonBrowseSource)
541         {
542                 QString filePath = QFileDialog::getOpenFileName(this, tr("Open Source File"), currentSourcePath(true), getInputFilterLst(), NULL, QFileDialog::DontUseNativeDialog);
543                 if(!(filePath.isNull() || filePath.isEmpty()))
544                 {
545                         QString destFile = generateOutputFileName(filePath, currentOutputPath(), currentOutputIndx(), m_preferences->getSaveToSourcePath());
546                         ui->editSource->setText(QDir::toNativeSeparators(filePath));
547                         ui->editOutput->setText(QDir::toNativeSeparators(destFile));
548                 }
549         }
550         else if(QObject::sender() == ui->buttonBrowseOutput)
551         {
552                 QString selectedType = getFilterStr(currentOutputIndx());
553                 QString filePath = QFileDialog::getSaveFileName(this, tr("Choose Output File"), currentOutputPath(true), getFilterLst(), &selectedType, QFileDialog::DontUseNativeDialog | QFileDialog::DontConfirmOverwrite);
554
555                 if(!(filePath.isNull() || filePath.isEmpty()))
556                 {
557                         if(getFilterIdx(QFileInfo(filePath).suffix()) < 0)
558                         {
559                                 int tempIndex = -1;
560                                 QRegExp regExp("\\(\\*\\.(\\w+)\\)");
561                                 if(regExp.lastIndexIn(selectedType) >= 0)
562                                 {
563                                         tempIndex = getFilterIdx(regExp.cap(1));
564                                 }
565                                 if(tempIndex < 0)
566                                 {
567                                         tempIndex = m_recentlyUsed->filterIndex();
568                                 }
569                                 filePath = QString("%1.%2").arg(filePath, getFilterExt(tempIndex));
570                         }
571                         ui->editOutput->setText(QDir::toNativeSeparators(filePath));
572                 }
573         }
574 }
575
576 void AddJobDialog::configurationChanged(void)
577 {
578         const OptionsModel* options = reinterpret_cast<const OptionsModel*>(ui->cbxTemplate->itemData(ui->cbxTemplate->currentIndex()).value<const void*>());
579         if(options)
580         {
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);
585         }
586 }
587
588 void AddJobDialog::templateSelected(void)
589 {
590         const OptionsModel* options = reinterpret_cast<const OptionsModel*>(ui->cbxTemplate->itemData(ui->cbxTemplate->currentIndex()).value<const void*>());
591         if(options)
592         {
593                 qDebug("Loading options!");
594                 REMOVE_USAFED_ITEM;
595                 restoreOptions(options);
596         }
597
598         //Force updates
599         encoderIndexChanged(ui->cbxEncoderType->currentIndex());
600         variantIndexChanged(ui->cbxEncoderVariant->currentIndex());
601         modeIndexChanged(ui->cbxRateControlMode->currentIndex());
602 }
603
604 void AddJobDialog::saveTemplateButtonClicked(void)
605 {
606         qDebug("Saving template");
607         QString name = tr("New Template");
608         int n = 2;
609
610         while(OptionsModel::templateExists(name))
611         {
612                 name = tr("New Template (%1)").arg(QString::number(n++));
613         }
614
615         OptionsModel *options = new OptionsModel(m_sysinfo);
616         saveOptions(options);
617
618         if(options->equals(m_defaults))
619         {
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);
624                 REMOVE_USAFED_ITEM;
625                 X264_DELETE(options);
626                 return;
627         }
628
629         for(int i = 0; i < ui->cbxTemplate->count(); i++)
630         {
631                 const QString tempName = ui->cbxTemplate->itemText(i);
632                 if(tempName.contains('<') || tempName.contains('>'))
633                 {
634                         continue;
635                 }
636                 const OptionsModel* test = reinterpret_cast<const OptionsModel*>(ui->cbxTemplate->itemData(i).value<const void*>());
637                 if(test != NULL)
638                 {
639                         if(options->equals(test))
640                         {
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);
645                                 REMOVE_USAFED_ITEM;
646                                 X264_DELETE(options);
647                                 return;
648                         }
649                 }
650         }
651
652         forever
653         {
654                 bool ok = false;
655                 name = QInputDialog::getText(this, tr("Save Template"), tr("Please enter the name of the template:").leftJustified(144, ' '), QLineEdit::Normal, name, &ok).simplified();
656                 if(!ok)
657                 {
658                         X264_DELETE(options);
659                         return;
660                 }
661                 if(name.contains('<') || name.contains('>') || name.contains('\\') || name.contains('/') || name.contains('"'))
662                 {
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();
670                         continue;
671                 }
672                 if(OptionsModel::templateExists(name))
673                 {
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)
676                         {
677                                 continue;
678                         }
679                 }
680                 break;
681         }
682         
683         if(!OptionsModel::saveTemplate(options, name))
684         {
685                 QMessageBox::critical(this, tr("Save Failed"), tr("Sorry, the template could not be saved!"));
686                 X264_DELETE(options);
687                 return;
688         }
689         
690         int index = ui->cbxTemplate->model()->rowCount();
691         ui->cbxTemplate->blockSignals(true);
692         for(int i = 0; i < ui->cbxTemplate->count(); i++)
693         {
694                 if(ui->cbxTemplate->itemText(i).compare(name, Qt::CaseInsensitive) == 0)
695                 {
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);
701                 }
702         }
703         if(index >= 0)
704         {
705                 ui->cbxTemplate->insertItem(index, name, QVariant::fromValue<const void*>(options));
706                 ui->cbxTemplate->setCurrentIndex(index);
707         }
708         ui->cbxTemplate->blockSignals(false);
709
710         REMOVE_USAFED_ITEM;
711 }
712
713 void AddJobDialog::deleteTemplateButtonClicked(void)
714 {
715         const int index = ui->cbxTemplate->currentIndex();
716         QString name = ui->cbxTemplate->itemText(index);
717
718         if(name.contains('<') || name.contains('>') || name.contains('\\') || name.contains('/'))
719         {
720                 QMessageBox::warning (this, tr("Invalid Item"), tr("Sorry, the selected item cannot be deleted!"));
721                 return;
722         }
723
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)
726         {
727                 return;
728         }
729
730
731         OptionsModel::deleteTemplate(name);
732         const OptionsModel *item = reinterpret_cast<const OptionsModel*>(ui->cbxTemplate->itemData(index).value<const void*>());
733         ui->cbxTemplate->removeItem(index);
734         X264_DELETE(item);
735 }
736
737 void AddJobDialog::editorActionTriggered(void)
738 {
739
740         if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
741         {
742                 QLineEdit *lineEdit = reinterpret_cast<QLineEdit*>(action->data().value<void*>());
743                 
744                 EditorDialog *editor = new EditorDialog(this);
745                 editor->setEditText(lineEdit->text());
746
747                 if(editor->exec() == QDialog::Accepted)
748                 {
749                         lineEdit->setText(editor->getEditText());
750                 }
751
752                 X264_DELETE(editor);
753         }
754 }
755
756 void AddJobDialog::copyActionTriggered(void)
757 {
758         if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
759         {
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);
764         }
765 }
766
767 void AddJobDialog::pasteActionTriggered(void)
768 {
769         if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
770         {
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);
775         }
776 }
777
778 ///////////////////////////////////////////////////////////////////////////////
779 // Public functions
780 ///////////////////////////////////////////////////////////////////////////////
781
782 QString AddJobDialog::sourceFile(void)
783 {
784         return QDir::fromNativeSeparators(ui->editSource->text());
785 }
786
787 QString AddJobDialog::outputFile(void)
788 {
789         return QDir::fromNativeSeparators(ui->editOutput->text());
790 }
791
792 bool AddJobDialog::runImmediately(void)
793 {
794         return ui->checkBoxRun->isChecked();
795 }
796
797 bool AddJobDialog::applyToAll(void)
798 {
799         return ui->checkBoxApplyToAll->isChecked();
800 }
801
802 void AddJobDialog::setRunImmediately(bool run)
803 {
804         ui->checkBoxRun->setChecked(run);
805 }
806
807 void AddJobDialog::setSourceFile(const QString &path)
808 {
809         ui->editSource->setText(QDir::toNativeSeparators(path));
810 }
811
812 void AddJobDialog::setOutputFile(const QString &path)
813 {
814         ui->editOutput->setText(QDir::toNativeSeparators(path));}
815
816 void AddJobDialog::setSourceEditable(const bool editable)
817 {
818         ui->buttonBrowseSource->setEnabled(editable);
819 }
820
821 void AddJobDialog::setApplyToAllVisible(const bool visible)
822 {
823         ui->checkBoxApplyToAll->setVisible(visible);
824 }
825
826 ///////////////////////////////////////////////////////////////////////////////
827 // Private functions
828 ///////////////////////////////////////////////////////////////////////////////
829
830 void AddJobDialog::loadTemplateList(void)
831 {
832         ui->cbxTemplate->addItem(tr("<Default>"), QVariant::fromValue<const void*>(m_defaults));
833         ui->cbxTemplate->setCurrentIndex(0);
834
835         QMap<QString, OptionsModel*> templates = OptionsModel::loadAllTemplates(m_sysinfo);
836         QStringList templateNames = templates.keys();
837         templateNames.sort();
838
839         for(QStringList::ConstIterator current = templateNames.constBegin(); current != templateNames.constEnd(); current++)
840         {
841                 OptionsModel *currentTemplate = templates.take(*current);
842                 ui->cbxTemplate->addItem(*current, QVariant::fromValue<const void*>(currentTemplate));
843                 if(currentTemplate->equals(m_options))
844                 {
845                         ui->cbxTemplate->setCurrentIndex(ui->cbxTemplate->count() - 1);
846                 }
847         }
848
849         if((ui->cbxTemplate->currentIndex() == 0) && (!m_options->equals(m_defaults)))
850         {
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);
854         }
855 }
856
857 void AddJobDialog::updateComboBox(QComboBox *cbox, const QString &text)
858 {
859         int index = -1;
860         if(QAbstractItemModel *model = cbox->model())
861         {
862                 for(int i = 0; i < cbox->model()->rowCount(); i++)
863                 {
864                         if(model->data(model->index(i, 0, QModelIndex())).toString().compare(text, Qt::CaseInsensitive) == 0)
865                         {
866                                 index = i;
867                                 break;
868                         }
869                 }
870         }
871         cbox->setCurrentIndex(index);
872 }
873
874 void AddJobDialog::restoreOptions(const OptionsModel *options)
875 {
876         BLOCK_SIGNALS(true);
877
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());
889
890         BLOCK_SIGNALS(false);
891 }
892
893 void AddJobDialog::saveOptions(OptionsModel *options)
894 {
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());
906 }
907
908 QString AddJobDialog::currentSourcePath(const bool bWithName)
909 {
910         QString path = m_recentlyUsed->sourceDirectory();
911         QString currentSourceFile = this->sourceFile();
912         
913         if(!currentSourceFile.isEmpty())
914         {
915                 QString currentSourceDir = QFileInfo(currentSourceFile).absolutePath();
916                 if(VALID_DIR(currentSourceDir))
917                 {
918                         path = currentSourceDir;
919                 }
920                 if(bWithName)
921                 {
922                         path.append("/").append(QFileInfo(currentSourceFile).fileName());
923                 }
924         }
925
926         return path;
927 }
928
929 QString AddJobDialog::currentOutputPath(const bool bWithName)
930 {
931         QString path = m_recentlyUsed->outputDirectory();
932         QString currentOutputFile = this->outputFile();
933         
934         if(!currentOutputFile.isEmpty())
935         {
936                 QString currentOutputDir = QFileInfo(currentOutputFile).absolutePath();
937                 if(VALID_DIR(currentOutputDir))
938                 {
939                         path = currentOutputDir;
940                 }
941                 if(bWithName)
942                 {
943                         path.append("/").append(QFileInfo(currentOutputFile).fileName());
944                 }
945         }
946
947         return path;
948 }
949
950 int AddJobDialog::currentOutputIndx(void)
951 {
952         int index = m_recentlyUsed->filterIndex();
953         QString currentOutputFile = this->outputFile();
954         
955         if(!currentOutputFile.isEmpty())
956         {
957                 const QString currentOutputExtn = QFileInfo(currentOutputFile).suffix();
958                 const int tempIndex = getFilterIdx(currentOutputExtn);
959                 if(tempIndex >= 0)
960                 {
961                         index = tempIndex;
962                 }
963         }
964
965         return index;
966 }
967
968 ///////////////////////////////////////////////////////////////////////////////
969 // Static functions
970 ///////////////////////////////////////////////////////////////////////////////
971
972 QString AddJobDialog::generateOutputFileName(const QString &sourceFilePath, const QString &destinationDirectory, const int filterIndex, const bool saveToSourceDir)
973 {
974         QString name = QFileInfo(sourceFilePath).completeBaseName();
975         QString path = saveToSourceDir ? QFileInfo(sourceFilePath).canonicalPath() : destinationDirectory;
976         QString fext = getFilterExt(filterIndex);
977         
978         if(!VALID_DIR(path))
979         {
980                 RecentlyUsed defaults;
981                 path = defaults.outputDirectory();
982         }
983
984         QString outPath = QString("%1/%2.%3").arg(path, name, fext);
985
986         int n = 2;
987         while(QFileInfo(outPath).exists())
988         {
989                 outPath = QString("%1/%2 (%3).%4").arg(path, name, QString::number(n++), fext);
990         }
991
992         return outPath;
993 }
994
995 /* ------------------------------------------------------------------------- */
996
997 QString AddJobDialog::getFilterExt(const int filterIndex)
998 {
999         const int count = ARRAY_SIZE(X264_FILE_TYPE_FILTERS);
1000
1001         if((filterIndex >= 0) && (filterIndex < count))
1002         {
1003                 return QString::fromLatin1(X264_FILE_TYPE_FILTERS[filterIndex].pcExt);
1004         }
1005
1006         return QString::fromLatin1(X264_FILE_TYPE_FILTERS[0].pcExt);
1007 }
1008
1009 int AddJobDialog::getFilterIdx(const QString &fileExt)
1010 {
1011         const int count = ARRAY_SIZE(X264_FILE_TYPE_FILTERS);
1012
1013         for(int i = 0; i < count; i++)
1014         {
1015                 if(fileExt.compare(QString::fromLatin1(X264_FILE_TYPE_FILTERS[i].pcExt), Qt::CaseInsensitive) == 0)
1016                 {
1017                         return i;
1018                 }
1019         }
1020
1021         return -1;
1022 }
1023
1024 QString AddJobDialog::getFilterStr(const int filterIndex)
1025 {
1026         const int count = ARRAY_SIZE(X264_FILE_TYPE_FILTERS);
1027
1028         if((filterIndex >= 0) && (filterIndex < count))
1029         {
1030                 return QString("%1 (*.%2)").arg(QString::fromLatin1(X264_FILE_TYPE_FILTERS[filterIndex].pcStr), QString::fromLatin1(X264_FILE_TYPE_FILTERS[filterIndex].pcExt));
1031         }
1032
1033         return QString("%1 (*.%2)").arg(QString::fromLatin1(X264_FILE_TYPE_FILTERS[0].pcStr), QString::fromLatin1(X264_FILE_TYPE_FILTERS[0].pcExt));
1034 }
1035
1036 QString AddJobDialog::getFilterLst(void)
1037 {
1038         QStringList filters;
1039         const int count = ARRAY_SIZE(X264_FILE_TYPE_FILTERS);
1040         
1041         for(int i = 0; i < count; i++)
1042         {
1043                 filters << QString("%1 (*.%2)").arg(QString::fromLatin1(X264_FILE_TYPE_FILTERS[i].pcStr), QString::fromLatin1(X264_FILE_TYPE_FILTERS[i].pcExt));
1044         }
1045
1046         return filters.join(";;");
1047 }
1048
1049 QString AddJobDialog::getInputFilterLst(void)
1050 {
1051         static const struct
1052         {
1053                 const char *name;
1054                 const char *fext;
1055         }
1056         s_filters[] =
1057         {
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"},
1066         };
1067
1068         const int count = ARRAY_SIZE(s_filters);
1069
1070         QString allTypes;
1071         for(size_t index = 0; index < count; index++)
1072         {
1073
1074                 allTypes += QString((index > 0) ? " *.%1" : "*.%1").arg(QString::fromLatin1(s_filters[index].fext));
1075         }
1076         
1077         QStringList filters;
1078         filters << QString("All supported files (%1)").arg(allTypes);
1079
1080         for(size_t index = 0; index < count; index++)
1081         {
1082                 filters << QString("%1 (*.%2)").arg(QString::fromLatin1(s_filters[index].name), QString::fromLatin1(s_filters[index].fext));
1083         }
1084                 
1085         filters << QString("All files (*.*)");
1086         return filters.join(";;");
1087 }