Updated CueImportDialog and CueSheetModel as well as the CueSheet helper classes...
[LameXP.git] / src / Dialog_CueImport.cpp
blob94054cde8a924f92a38f2791a7e045c292864d70
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2013 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.
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 "Dialog_CueImport.h"
24 //UIC includes
25 #include "../tmp/UIC_CueSheetImport.h"
27 //LameXP includes
28 #include "Global.h"
29 #include "Model_CueSheet.h"
30 #include "Model_AudioFile.h"
31 #include "Model_FileList.h"
32 #include "Dialog_WorkingBanner.h"
33 #include "Thread_FileAnalyzer.h"
34 #include "Thread_CueSplitter.h"
35 #include "Registry_Decoder.h"
36 #include "LockedFile.h"
38 //Qt includes
39 #include <QFileInfo>
40 #include <QMessageBox>
41 #include <QTimer>
42 #include <QFileDialog>
43 #include <QProgressDialog>
44 #include <QMenu>
45 #include <QTextCodec>
46 #include <QInputDialog>
48 #define SET_FONT_BOLD(WIDGET,BOLD) { QFont _font = WIDGET->font(); _font.setBold(BOLD); WIDGET->setFont(_font); }
49 #define EXPAND(STR) QString(STR).leftJustified(96, ' ')
51 ////////////////////////////////////////////////////////////
52 // Constructor & Destructor
53 ////////////////////////////////////////////////////////////
55 CueImportDialog::CueImportDialog(QWidget *parent, FileListModel *fileList, const QString &cueFile, const SettingsModel *settings)
57 QDialog(parent),
58 ui(new Ui::CueSheetImport),
59 m_fileList(fileList),
60 m_cueFileName(cueFile),
61 m_settings(settings)
63 //Init the dialog, from the .ui file
64 ui->setupUi(this);
66 //Fix size
67 setMinimumSize(this->size());
68 setMaximumHeight(this->height());
70 //Create model
71 m_model = new CueSheetModel();
72 connect(m_model, SIGNAL(modelReset()), this, SLOT(modelChanged()));
74 //Setup table view
75 ui->treeView->setModel(m_model);
76 ui->treeView->header()->setStretchLastSection(false);
77 ui->treeView->header()->setResizeMode(QHeaderView::ResizeToContents);
78 ui->treeView->header()->setResizeMode(1, QHeaderView::Stretch);
79 ui->treeView->header()->setMovable(false);
80 ui->treeView->setItemsExpandable(false);
82 //Enable up/down button
83 connect(ui->imprtButton, SIGNAL(clicked()), this, SLOT(importButtonClicked()));
84 connect(ui->browseButton, SIGNAL(clicked()), this, SLOT(browseButtonClicked()));
85 connect(ui->loadOtherButton, SIGNAL(clicked()), this, SLOT(loadOtherButtonClicked()));
87 //Translate
88 ui->labelHeaderText->setText(QString("<b>%1</b><br>%2").arg(tr("Import Cue Sheet"), tr("The following Cue Sheet will be split and imported into LameXP.")));
91 CueImportDialog::~CueImportDialog(void)
93 LAMEXP_DELETE(m_model);
94 LAMEXP_DELETE(ui);
97 ////////////////////////////////////////////////////////////
98 // EVENTS
99 ////////////////////////////////////////////////////////////
101 void CueImportDialog::showEvent(QShowEvent *event)
103 QDialog::showEvent(event);
104 modelChanged();
107 ////////////////////////////////////////////////////////////
108 // Slots
109 ////////////////////////////////////////////////////////////
111 int CueImportDialog::exec(void)
113 WorkingBanner *progress = new WorkingBanner(dynamic_cast<QWidget*>(parent()));
114 progress->show(tr("Loading Cue Sheet file, please be patient..."));
116 QFileInfo cueFileInfo(m_cueFileName);
117 if(!cueFileInfo.exists() || !cueFileInfo.isFile())
119 QString text = QString("<nobr>%1</nobr><br><nobr>%2</nobr><br><br><nobr>%3</nobr>").arg(tr("Failed to load the Cue Sheet file:"), QDir::toNativeSeparators(m_cueFileName), tr("The specified file could not be found!")).replace("-", "&minus;");
120 QMessageBox::warning(progress, tr("Cue Sheet Error"), text);
121 progress->close();
122 LAMEXP_DELETE(progress);
123 return CueSheetModel::ErrorIOFailure;
126 //----------------------//
128 QTextCodec *codec = NULL;
130 QFile cueFile(cueFileInfo.canonicalFilePath());
131 cueFile.open(QIODevice::ReadOnly);
132 QByteArray bomCheck = cueFile.isOpen() ? cueFile.peek(16) : QByteArray();
134 if((!bomCheck.isEmpty()) && bomCheck.startsWith("\xef\xbb\xbf"))
136 codec = QTextCodec::codecForName("UTF-8");
138 else if((!bomCheck.isEmpty()) && bomCheck.startsWith("\xff\xfe"))
140 codec = QTextCodec::codecForName("UTF-16LE");
142 else if((!bomCheck.isEmpty()) && bomCheck.startsWith("\xfe\xff"))
144 codec = QTextCodec::codecForName("UTF-16BE");
146 else
148 const QString systemDefault = tr("(System Default)");
150 QStringList codecList;
151 codecList.append(systemDefault);
152 codecList.append(lamexp_available_codepages());
154 QInputDialog *input = new QInputDialog(progress);
155 input->setLabelText(EXPAND(tr("Select ANSI Codepage for Cue Sheet file:")));
156 input->setOkButtonText(tr("OK"));
157 input->setCancelButtonText(tr("Cancel"));
158 input->setTextEchoMode(QLineEdit::Normal);
159 input->setComboBoxItems(codecList);
161 if(input->exec() < 1)
163 progress->close();
164 LAMEXP_DELETE(input);
165 LAMEXP_DELETE(progress);
166 return Rejected;
169 if(input->textValue().compare(systemDefault, Qt::CaseInsensitive))
171 qDebug("User-selected codec is: %s", input->textValue().toLatin1().constData());
172 codec = QTextCodec::codecForName(input->textValue().toLatin1().constData());
174 else
176 qDebug("Going to use the system's default codec!");
177 codec = QTextCodec::codecForName("System");
180 LAMEXP_DELETE(input);
183 bomCheck.clear();
185 //----------------------//
187 QString baseName = cueFileInfo.completeBaseName().simplified();
188 while(baseName.endsWith(".") || baseName.endsWith(" ")) baseName.chop(1);
189 if(baseName.isEmpty()) baseName = tr("New Folder");
191 m_outputDir = QString("%1/%2").arg(cueFileInfo.canonicalPath(), baseName);
192 for(int n = 2; QDir(m_outputDir).exists() || QFileInfo(m_outputDir).exists(); n++)
194 m_outputDir = QString("%1/%2 (%3)").arg(cueFileInfo.canonicalPath(), baseName, QString::number(n));
197 setWindowTitle(QString("%1: %2").arg(windowTitle().split(":", QString::SkipEmptyParts).first().trimmed(), cueFileInfo.fileName()));
199 int iResult = m_model->loadCueSheet(m_cueFileName, QApplication::instance(), codec);
200 if(iResult != CueSheetModel::ErrorSuccess)
202 QString errorMsg = tr("An unknown error has occured!");
204 switch(iResult)
206 case CueSheetModel::ErrorIOFailure:
207 errorMsg = tr("The file could not be opened for reading. Make sure you have the required rights!");
208 break;
209 case CueSheetModel::ErrorBadFile:
210 errorMsg = tr("The provided file does not look like a valid Cue Sheet disc image file!");
211 break;
212 case CueSheetModel::ErrorUnsupported:
213 errorMsg = QString("%1<br>%2").arg(tr("Could not find any supported audio track in the Cue Sheet image!"), tr("Note that LameXP can not handle \"binary\" Cue Sheet images."));
214 break;
215 case CueSheetModel::ErrorInconsistent:
216 errorMsg = tr("The selected Cue Sheet file contains inconsistent information. Take care!");
217 break;
220 QString text = QString("<nobr>%1</nobr><br><nobr>%2</nobr><br><br><nobr>%3</nobr>").arg(tr("Failed to load the Cue Sheet file:"), QDir::toNativeSeparators(m_cueFileName), errorMsg).replace("-", "&minus;");
221 QMessageBox::warning(progress, tr("Cue Sheet Error"), text);
222 progress->close();
223 LAMEXP_DELETE(progress);
224 return iResult;
227 progress->close();
228 LAMEXP_DELETE(progress);
229 return QDialog::exec();
232 void CueImportDialog::modelChanged(void)
234 ui->treeView->expandAll();
235 ui->editOutputDir->setText(QDir::toNativeSeparators(m_outputDir));
236 if(const AudioFileModel_MetaInfo *albumInfo = m_model->getAlbumInfo())
238 ui->labelArtist->setText(albumInfo->artist().isEmpty() ? tr("Unknown Artist") : albumInfo->artist());
239 ui->labelAlbum->setText(albumInfo->album().isEmpty() ? tr("Unknown Album") : albumInfo->album());
243 void CueImportDialog::browseButtonClicked(void)
245 QString newOutDir, currentDir = m_outputDir;
247 while(QDir(currentDir).exists())
249 int pos = qMax(currentDir.lastIndexOf(QChar('\\')), currentDir.lastIndexOf(QChar('/')));
250 if(pos > 0) currentDir.left(pos - 1); else break;
253 if(lamexp_themes_enabled())
255 newOutDir = QFileDialog::getExistingDirectory(this, tr("Choose Output Directory"), currentDir);
257 else
259 QFileDialog dialog(this, tr("Choose Output Directory"));
260 dialog.setFileMode(QFileDialog::DirectoryOnly);
261 dialog.setDirectory(currentDir);
262 if(dialog.exec())
264 newOutDir = dialog.selectedFiles().first();
268 if(!newOutDir.isEmpty())
270 m_outputDir = newOutDir;
271 modelChanged();
275 void CueImportDialog::importButtonClicked(void)
277 static const unsigned __int64 oneGigabyte = 1073741824ui64;
278 static const unsigned __int64 minimumFreeDiskspaceMultiplier = 2ui64;
279 static const char *writeTestBuffer = "LAMEXP_WRITE_TEST";
281 QDir outputDir(m_outputDir);
282 outputDir.mkpath(".");
283 if(!(outputDir.exists() && outputDir.isReadable()))
285 QMessageBox::warning(this, tr("LameXP"), QString("<nobr>%2</nobr>").arg(tr("Error: The selected output directory could not be created!")));
286 return;
289 QFile writeTest(QString("%1/~%2.txt").arg(m_outputDir, lamexp_rand_str()));
290 if(!(writeTest.open(QIODevice::ReadWrite) && (writeTest.write(writeTestBuffer) == strlen(writeTestBuffer))))
292 QMessageBox::warning(this, tr("LameXP"), QString("<nobr>%2</nobr>").arg(tr("Error: The selected output directory is not writable!")));
293 return;
295 else
297 writeTest.close();
298 writeTest.remove();
301 bool ok = false;
302 unsigned __int64 currentFreeDiskspace = lamexp_free_diskspace(m_outputDir, &ok);
304 if(ok && (currentFreeDiskspace < (oneGigabyte * minimumFreeDiskspaceMultiplier)))
306 QMessageBox::warning(this, tr("Low Diskspace Warning"), QString("<nobr>%1</nobr><br><nobr>%2</nobr>").arg(tr("There are less than %1 GB of free diskspace available in the selected output directory.").arg(QString::number(minimumFreeDiskspaceMultiplier)), tr("It is highly recommend to free up more diskspace before proceeding with the import!")));
307 return;
310 importCueSheet();
311 accept();
314 void CueImportDialog::loadOtherButtonClicked(void)
316 done(-1);
319 void CueImportDialog::analyzedFile(const AudioFileModel &file)
321 qDebug("Received result: <%s> <%s/%s>", file.filePath().toLatin1().constData(), file.techInfo().containerType().toLatin1().constData(), file.techInfo().audioType().toLatin1().constData());
322 m_fileInfo << file;
325 ////////////////////////////////////////////////////////////
326 // Private Functions
327 ////////////////////////////////////////////////////////////
329 void CueImportDialog::importCueSheet(void)
331 QStringList files;
333 //Fetch all files that are referenced in the Cue Sheet and lock them
334 int nFiles = m_model->getFileCount();
335 for(int i = 0; i < nFiles; i++)
337 QString temp = m_model->getFileName(i);
340 m_locks << new LockedFile(temp);
342 catch(char *err)
344 qWarning("Failed to lock file: %s", err);
345 continue;
347 files << temp;
350 //Analyze all source files first
351 if(analyzeFiles(files))
353 //Now split files according to Cue Sheet
354 splitFiles();
357 //Release locks
358 while(!m_locks.isEmpty())
360 delete m_locks.takeFirst();
364 bool CueImportDialog::analyzeFiles(QStringList &files)
366 m_fileInfo.clear();
367 bool bSuccess = true;
369 WorkingBanner *progress = new WorkingBanner(this);
370 FileAnalyzer *analyzer = new FileAnalyzer(files);
372 connect(analyzer, SIGNAL(fileSelected(QString)), progress, SLOT(setText(QString)), Qt::QueuedConnection);
373 connect(analyzer, SIGNAL(fileAnalyzed(AudioFileModel)), this, SLOT(analyzedFile(AudioFileModel)), Qt::QueuedConnection);
374 connect(progress, SIGNAL(userAbort()), analyzer, SLOT(abortProcess()), Qt::DirectConnection);
376 progress->show(tr("Analyzing file(s), please wait..."), analyzer);
377 progress->close();
379 if(analyzer->filesAccepted() < static_cast<unsigned int>(files.count()))
381 if(QMessageBox::warning(this, tr("Analysis Failed"), tr("Warning: The format of some of the input files could not be determined!"), tr("Continue Anyway"), tr("Abort")) == 1)
383 bSuccess = false;
387 LAMEXP_DELETE(progress);
388 LAMEXP_DELETE(analyzer);
390 return bSuccess;
393 void CueImportDialog::splitFiles(void)
395 QString baseName = QFileInfo(m_cueFileName).completeBaseName().replace(".", " ").simplified();
397 WorkingBanner *progress = new WorkingBanner(this);
398 CueSplitter *splitter = new CueSplitter(m_outputDir, baseName, m_model, m_fileInfo);
400 connect(splitter, SIGNAL(fileSelected(QString)), progress, SLOT(setText(QString)), Qt::QueuedConnection);
401 connect(splitter, SIGNAL(fileSplit(AudioFileModel)), m_fileList, SLOT(addFile(AudioFileModel)), Qt::QueuedConnection);
402 connect(splitter, SIGNAL(progressValChanged(unsigned int)), progress, SLOT(setProgressVal(unsigned int)), Qt::QueuedConnection);
403 connect(splitter, SIGNAL(progressMaxChanged(unsigned int)), progress, SLOT(setProgressMax(unsigned int)), Qt::QueuedConnection);
404 connect(progress, SIGNAL(userAbort()), splitter, SLOT(abortProcess()), Qt::DirectConnection);
406 DecoderRegistry::configureDecoders(m_settings);
408 progress->show(tr("Splitting file(s), please wait..."), splitter);
409 progress->close();
411 if(splitter->getAborted())
413 QMessageBox::warning(this, tr("Cue Sheet Error"), tr("Process was aborted by the user after %n track(s)!", "", splitter->getTracksSuccess()));
415 else if(!splitter->getSuccess())
417 QMessageBox::warning(this, tr("Cue Sheet Error"), tr("An unexpected error has occured while splitting the Cue Sheet!"));
419 else
421 QString text = QString("<nobr>%1 %2</nobr>").arg(tr("Imported %n track(s) from the Cue Sheet.", "", splitter->getTracksSuccess()), tr("Skipped %n track(s).", "", splitter->getTracksSkipped()));
422 QMessageBox::information(this, tr("Cue Sheet Completed"), text);
425 LAMEXP_DELETE(splitter);
426 LAMEXP_DELETE(progress);