1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2012 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 "Dialog_CueImport.h"
25 #include "Model_CueSheet.h"
26 #include "Model_AudioFile.h"
27 #include "Model_FileList.h"
28 #include "Dialog_WorkingBanner.h"
29 #include "Thread_FileAnalyzer.h"
30 #include "Thread_CueSplitter.h"
31 #include "LockedFile.h"
34 #include <QMessageBox>
36 #include <QFileDialog>
37 #include <QProgressDialog>
40 #include <QInputDialog>
42 #define SET_FONT_BOLD(WIDGET,BOLD) { QFont _font = WIDGET->font(); _font.setBold(BOLD); WIDGET->setFont(_font); }
43 #define EXPAND(STR) QString(STR).leftJustified(96, ' ')
45 ////////////////////////////////////////////////////////////
46 // Constructor & Destructor
47 ////////////////////////////////////////////////////////////
49 CueImportDialog::CueImportDialog(QWidget
*parent
, FileListModel
*fileList
, const QString
&cueFile
)
52 m_cueFileName(cueFile
),
55 //Init the dialog, from the .ui file
59 setMinimumSize(this->size());
60 setMaximumHeight(this->height());
63 m_model
= new CueSheetModel();
64 connect(m_model
, SIGNAL(modelReset()), this, SLOT(modelChanged()));
67 treeView
->setModel(m_model
);
68 treeView
->header()->setStretchLastSection(false);
69 treeView
->header()->setResizeMode(QHeaderView::ResizeToContents
);
70 treeView
->header()->setResizeMode(1, QHeaderView::Stretch
);
71 treeView
->header()->setMovable(false);
72 treeView
->setItemsExpandable(false);
74 //Enable up/down button
75 connect(imprtButton
, SIGNAL(clicked()), this, SLOT(importButtonClicked()));
76 connect(browseButton
, SIGNAL(clicked()), this, SLOT(browseButtonClicked()));
77 connect(loadOtherButton
, SIGNAL(clicked()), this, SLOT(loadOtherButtonClicked()));
80 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.")));
83 CueImportDialog::~CueImportDialog(void)
85 LAMEXP_DELETE(m_model
);
88 ////////////////////////////////////////////////////////////
90 ////////////////////////////////////////////////////////////
92 void CueImportDialog::showEvent(QShowEvent
*event
)
94 QDialog::showEvent(event
);
98 ////////////////////////////////////////////////////////////
100 ////////////////////////////////////////////////////////////
102 int CueImportDialog::exec(void)
104 WorkingBanner
*progress
= new WorkingBanner(dynamic_cast<QWidget
*>(parent()));
105 progress
->show(tr("Loading Cue Sheet file, please be patient..."));
107 QFileInfo
cueFileInfo(m_cueFileName
);
108 if(!cueFileInfo
.exists() || !cueFileInfo
.isFile())
110 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("-", "−");
111 QMessageBox::warning(progress
, tr("Cue Sheet Error"), text
);
113 LAMEXP_DELETE(progress
);
114 return CueSheetModel::ErrorIOFailure
;
117 //----------------------//
119 QTextCodec
*codec
= NULL
;
121 QFile
cueFile(cueFileInfo
.canonicalFilePath());
122 cueFile
.open(QIODevice::ReadOnly
);
123 QByteArray bomCheck
= cueFile
.isOpen() ? cueFile
.peek(16) : QByteArray();
125 if((!bomCheck
.isEmpty()) && bomCheck
.startsWith("\xef\xbb\xbf"))
127 codec
= QTextCodec::codecForName("UTF-8");
129 else if((!bomCheck
.isEmpty()) && bomCheck
.startsWith("\xff\xfe"))
131 codec
= QTextCodec::codecForName("UTF-16LE");
133 else if((!bomCheck
.isEmpty()) && bomCheck
.startsWith("\xfe\xff"))
135 codec
= QTextCodec::codecForName("UTF-16BE");
139 const QString systemDefault
= tr("(System Default)");
141 QStringList codecList
;
142 codecList
.append(systemDefault
);
143 codecList
.append(lamexp_available_codepages());
145 QInputDialog
*input
= new QInputDialog(progress
);
146 input
->setLabelText(EXPAND(tr("Select ANSI Codepage for Cue Sheet file:")));
147 input
->setOkButtonText(tr("OK"));
148 input
->setCancelButtonText(tr("Cancel"));
149 input
->setTextEchoMode(QLineEdit::Normal
);
150 input
->setComboBoxItems(codecList
);
152 if(input
->exec() < 1)
155 LAMEXP_DELETE(input
);
156 LAMEXP_DELETE(progress
);
160 if(input
->textValue().compare(systemDefault
, Qt::CaseInsensitive
))
162 qDebug("User-selected codec is: %s", input
->textValue().toLatin1().constData());
163 codec
= QTextCodec::codecForName(input
->textValue().toLatin1().constData());
167 qDebug("Going to use the system's default codec!");
168 codec
= QTextCodec::codecForName("System");
171 LAMEXP_DELETE(input
);
176 //----------------------//
178 m_outputDir
= QString("%1/%2").arg(cueFileInfo
.canonicalPath(), cueFileInfo
.completeBaseName());
179 for(int n
= 2; QDir(m_outputDir
).exists(); n
++)
181 m_outputDir
= QString("%1/%2 (%3)").arg(cueFileInfo
.canonicalPath(), cueFileInfo
.completeBaseName(), QString::number(n
));
184 setWindowTitle(QString("%1: %2").arg(windowTitle().split(":", QString::SkipEmptyParts
).first().trimmed(), cueFileInfo
.fileName()));
186 int iResult
= m_model
->loadCueSheet(m_cueFileName
, QApplication::instance(), codec
);
187 if(iResult
!= CueSheetModel::ErrorSuccess
)
189 QString errorMsg
= tr("An unknown error has occured!");
193 case CueSheetModel::ErrorIOFailure
:
194 errorMsg
= tr("The file could not be opened for reading. Make sure you have the required rights!");
196 case CueSheetModel::ErrorBadFile
:
197 errorMsg
= tr("The provided file does not look like a valid Cue Sheet disc image file!");
199 case CueSheetModel::ErrorUnsupported
:
200 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."));
202 case CueSheetModel::ErrorInconsistent
:
203 errorMsg
= tr("The selected Cue Sheet file contains inconsistent information. Take care!");
207 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("-", "−");
208 QMessageBox::warning(progress
, tr("Cue Sheet Error"), text
);
210 LAMEXP_DELETE(progress
);
215 LAMEXP_DELETE(progress
);
216 return QDialog::exec();
219 void CueImportDialog::modelChanged(void)
221 treeView
->expandAll();
222 editOutputDir
->setText(QDir::toNativeSeparators(m_outputDir
));
223 labelArtist
->setText(m_model
->getAlbumPerformer().isEmpty() ? tr("Unknown Artist") : m_model
->getAlbumPerformer());
224 labelAlbum
->setText(m_model
->getAlbumTitle().isEmpty() ? tr("Unknown Album") : m_model
->getAlbumTitle());
227 void CueImportDialog::browseButtonClicked(void)
229 QString newOutDir
, currentDir
= m_outputDir
;
231 while(QDir(currentDir
).exists())
233 int pos
= qMax(currentDir
.lastIndexOf(QChar('\\')), currentDir
.lastIndexOf(QChar('/')));
234 if(pos
> 0) currentDir
.left(pos
- 1); else break;
237 if(lamexp_themes_enabled() || ((QSysInfo::windowsVersion() & QSysInfo::WV_NT_based
) < QSysInfo::WV_XP
))
239 newOutDir
= QFileDialog::getExistingDirectory(this, tr("Choose Output Directory"), currentDir
);
243 QFileDialog
dialog(this, tr("Choose Output Directory"));
244 dialog
.setFileMode(QFileDialog::DirectoryOnly
);
245 dialog
.setDirectory(currentDir
);
248 newOutDir
= dialog
.selectedFiles().first();
252 if(!newOutDir
.isEmpty())
254 m_outputDir
= newOutDir
;
259 void CueImportDialog::importButtonClicked(void)
261 static const unsigned __int64 oneGigabyte
= 1073741824ui
64;
262 static const unsigned __int64 minimumFreeDiskspaceMultiplier
= 2ui
64;
263 static const char *writeTestBuffer
= "LAMEXP_WRITE_TEST";
265 QDir
outputDir(m_outputDir
);
266 outputDir
.mkpath(".");
267 if(!(outputDir
.exists() && outputDir
.isReadable()))
269 QMessageBox::warning(this, tr("LameXP"), QString("<nobr>%2</nobr>").arg(tr("Error: The selected output directory could not be created!")));
273 QFile
writeTest(QString("%1/~%2.txt").arg(m_outputDir
, lamexp_rand_str()));
274 if(!(writeTest
.open(QIODevice::ReadWrite
) && (writeTest
.write(writeTestBuffer
) == strlen(writeTestBuffer
))))
276 QMessageBox::warning(this, tr("LameXP"), QString("<nobr>%2</nobr>").arg(tr("Error: The selected output directory is not writable!")));
286 unsigned __int64 currentFreeDiskspace
= lamexp_free_diskspace(m_outputDir
, &ok
);
288 if(ok
&& (currentFreeDiskspace
< (oneGigabyte
* minimumFreeDiskspaceMultiplier
)))
290 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!")));
298 void CueImportDialog::loadOtherButtonClicked(void)
303 void CueImportDialog::analyzedFile(const AudioFileModel
&file
)
305 qDebug("Received result: <%s> <%s/%s>", file
.filePath().toLatin1().constData(), file
.formatContainerType().toLatin1().constData(), file
.formatAudioType().toLatin1().constData());
309 ////////////////////////////////////////////////////////////
311 ////////////////////////////////////////////////////////////
313 void CueImportDialog::importCueSheet(void)
317 //Fetch all files that are referenced in the Cue Sheet and lock them
318 int nFiles
= m_model
->getFileCount();
319 for(int i
= 0; i
< nFiles
; i
++)
321 QString temp
= m_model
->getFileName(i
);
324 m_locks
<< new LockedFile(temp
);
328 qWarning("Failed to lock file: %s", err
);
334 //Analyze all source files first
335 if(analyzeFiles(files
))
337 //Now split files according to Cue Sheet
342 while(!m_locks
.isEmpty())
344 delete m_locks
.takeFirst();
348 bool CueImportDialog::analyzeFiles(QStringList
&files
)
351 bool bSuccess
= true;
353 WorkingBanner
*progress
= new WorkingBanner(this);
354 FileAnalyzer
*analyzer
= new FileAnalyzer(files
);
356 connect(analyzer
, SIGNAL(fileSelected(QString
)), progress
, SLOT(setText(QString
)), Qt::QueuedConnection
);
357 connect(analyzer
, SIGNAL(fileAnalyzed(AudioFileModel
)), this, SLOT(analyzedFile(AudioFileModel
)), Qt::QueuedConnection
);
358 connect(progress
, SIGNAL(userAbort()), analyzer
, SLOT(abortProcess()), Qt::DirectConnection
);
360 progress
->show(tr("Analyzing file(s), please wait..."), analyzer
);
363 if(analyzer
->filesAccepted() < static_cast<unsigned int>(files
.count()))
365 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)
371 LAMEXP_DELETE(progress
);
372 LAMEXP_DELETE(analyzer
);
377 void CueImportDialog::splitFiles(void)
379 QString baseName
= QFileInfo(m_cueFileName
).completeBaseName().replace(".", " ").simplified();
381 WorkingBanner
*progress
= new WorkingBanner(this);
382 CueSplitter
*splitter
= new CueSplitter(m_outputDir
, baseName
, m_model
, m_fileInfo
);
384 connect(splitter
, SIGNAL(fileSelected(QString
)), progress
, SLOT(setText(QString
)), Qt::QueuedConnection
);
385 connect(splitter
, SIGNAL(fileSplit(AudioFileModel
)), m_fileList
, SLOT(addFile(AudioFileModel
)), Qt::QueuedConnection
);
386 connect(progress
, SIGNAL(userAbort()), splitter
, SLOT(abortProcess()), Qt::DirectConnection
);
388 progress
->show(tr("Splitting file(s), please wait..."), splitter
);
391 if(splitter
->getAborted())
393 QMessageBox::warning(this, tr("Cue Sheet Error"), tr("Process was aborted by the user after %1 track(s)!").arg(QString::number(splitter
->getTracksSuccess())));
395 else if(!splitter
->getSuccess())
397 QMessageBox::warning(this, tr("Cue Sheet Error"), tr("An unexpected error has occured while splitting the Cue Sheet!"));
401 QString text
= QString("<nobr>%1</nobr>").arg(tr("Imported %1 track(s) from the Cue Sheet and skipped %2 track(s).").arg(QString::number(splitter
->getTracksSuccess()), QString::number(splitter
->getTracksSkipped() /*+ nTracksSkipped*/)));
402 QMessageBox::information(this, tr("Cue Sheet Completed"), text
);
405 LAMEXP_DELETE(splitter
);
406 LAMEXP_DELETE(progress
);