123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817 |
- /*
- * Copyright (c) Contributors to the Open 3D Engine Project.
- * For complete copyright and license terms please see the LICENSE at the root of this distribution.
- *
- * SPDX-License-Identifier: Apache-2.0 OR MIT
- *
- */
- #include "EditorDefs.h"
- #include "AssetImporterManager.h"
- // Qt
- #include <QFileDialog>
- #include <QMessageBox>
- #include <QSettings>
- #include <QStandardPaths>
- // AzFramework
- #include <AzFramework/Asset/AssetSystemBus.h>
- // AzToolsFramework
- #include <AzToolsFramework/UI/UICore/WidgetHelpers.h>
- // Editor
- #include "AssetImporter/UI/FilesAlreadyExistDialog.h"
- namespace AssetImporterManagerPrivate
- {
- const char* g_selectFilesPath = "AssetImporter/SelectFilesPath";
- const char* g_selectDestinationFilesPath = "AssetImporter/SelectDestinationFilesPath";
- const char* g_errorMessageBoxTitle = "File failed to process.";
- const char* g_crateError = "Crate files cannot be imported.";
- static const char* s_crateFileExtension = "crate";
- };
- AssetImporterManager::AssetImporterManager(QWidget* parent)
- : QObject(parent)
- {
- }
- AssetImporterManager::~AssetImporterManager()
- {
- }
- void AssetImporterManager::Exec()
- {
- // tell the AssetImporterDragAndDropHandler that the Asset Importer now is running
- Q_EMIT StartAssetImporter();
- m_fileDialog = new QFileDialog;
- m_fileDialog->setFileMode(QFileDialog::ExistingFiles);
- m_fileDialog->setWindowModality(Qt::WindowModality::ApplicationModal);
- m_fileDialog->setViewMode(QFileDialog::Detail);
- m_fileDialog->setWindowTitle(tr("Select files to import"));
- m_fileDialog->setLabelText(QFileDialog::Accept, "Select");
- m_fileDialog->setAttribute(Qt::WA_DeleteOnClose);
- QSettings settings;
- m_currentAbsolutePath = settings.value(AssetImporterManagerPrivate::g_selectFilesPath).toString();
- QDir gameRoot(Path::GetEditingGameDataFolder().c_str());
- m_gameRootAbsPath = gameRoot.absolutePath();
- // Case 1: if currentAbsolutePath is empty at this point, that means this is the first time
- // users using the Asset Importer, set the default directory to be users' PC's desktop.
- // Case 2: if the current folder directory stored in the registry doesn't exist anymore,
- // that means users have removed the directory already (deleted or use the Move feature).
- // Case 3: if it's a directory under the game root folder, then in general,
- // users have modified the folder directory in the registry. It should not be happening.
- if (m_currentAbsolutePath.isEmpty() || !QFile(m_currentAbsolutePath).exists() ||
- m_currentAbsolutePath.startsWith(m_gameRootAbsPath, Qt::CaseInsensitive))
- {
- m_currentAbsolutePath = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation);
- }
- m_fileDialog->setDirectory(m_currentAbsolutePath);
- connect(m_fileDialog, &QFileDialog::rejected, [this]()
- {
- reject();
- });
- connect(m_fileDialog, &QDialog::accepted, [this]()
- {
- bool encounteredCrate = false;
- QStringList invalidFiles;
- for (const QString& path : m_fileDialog->selectedFiles())
- {
- QString fileName = GetFileName(path);
- QFileInfo info(path);
- QString extension = info.completeSuffix(); // extension without '.'
- if (QString(AssetImporterManagerPrivate::s_crateFileExtension).compare(extension, Qt::CaseInsensitive) != 0)
- {
- // prevent users from importing files under the game root directory
- if (path.startsWith(m_gameRootAbsPath, Qt::CaseInsensitive))
- {
- invalidFiles << fileName;
- }
- else
- {
- // store paths into the map.
- m_pathMap[path] = fileName;
- }
- }
- else
- {
- encounteredCrate = true;
- }
- }
- if (invalidFiles.size() > 0)
- {
- QString fileWarning =
- QString("Files cannot be imported into their own project. The following files will not be moved or copied:\n");
- fileWarning.append(invalidFiles.join(", "));
- fileWarning.append('.');
- QMessageBox::warning(AzToolsFramework::GetActiveWindow(), AssetImporterManagerPrivate::g_errorMessageBoxTitle, fileWarning);
- }
- if (encounteredCrate)
- {
- QMessageBox::warning(
- AzToolsFramework::GetActiveWindow(), AssetImporterManagerPrivate::g_errorMessageBoxTitle,
- AssetImporterManagerPrivate::g_crateError);
- }
- m_currentAbsolutePath = m_fileDialog->directory().absolutePath();
- QSettings settings;
- settings.setValue(AssetImporterManagerPrivate::g_selectFilesPath, m_currentAbsolutePath);
- // prevent users from selecting crate files from the File Explorer and open the Asset Importer.
- if (m_pathMap.size() > 0)
- {
- OnOpenSelectDestinationDialog();
- }
- });
- m_fileDialog->open();
- }
- void AssetImporterManager::Exec(const QStringList& dragAndDropFileList)
- {
- // note: dragging and dropping an empty folder can also trigger this condition
- if (!dragAndDropFileList.isEmpty())
- {
- OnDragAndDropFiles(&dragAndDropFileList);
- // only open the Asset Importer when the folder contains correct type files
- if (!m_pathMap.isEmpty())
- {
- // tell the AssetImporterDragAndDropHandler that the Asset Importer now is running
- Q_EMIT StartAssetImporter();
- OnOpenSelectDestinationDialog();
- }
- else
- {
- reject();
- }
- }
- }
- void AssetImporterManager::Exec(const QStringList& dragAndDropFileList, const QString& suggestedPath)
- {
- m_suggestedInitialPath = suggestedPath;
- Exec(dragAndDropFileList);
- }
- // used to cancel actions and close the dialog
- void AssetImporterManager::reject()
- {
- CompleteAssetImporting(false);
- }
- void AssetImporterManager::CompleteAssetImporting(bool wasSuccessful)
- {
- // Clear the pathMap to prevent trying to reimport assets later.
- m_pathMap.clear();
- m_destinationRootDirectory = "";
- // Inform listeners that we have completed the copy/move operation.
- if (wasSuccessful)
- {
- Q_EMIT AssetImportingComplete();
- }
- else
- {
- Q_EMIT StopAssetImporter();
- }
- }
- void AssetImporterManager::OnDragAndDropFiles(const QStringList* fileList)
- {
- for (int i = 0; i < fileList->size(); ++i)
- {
- // if the list contains a crate file,
- // the whole process should stop
- if (!GetAndCheckAllFilesInFolder(fileList->at(i)))
- {
- QMessageBox::warning(AzToolsFramework::GetActiveWindow(), AssetImporterManagerPrivate::g_errorMessageBoxTitle, AssetImporterManagerPrivate::g_crateError);
- reject();
- return;
- }
- }
- }
- void AssetImporterManager::OnBrowseDestinationFilePath(QLineEdit* destinationLineEdit)
- {
- QFileDialog fileDialog;
- fileDialog.setOption(QFileDialog::ShowDirsOnly, true);
- fileDialog.setViewMode(QFileDialog::List);
- fileDialog.setWindowModality(Qt::WindowModality::ApplicationModal);
- fileDialog.setWindowTitle(tr("Select import destination"));
- fileDialog.setFileMode(QFileDialog::Directory);
- QSettings settings;
- QString currentDestination = settings.value(AssetImporterManagerPrivate::g_selectDestinationFilesPath).toString();
- QDir gameRoot(Path::GetEditingGameDataFolder().c_str());
- QString gameRootAbsPath = gameRoot.absolutePath();
- // Case 1: if currentDestination is empty at this point, that means this is the first time
- // users using the Asset Importer, set the default directory to be the current game project's root folder
- // Case 2: if the current folder directory stored in the registry doesn't exist anymore,
- // that means users have removed the directory already (deleted or use the Move feature).
- // Case 3: if it's a directory outside of the game root folder, then in general,
- // users have modified the folder directory in the registry. It should not be happening.
- if (currentDestination.isEmpty() || !QDir(currentDestination).exists() || !currentDestination.startsWith(gameRootAbsPath, Qt::CaseInsensitive))
- {
- currentDestination = gameRootAbsPath;
- }
- fileDialog.setDirectory(currentDestination);
- // The default file path is the game project root folder.
- // After that, the default file path will be the previous opened folder path.
- connect(&fileDialog, &QFileDialog::directoryEntered, this, [&fileDialog, &gameRoot, &gameRootAbsPath](const QString& path)
- {
- // get current relative path
- QString relativePath = gameRoot.relativeFilePath(path);
- // Guard against navigating outside of the project folder. Lambda used as the dialog had to be captured.
- // checking the directory and prevent users from changing the directory outside of the game root
- if (!path.startsWith(gameRootAbsPath, Qt::CaseInsensitive) || (relativePath.length() > 2 && relativePath[0] == '.' && relativePath[1] == '.'))
- {
- fileDialog.setDirectory(gameRoot);
- }
- });
- if (!fileDialog.exec())
- {
- return;
- }
- // users can only select one folder at a time, so the index is always 0.
- // This fixes the issue that QFileDialog does not select the highlighted folder
- QString destinationDirectory = fileDialog.selectedFiles().at(0);
- OnSetDestinationDirectory(destinationDirectory);
- destinationLineEdit->setText(destinationDirectory);
- }
- // Copy + Paste
- void AssetImporterManager::OnCopyFiles()
- {
- m_importMethod = ImportFilesMethod::CopyFiles;
- ProcessCopyFiles();
- }
- // Cut + Paste
- void AssetImporterManager::OnMoveFiles()
- {
- m_importMethod = ImportFilesMethod::MoveFiles;
- ProcessMoveFiles();
- }
- bool AssetImporterManager::OnOverwriteFiles(QString relativePath, QString oldAbsolutePath)
- {
- // this is the absolute path in the destination folder
- QString destinationAbsolutePath = GenerateAbsolutePath(relativePath);
- return Overwrite(relativePath, oldAbsolutePath, destinationAbsolutePath);
- }
- bool AssetImporterManager::OnKeepBothFiles(QString relativePath, QString oldAbsolutePath)
- {
- // this is the absolute path in the destination folder
- QString destinationAbsolutePath = GenerateAbsolutePath(relativePath);
- QString subPath = QFileInfo(destinationAbsolutePath).absoluteDir().absolutePath();
- QFileInfo info(destinationAbsolutePath);
- QString extension = info.completeSuffix(); // extension without '.'
- QString fileName = info.baseName(); //file name without extension
- int number = 1;
- int index = destinationAbsolutePath.indexOf(extension);
- QString newFileName = CreateFileNameWithNumber(number, fileName, index, extension);
- QString newDestinationAbsolutePath = subPath + '/' + newFileName;
- while (QFile(newDestinationAbsolutePath).exists())
- {
- number++;
- newFileName = CreateFileNameWithNumber(number, fileName, index, extension);
- newDestinationAbsolutePath = subPath + '/' + newFileName;
- }
- if (m_importMethod == ImportFilesMethod::CopyFiles)
- {
- return Copy(relativePath, oldAbsolutePath, newDestinationAbsolutePath);
- }
- else if (m_importMethod == ImportFilesMethod::MoveFiles)
- {
- return Move(relativePath, oldAbsolutePath, newDestinationAbsolutePath);
- }
- return false;
- }
- void AssetImporterManager::OnOpenLogDialog()
- {
- AzFramework::AssetSystemRequestBus::Broadcast(&AzFramework::AssetSystem::AssetSystemRequests::ShowAssetProcessor);
- reject();
- }
- void AssetImporterManager::OnSetDestinationDirectory(QString destinationDirectory)
- {
- QSettings settings;
- QString currentDestination = settings.value(AssetImporterManagerPrivate::g_selectDestinationFilesPath).toString();
- m_destinationRootDirectory = (!destinationDirectory.isEmpty()) ? destinationDirectory : currentDestination;
- settings.setValue(AssetImporterManagerPrivate::g_selectDestinationFilesPath, destinationDirectory);
- }
- void AssetImporterManager::OnOpenSelectDestinationDialog()
- {
- QWidget* mainWindow = nullptr;
- AzToolsFramework::EditorRequestBus::BroadcastResult(mainWindow, &AzToolsFramework::EditorRequests::GetMainWindow);
- QString numberOfFilesMessage = m_pathMap.size() == 1 ? QString(tr("Importing 1 asset")) : QString(tr("Importing %1 assets").arg(m_pathMap.size()));
- SelectDestinationDialog selectDestinationDialog(numberOfFilesMessage, mainWindow, m_suggestedInitialPath);
- // Browse Destination File Path
- connect(&selectDestinationDialog, &SelectDestinationDialog::BrowseDestinationPath, this, &AssetImporterManager::OnBrowseDestinationFilePath);
- connect(&selectDestinationDialog, &SelectDestinationDialog::DoCopyFiles, this, &AssetImporterManager::OnCopyFiles);
- connect(&selectDestinationDialog, &SelectDestinationDialog::DoMoveFiles, this, &AssetImporterManager::OnMoveFiles);
- connect(&selectDestinationDialog, &SelectDestinationDialog::Cancel, this, &AssetImporterManager::reject);
- connect(&selectDestinationDialog, &SelectDestinationDialog::SetDestinationDirectory, this, &AssetImporterManager::OnSetDestinationDirectory);
- selectDestinationDialog.exec();
- }
- ProcessFilesMethod AssetImporterManager::OnOpenFilesAlreadyExistDialog(QString message, int numberOfFiles)
- {
- ProcessFilesMethod processMethod = ProcessFilesMethod::Default;
- // make sure the dialog is opened in front of the Editor main window
- QWidget* mainWindow = nullptr;
- AzToolsFramework::EditorRequestBus::BroadcastResult(mainWindow, &AzToolsFramework::EditorRequests::GetMainWindow);
- FilesAlreadyExistDialog filesAlreadyExistDialog(message, numberOfFiles, mainWindow);
- bool applyToAll = false;
- connect(&filesAlreadyExistDialog, &FilesAlreadyExistDialog::ApplyActionToAllFiles, this, [&applyToAll](bool result)
- {
- applyToAll = result;
- });
- connect(&filesAlreadyExistDialog, &FilesAlreadyExistDialog::OverWriteFiles, this, [this, &processMethod, &applyToAll]()
- {
- processMethod = UpdateProcessFileMethod(ProcessFilesMethod::OverwriteFile, applyToAll);
- });
- connect(&filesAlreadyExistDialog, &FilesAlreadyExistDialog::KeepBothFiles, this, [this, &processMethod, &applyToAll]()
- {
- processMethod = UpdateProcessFileMethod(ProcessFilesMethod::KeepBothFile, applyToAll);
- });
- connect(&filesAlreadyExistDialog, &FilesAlreadyExistDialog::SkipCurrentProcess, this, [this, &processMethod, &applyToAll]()
- {
- processMethod = UpdateProcessFileMethod(ProcessFilesMethod::SkipProcessingFile, applyToAll);
- });
- connect(&filesAlreadyExistDialog, &FilesAlreadyExistDialog::CancelAllProcesses, this, [&processMethod]()
- {
- processMethod = ProcessFilesMethod::Cancel;
- });
- if (!applyToAll && processMethod != ProcessFilesMethod::Cancel)
- {
- filesAlreadyExistDialog.exec();
- }
- return processMethod;
- }
- ProcessFilesMethod AssetImporterManager::UpdateProcessFileMethod(ProcessFilesMethod processMethod, bool applyToAll)
- {
- if (applyToAll)
- {
- switch (processMethod)
- {
- case ProcessFilesMethod::OverwriteFile:
- processMethod = ProcessFilesMethod::OverwriteAllFiles;
- break;
- case ProcessFilesMethod::KeepBothFile:
- processMethod = ProcessFilesMethod::KeepBothAllFiles;
- break;
- case ProcessFilesMethod::SkipProcessingFile:
- processMethod = ProcessFilesMethod::SkipProcessingAllFiles;
- }
- }
- return processMethod;
- }
- bool AssetImporterManager::ProcessFileMethod(ProcessFilesMethod processMethod, QString relativePath, QString oldAbsolutePath)
- {
- switch (processMethod)
- {
- case ProcessFilesMethod::OverwriteFile:
- case ProcessFilesMethod::OverwriteAllFiles:
- return OnOverwriteFiles(relativePath, oldAbsolutePath);
- case ProcessFilesMethod::KeepBothFile:
- case ProcessFilesMethod::KeepBothAllFiles:
- return OnKeepBothFiles(relativePath, oldAbsolutePath);
- case ProcessFilesMethod::SkipProcessingAllFiles:
- return false;
- }
- return false;
- }
- void AssetImporterManager::ProcessCopyFiles()
- {
- int numberOfFiles = m_pathMap.size();
- int numberOfProcessedFiles = 0;
- ProcessFilesMethod processMethod = ProcessFilesMethod::Default;
- for (int i = 0; i < m_pathMap.size(); ++i)
- {
- QString relativePath = m_pathMap.values().at(i);
- QString oldAbsolutePath = m_pathMap.keys().at(i);
- // this is the absolute path in the destination folder
- QString destinationAbsolutePath = GenerateAbsolutePath(relativePath);
- // check if the file exists in the destination folder
- if (!QFile::exists(destinationAbsolutePath))
- {
- if (Copy(relativePath, oldAbsolutePath, destinationAbsolutePath))
- {
- numberOfProcessedFiles++;
- }
- }
- else
- {
- if (processMethod == ProcessFilesMethod::Default ||
- processMethod == ProcessFilesMethod::OverwriteFile ||
- processMethod == ProcessFilesMethod::KeepBothFile ||
- processMethod == ProcessFilesMethod::SkipProcessingFile)
- {
- QString fileName = GetFileName(oldAbsolutePath);
- QString message = QString("The destination already has a file named \"%1\". What would you like to do?").arg(fileName);
- processMethod = OnOpenFilesAlreadyExistDialog(message, numberOfFiles);
- }
- if (ProcessFileMethod(processMethod, relativePath, oldAbsolutePath))
- {
- numberOfProcessedFiles++;
- }
- }
- numberOfFiles--;
- }
- if (numberOfProcessedFiles == 0)
- {
- reject();
- }
- else
- {
- CompleteAssetImporting();
- }
- }
- void AssetImporterManager::ProcessMoveFiles()
- {
- int numberOfFiles = m_pathMap.size();
- int numberOfProcessedFiles = 0;
- ProcessFilesMethod processMethod = ProcessFilesMethod::Default;
- for (int i = 0; i < m_pathMap.size(); ++i)
- {
- QString relativePath = m_pathMap.values().at(i);
- QString oldAbsolutePath = m_pathMap.keys().at(i);
- // this is the absolute path in the destination folder
- QString destinationAbsolutePath = GenerateAbsolutePath(relativePath);
- // check if the file exists in the destination folder
- if (!QFile::exists(destinationAbsolutePath))
- {
- if (Move(relativePath, oldAbsolutePath, destinationAbsolutePath))
- {
- numberOfProcessedFiles++;
- }
- }
- else
- {
- if (processMethod == ProcessFilesMethod::Default ||
- processMethod == ProcessFilesMethod::OverwriteFile ||
- processMethod == ProcessFilesMethod::KeepBothFile ||
- processMethod == ProcessFilesMethod::SkipProcessingFile)
- {
- QString fileName = GetFileName(oldAbsolutePath);
- QString message = QString("The destination already has a file named \"%1\". What would you like to do?").arg(fileName);
- processMethod = OnOpenFilesAlreadyExistDialog(message, numberOfFiles);
- }
- if (ProcessFileMethod(processMethod, relativePath, oldAbsolutePath))
- {
- numberOfProcessedFiles++;
- }
- }
- numberOfFiles--;
- }
- if (numberOfProcessedFiles == 0)
- {
- reject();
- }
- else
- {
- CompleteAssetImporting();
- }
- }
- bool AssetImporterManager::Copy(QString relativePath, QString oldAbsolutePath, QString destinationAbsolutePath)
- {
- QString fileName = GetFileName(destinationAbsolutePath);
- QString subPath = QFileInfo(destinationAbsolutePath).absoluteDir().absolutePath();
- QDir dir;
- bool directoryExistedAlready = QDir(subPath).exists();
- if (!directoryExistedAlready)
- {
- dir.mkpath(subPath);
- }
- QString newDestinationAbsolutePath = subPath;
- newDestinationAbsolutePath = newDestinationAbsolutePath.append('/' + fileName);
- // Copy the file from the old path to the new path
- if (!QFile::copy(oldAbsolutePath, newDestinationAbsolutePath))
- {
- QString reason = tr("an unknown issue occurred.");
- if (!directoryExistedAlready)
- {
- dir.rmdir(subPath);
- }
- // if the original files got deleted at this condition
- if (!QFile(oldAbsolutePath).exists())
- {
- reason = tr("%1 no longer exists.").arg(fileName);
- }
- // if users manually copy the file into the destination folder at this condition
- if (QFile(newDestinationAbsolutePath).exists())
- {
- reason = tr("%1 already exists in the target directory.").arg(fileName);
- }
- QMessageBox::critical(AzToolsFramework::GetActiveWindow(), AssetImporterManagerPrivate::g_errorMessageBoxTitle, QObject::tr("We're sorry, but the file failed to process because %1").arg(reason));
- return false;
- }
- // set the destination file to be writable by user himself/herself if it's read-only
- QFile destinationFile(newDestinationAbsolutePath);
- SetDestinationFileWritable(destinationFile);
- return true;
- }
- bool AssetImporterManager::Move(QString relativePath, QString oldAbsolutePath, QString destinationAbsolutePath)
- {
- QString fileName = GetFileName(destinationAbsolutePath);
- QString subPath = QFileInfo(destinationAbsolutePath).absoluteDir().absolutePath();
- QString newDestinationAbsolutePath = subPath;
- QDir dir;
- bool directoryExistedAlready = QDir(subPath).exists();
- if (!directoryExistedAlready)
- {
- dir.mkpath(subPath);
- }
- if (QFile::rename(oldAbsolutePath, newDestinationAbsolutePath.append('/' + fileName)))
- {
- QString oldFileName = GetFileName(oldAbsolutePath);
- // Only remove the old directory if the relative path is the file name itself.
- // That also means users are dragging and dropping files, but not a folder containing those files.
- if (oldFileName.compare(relativePath) != 0)
- {
- RemoveOldPath(oldAbsolutePath, relativePath);
- }
- // set the destination file to be writable by user himself/herself if it's read-only
- QFile destinationFile(newDestinationAbsolutePath);
- SetDestinationFileWritable(destinationFile);
- return true;
- }
- else
- {
- QString reason = tr("an unknown issue occurred.");
- QString oldFileName = GetFileName(oldAbsolutePath);
- if (!directoryExistedAlready)
- {
- dir.rmdir(subPath);
- }
- // if the original files got deleted at this condition
- if (!QFile(oldAbsolutePath).exists())
- {
- reason = tr("%1 no longer exists.").arg(oldFileName);
- }
- // if users manually copy the file into the destination folder at this condition
- if (QFile(newDestinationAbsolutePath).exists())
- {
- reason = tr("%1 already exists in the target directory.").arg(oldFileName);
- }
- QMessageBox::critical(AzToolsFramework::GetActiveWindow(), AssetImporterManagerPrivate::g_errorMessageBoxTitle, QObject::tr("We're sorry, but the file failed to process because %1").arg(reason));
- return false;
- }
- }
- bool AssetImporterManager::Overwrite(QString relativePath, QString oldAbsolutePath, QString destinationAbsolutePath)
- {
- QFile newFile(destinationAbsolutePath);
- QFile oldFile(oldAbsolutePath);
- // double check if paths are valid
- if ((!oldFile.open(QIODevice::ReadOnly)))
- {
- QString fileName = GetFileName(oldAbsolutePath);
- QString reason = tr("%1 no longer exists.").arg(fileName);
- QMessageBox::critical(AzToolsFramework::GetActiveWindow(), AssetImporterManagerPrivate::g_errorMessageBoxTitle, QObject::tr("We're sorry, but the file failed to process because %1").arg(reason));
- return false;
- }
- if (!newFile.open(QIODevice::WriteOnly | QIODevice::Truncate))
- {
- QString reason = tr("We're sorry, but the file failed to process.");
- QString fileName = GetFileName(destinationAbsolutePath);
- if (!newFile.exists())
- {
- reason = tr("%1 from the destination directory is removed.").arg(fileName);
- }
- else
- {
- reason = tr("%1 from the destination directory cannot be overwritten.").arg(fileName);
- }
- QMessageBox::critical(AzToolsFramework::GetActiveWindow(), AssetImporterManagerPrivate::g_errorMessageBoxTitle, QObject::tr("We're sorry, but the file failed to process because %1").arg(reason));
- return false;
- }
- QDataStream dataStream(&oldFile);
- QDataStream out(&newFile);
- int bufferSize = 1024 * 1024;
- char* buffer = new char[bufferSize];
- while (!dataStream.atEnd())
- {
- int bytesRead = dataStream.readRawData(buffer, bufferSize);
- out.writeRawData(buffer, bytesRead);
- }
- delete[] buffer;
- oldFile.close();
- newFile.close();
- // if it's the move file method, got to remove the original files
- if (m_importMethod == ImportFilesMethod::MoveFiles)
- {
- QString fileName = GetFileName(oldAbsolutePath);
- QFile file(oldAbsolutePath);
- QDir absoluteDir = QFileInfo(oldAbsolutePath).absoluteDir();
- if (file.exists())
- {
- // if the original file is read-only,
- // then it got to be writable in order to be deleted successfully
- SetDestinationFileWritable(file);
- absoluteDir.remove(fileName);
- }
- // Only remove the old directory if the relative path is the file name itself.
- // That also means users are dragging and dropping files, but not a folder containing those files.
- if (fileName.compare(relativePath) != 0)
- {
- RemoveOldPath(oldAbsolutePath, relativePath);
- }
- }
- return true;
- }
- bool AssetImporterManager::GetAndCheckAllFilesInFolder(QString path)
- {
- QString formattedPath = path;
- // Paths ending with '/' return from QFileInfo().fileName() with a value of ""
- // Strip a trailing slash so we can correctly get rootFolderName on all platforms
- if (formattedPath.endsWith("/"))
- {
- formattedPath.truncate(formattedPath.lastIndexOf(QChar('/')));
- }
- QString rootFolderName = GetFileName(formattedPath);
- QDirIterator it(formattedPath, QDir::NoDotAndDotDot | QDir::Files, QDirIterator::Subdirectories);
- QFileInfo info(formattedPath);
- if (!info.isDir() && !it.hasNext() && info.exists())
- {
- m_pathMap[formattedPath] = rootFolderName;
- return true;
- }
- // Get the index of the last sub folder name in the path
- QStringList directoryNameList = formattedPath.split('/');
- int lastFolderIndex = directoryNameList.size() - 1;
- QString pathToBeRelativeTo = directoryNameList.mid(0, lastFolderIndex).join('/');
- while (it.hasNext())
- {
- QString absolutePath = it.next();
- QFileInfo absoluteInfo(absolutePath);
- QString extension = absoluteInfo.completeSuffix();
- if (QString(AssetImporterManagerPrivate::s_crateFileExtension).compare(extension, Qt::CaseInsensitive) == 0)
- {
- return false;
- }
- Q_ASSERT(absolutePath.startsWith(pathToBeRelativeTo));
- QString relativePath = absolutePath.mid(pathToBeRelativeTo.size() + 1);
- m_pathMap[absolutePath] = relativePath;
- }
- return true;
- }
- void AssetImporterManager::RemoveOldPath(QString oldAbsolutePath, QString oldRelativePath)
- {
- QDir absoluteDir = QFileInfo(oldAbsolutePath).absoluteDir();
- QStringList directoryList = oldRelativePath.split('/');
- // remove each folder from the leave to the root, based on the relative path
- for (int i = 0; i < directoryList.size(); ++i)
- {
- QString currentDir = absoluteDir.path();
- absoluteDir.rmpath(currentDir);
- absoluteDir.cdUp();
- }
- }
- void AssetImporterManager::SetDestinationFileWritable(QFile& destinationFile)
- {
- if (destinationFile.open(QIODevice::ReadOnly))
- {
- destinationFile.setPermissions(QFile::WriteOwner | destinationFile.permissions());
- }
- destinationFile.close();
- }
- QString AssetImporterManager::CreateFileNameWithNumber(int number, QString fileName, int index, QString extension)
- {
- QString newFileName;
- newFileName = fileName.isEmpty() ? fileName : fileName.left(index);
- newFileName += "(" + QString::number(number) + ")";
- if (extension.size() > 0)
- {
- newFileName += "." + extension;
- }
- return newFileName;
- }
- QString AssetImporterManager::GenerateAbsolutePath(QString relativePath)
- {
- return QDir(m_destinationRootDirectory).absoluteFilePath(relativePath);
- }
- QString AssetImporterManager::GetFileName(QString path)
- {
- return QFileInfo(path).fileName();
- }
- #include <AssetImporter/AssetImporterManager/moc_AssetImporterManager.cpp>
|