AssetImporterManager.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. #include "EditorDefs.h"
  9. #include "AssetImporterManager.h"
  10. // Qt
  11. #include <QFileDialog>
  12. #include <QMessageBox>
  13. #include <QSettings>
  14. #include <QStandardPaths>
  15. // AzFramework
  16. #include <AzFramework/Asset/AssetSystemBus.h>
  17. // AzToolsFramework
  18. #include <AzToolsFramework/UI/UICore/WidgetHelpers.h>
  19. // Editor
  20. #include "AssetImporter/UI/FilesAlreadyExistDialog.h"
  21. namespace AssetImporterManagerPrivate
  22. {
  23. const char* g_selectFilesPath = "AssetImporter/SelectFilesPath";
  24. const char* g_selectDestinationFilesPath = "AssetImporter/SelectDestinationFilesPath";
  25. const char* g_errorMessageBoxTitle = "File failed to process.";
  26. const char* g_crateError = "Crate files cannot be imported.";
  27. static const char* s_crateFileExtension = "crate";
  28. };
  29. AssetImporterManager::AssetImporterManager(QWidget* parent)
  30. : QObject(parent)
  31. {
  32. }
  33. AssetImporterManager::~AssetImporterManager()
  34. {
  35. }
  36. void AssetImporterManager::Exec()
  37. {
  38. // tell the AssetImporterDragAndDropHandler that the Asset Importer now is running
  39. Q_EMIT StartAssetImporter();
  40. m_fileDialog = new QFileDialog;
  41. m_fileDialog->setFileMode(QFileDialog::ExistingFiles);
  42. m_fileDialog->setWindowModality(Qt::WindowModality::ApplicationModal);
  43. m_fileDialog->setViewMode(QFileDialog::Detail);
  44. m_fileDialog->setWindowTitle(tr("Select files to import"));
  45. m_fileDialog->setLabelText(QFileDialog::Accept, "Select");
  46. m_fileDialog->setAttribute(Qt::WA_DeleteOnClose);
  47. QSettings settings;
  48. m_currentAbsolutePath = settings.value(AssetImporterManagerPrivate::g_selectFilesPath).toString();
  49. QDir gameRoot(Path::GetEditingGameDataFolder().c_str());
  50. m_gameRootAbsPath = gameRoot.absolutePath();
  51. // Case 1: if currentAbsolutePath is empty at this point, that means this is the first time
  52. // users using the Asset Importer, set the default directory to be users' PC's desktop.
  53. // Case 2: if the current folder directory stored in the registry doesn't exist anymore,
  54. // that means users have removed the directory already (deleted or use the Move feature).
  55. // Case 3: if it's a directory under the game root folder, then in general,
  56. // users have modified the folder directory in the registry. It should not be happening.
  57. if (m_currentAbsolutePath.isEmpty() || !QFile(m_currentAbsolutePath).exists() ||
  58. m_currentAbsolutePath.startsWith(m_gameRootAbsPath, Qt::CaseInsensitive))
  59. {
  60. m_currentAbsolutePath = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation);
  61. }
  62. m_fileDialog->setDirectory(m_currentAbsolutePath);
  63. connect(m_fileDialog, &QFileDialog::rejected, [this]()
  64. {
  65. reject();
  66. });
  67. connect(m_fileDialog, &QDialog::accepted, [this]()
  68. {
  69. bool encounteredCrate = false;
  70. QStringList invalidFiles;
  71. for (const QString& path : m_fileDialog->selectedFiles())
  72. {
  73. QString fileName = GetFileName(path);
  74. QFileInfo info(path);
  75. QString extension = info.completeSuffix(); // extension without '.'
  76. if (QString(AssetImporterManagerPrivate::s_crateFileExtension).compare(extension, Qt::CaseInsensitive) != 0)
  77. {
  78. // prevent users from importing files under the game root directory
  79. if (path.startsWith(m_gameRootAbsPath, Qt::CaseInsensitive))
  80. {
  81. invalidFiles << fileName;
  82. }
  83. else
  84. {
  85. // store paths into the map.
  86. m_pathMap[path] = fileName;
  87. }
  88. }
  89. else
  90. {
  91. encounteredCrate = true;
  92. }
  93. }
  94. if (invalidFiles.size() > 0)
  95. {
  96. QString fileWarning =
  97. QString("Files cannot be imported into their own project. The following files will not be moved or copied:\n");
  98. fileWarning.append(invalidFiles.join(", "));
  99. fileWarning.append('.');
  100. QMessageBox::warning(AzToolsFramework::GetActiveWindow(), AssetImporterManagerPrivate::g_errorMessageBoxTitle, fileWarning);
  101. }
  102. if (encounteredCrate)
  103. {
  104. QMessageBox::warning(
  105. AzToolsFramework::GetActiveWindow(), AssetImporterManagerPrivate::g_errorMessageBoxTitle,
  106. AssetImporterManagerPrivate::g_crateError);
  107. }
  108. m_currentAbsolutePath = m_fileDialog->directory().absolutePath();
  109. QSettings settings;
  110. settings.setValue(AssetImporterManagerPrivate::g_selectFilesPath, m_currentAbsolutePath);
  111. // prevent users from selecting crate files from the File Explorer and open the Asset Importer.
  112. if (m_pathMap.size() > 0)
  113. {
  114. OnOpenSelectDestinationDialog();
  115. }
  116. });
  117. m_fileDialog->open();
  118. }
  119. void AssetImporterManager::Exec(const QStringList& dragAndDropFileList)
  120. {
  121. // note: dragging and dropping an empty folder can also trigger this condition
  122. if (!dragAndDropFileList.isEmpty())
  123. {
  124. OnDragAndDropFiles(&dragAndDropFileList);
  125. // only open the Asset Importer when the folder contains correct type files
  126. if (!m_pathMap.isEmpty())
  127. {
  128. // tell the AssetImporterDragAndDropHandler that the Asset Importer now is running
  129. Q_EMIT StartAssetImporter();
  130. OnOpenSelectDestinationDialog();
  131. }
  132. else
  133. {
  134. reject();
  135. }
  136. }
  137. }
  138. void AssetImporterManager::Exec(const QStringList& dragAndDropFileList, const QString& suggestedPath)
  139. {
  140. m_suggestedInitialPath = suggestedPath;
  141. Exec(dragAndDropFileList);
  142. }
  143. // used to cancel actions and close the dialog
  144. void AssetImporterManager::reject()
  145. {
  146. CompleteAssetImporting(false);
  147. }
  148. void AssetImporterManager::CompleteAssetImporting(bool wasSuccessful)
  149. {
  150. // Clear the pathMap to prevent trying to reimport assets later.
  151. m_pathMap.clear();
  152. m_destinationRootDirectory = "";
  153. // Inform listeners that we have completed the copy/move operation.
  154. if (wasSuccessful)
  155. {
  156. Q_EMIT AssetImportingComplete();
  157. }
  158. else
  159. {
  160. Q_EMIT StopAssetImporter();
  161. }
  162. }
  163. void AssetImporterManager::OnDragAndDropFiles(const QStringList* fileList)
  164. {
  165. for (int i = 0; i < fileList->size(); ++i)
  166. {
  167. // if the list contains a crate file,
  168. // the whole process should stop
  169. if (!GetAndCheckAllFilesInFolder(fileList->at(i)))
  170. {
  171. QMessageBox::warning(AzToolsFramework::GetActiveWindow(), AssetImporterManagerPrivate::g_errorMessageBoxTitle, AssetImporterManagerPrivate::g_crateError);
  172. reject();
  173. return;
  174. }
  175. }
  176. }
  177. void AssetImporterManager::OnBrowseDestinationFilePath(QLineEdit* destinationLineEdit)
  178. {
  179. QFileDialog fileDialog;
  180. fileDialog.setOption(QFileDialog::ShowDirsOnly, true);
  181. fileDialog.setViewMode(QFileDialog::List);
  182. fileDialog.setWindowModality(Qt::WindowModality::ApplicationModal);
  183. fileDialog.setWindowTitle(tr("Select import destination"));
  184. fileDialog.setFileMode(QFileDialog::Directory);
  185. QSettings settings;
  186. QString currentDestination = settings.value(AssetImporterManagerPrivate::g_selectDestinationFilesPath).toString();
  187. QDir gameRoot(Path::GetEditingGameDataFolder().c_str());
  188. QString gameRootAbsPath = gameRoot.absolutePath();
  189. // Case 1: if currentDestination is empty at this point, that means this is the first time
  190. // users using the Asset Importer, set the default directory to be the current game project's root folder
  191. // Case 2: if the current folder directory stored in the registry doesn't exist anymore,
  192. // that means users have removed the directory already (deleted or use the Move feature).
  193. // Case 3: if it's a directory outside of the game root folder, then in general,
  194. // users have modified the folder directory in the registry. It should not be happening.
  195. if (currentDestination.isEmpty() || !QDir(currentDestination).exists() || !currentDestination.startsWith(gameRootAbsPath, Qt::CaseInsensitive))
  196. {
  197. currentDestination = gameRootAbsPath;
  198. }
  199. fileDialog.setDirectory(currentDestination);
  200. // The default file path is the game project root folder.
  201. // After that, the default file path will be the previous opened folder path.
  202. connect(&fileDialog, &QFileDialog::directoryEntered, this, [&fileDialog, &gameRoot, &gameRootAbsPath](const QString& path)
  203. {
  204. // get current relative path
  205. QString relativePath = gameRoot.relativeFilePath(path);
  206. // Guard against navigating outside of the project folder. Lambda used as the dialog had to be captured.
  207. // checking the directory and prevent users from changing the directory outside of the game root
  208. if (!path.startsWith(gameRootAbsPath, Qt::CaseInsensitive) || (relativePath.length() > 2 && relativePath[0] == '.' && relativePath[1] == '.'))
  209. {
  210. fileDialog.setDirectory(gameRoot);
  211. }
  212. });
  213. if (!fileDialog.exec())
  214. {
  215. return;
  216. }
  217. // users can only select one folder at a time, so the index is always 0.
  218. // This fixes the issue that QFileDialog does not select the highlighted folder
  219. QString destinationDirectory = fileDialog.selectedFiles().at(0);
  220. OnSetDestinationDirectory(destinationDirectory);
  221. destinationLineEdit->setText(destinationDirectory);
  222. }
  223. // Copy + Paste
  224. void AssetImporterManager::OnCopyFiles()
  225. {
  226. m_importMethod = ImportFilesMethod::CopyFiles;
  227. ProcessCopyFiles();
  228. }
  229. // Cut + Paste
  230. void AssetImporterManager::OnMoveFiles()
  231. {
  232. m_importMethod = ImportFilesMethod::MoveFiles;
  233. ProcessMoveFiles();
  234. }
  235. bool AssetImporterManager::OnOverwriteFiles(QString relativePath, QString oldAbsolutePath)
  236. {
  237. // this is the absolute path in the destination folder
  238. QString destinationAbsolutePath = GenerateAbsolutePath(relativePath);
  239. return Overwrite(relativePath, oldAbsolutePath, destinationAbsolutePath);
  240. }
  241. bool AssetImporterManager::OnKeepBothFiles(QString relativePath, QString oldAbsolutePath)
  242. {
  243. // this is the absolute path in the destination folder
  244. QString destinationAbsolutePath = GenerateAbsolutePath(relativePath);
  245. QString subPath = QFileInfo(destinationAbsolutePath).absoluteDir().absolutePath();
  246. QFileInfo info(destinationAbsolutePath);
  247. QString extension = info.completeSuffix(); // extension without '.'
  248. QString fileName = info.baseName(); //file name without extension
  249. int number = 1;
  250. int index = destinationAbsolutePath.indexOf(extension);
  251. QString newFileName = CreateFileNameWithNumber(number, fileName, index, extension);
  252. QString newDestinationAbsolutePath = subPath + '/' + newFileName;
  253. while (QFile(newDestinationAbsolutePath).exists())
  254. {
  255. number++;
  256. newFileName = CreateFileNameWithNumber(number, fileName, index, extension);
  257. newDestinationAbsolutePath = subPath + '/' + newFileName;
  258. }
  259. if (m_importMethod == ImportFilesMethod::CopyFiles)
  260. {
  261. return Copy(relativePath, oldAbsolutePath, newDestinationAbsolutePath);
  262. }
  263. else if (m_importMethod == ImportFilesMethod::MoveFiles)
  264. {
  265. return Move(relativePath, oldAbsolutePath, newDestinationAbsolutePath);
  266. }
  267. return false;
  268. }
  269. void AssetImporterManager::OnOpenLogDialog()
  270. {
  271. AzFramework::AssetSystemRequestBus::Broadcast(&AzFramework::AssetSystem::AssetSystemRequests::ShowAssetProcessor);
  272. reject();
  273. }
  274. void AssetImporterManager::OnSetDestinationDirectory(QString destinationDirectory)
  275. {
  276. QSettings settings;
  277. QString currentDestination = settings.value(AssetImporterManagerPrivate::g_selectDestinationFilesPath).toString();
  278. m_destinationRootDirectory = (!destinationDirectory.isEmpty()) ? destinationDirectory : currentDestination;
  279. settings.setValue(AssetImporterManagerPrivate::g_selectDestinationFilesPath, destinationDirectory);
  280. }
  281. void AssetImporterManager::OnOpenSelectDestinationDialog()
  282. {
  283. QWidget* mainWindow = nullptr;
  284. AzToolsFramework::EditorRequestBus::BroadcastResult(mainWindow, &AzToolsFramework::EditorRequests::GetMainWindow);
  285. QString numberOfFilesMessage = m_pathMap.size() == 1 ? QString(tr("Importing 1 asset")) : QString(tr("Importing %1 assets").arg(m_pathMap.size()));
  286. SelectDestinationDialog selectDestinationDialog(numberOfFilesMessage, mainWindow, m_suggestedInitialPath);
  287. // Browse Destination File Path
  288. connect(&selectDestinationDialog, &SelectDestinationDialog::BrowseDestinationPath, this, &AssetImporterManager::OnBrowseDestinationFilePath);
  289. connect(&selectDestinationDialog, &SelectDestinationDialog::DoCopyFiles, this, &AssetImporterManager::OnCopyFiles);
  290. connect(&selectDestinationDialog, &SelectDestinationDialog::DoMoveFiles, this, &AssetImporterManager::OnMoveFiles);
  291. connect(&selectDestinationDialog, &SelectDestinationDialog::Cancel, this, &AssetImporterManager::reject);
  292. connect(&selectDestinationDialog, &SelectDestinationDialog::SetDestinationDirectory, this, &AssetImporterManager::OnSetDestinationDirectory);
  293. selectDestinationDialog.exec();
  294. }
  295. ProcessFilesMethod AssetImporterManager::OnOpenFilesAlreadyExistDialog(QString message, int numberOfFiles)
  296. {
  297. ProcessFilesMethod processMethod = ProcessFilesMethod::Default;
  298. // make sure the dialog is opened in front of the Editor main window
  299. QWidget* mainWindow = nullptr;
  300. AzToolsFramework::EditorRequestBus::BroadcastResult(mainWindow, &AzToolsFramework::EditorRequests::GetMainWindow);
  301. FilesAlreadyExistDialog filesAlreadyExistDialog(message, numberOfFiles, mainWindow);
  302. bool applyToAll = false;
  303. connect(&filesAlreadyExistDialog, &FilesAlreadyExistDialog::ApplyActionToAllFiles, this, [&applyToAll](bool result)
  304. {
  305. applyToAll = result;
  306. });
  307. connect(&filesAlreadyExistDialog, &FilesAlreadyExistDialog::OverWriteFiles, this, [this, &processMethod, &applyToAll]()
  308. {
  309. processMethod = UpdateProcessFileMethod(ProcessFilesMethod::OverwriteFile, applyToAll);
  310. });
  311. connect(&filesAlreadyExistDialog, &FilesAlreadyExistDialog::KeepBothFiles, this, [this, &processMethod, &applyToAll]()
  312. {
  313. processMethod = UpdateProcessFileMethod(ProcessFilesMethod::KeepBothFile, applyToAll);
  314. });
  315. connect(&filesAlreadyExistDialog, &FilesAlreadyExistDialog::SkipCurrentProcess, this, [this, &processMethod, &applyToAll]()
  316. {
  317. processMethod = UpdateProcessFileMethod(ProcessFilesMethod::SkipProcessingFile, applyToAll);
  318. });
  319. connect(&filesAlreadyExistDialog, &FilesAlreadyExistDialog::CancelAllProcesses, this, [&processMethod]()
  320. {
  321. processMethod = ProcessFilesMethod::Cancel;
  322. });
  323. if (!applyToAll && processMethod != ProcessFilesMethod::Cancel)
  324. {
  325. filesAlreadyExistDialog.exec();
  326. }
  327. return processMethod;
  328. }
  329. ProcessFilesMethod AssetImporterManager::UpdateProcessFileMethod(ProcessFilesMethod processMethod, bool applyToAll)
  330. {
  331. if (applyToAll)
  332. {
  333. switch (processMethod)
  334. {
  335. case ProcessFilesMethod::OverwriteFile:
  336. processMethod = ProcessFilesMethod::OverwriteAllFiles;
  337. break;
  338. case ProcessFilesMethod::KeepBothFile:
  339. processMethod = ProcessFilesMethod::KeepBothAllFiles;
  340. break;
  341. case ProcessFilesMethod::SkipProcessingFile:
  342. processMethod = ProcessFilesMethod::SkipProcessingAllFiles;
  343. }
  344. }
  345. return processMethod;
  346. }
  347. bool AssetImporterManager::ProcessFileMethod(ProcessFilesMethod processMethod, QString relativePath, QString oldAbsolutePath)
  348. {
  349. switch (processMethod)
  350. {
  351. case ProcessFilesMethod::OverwriteFile:
  352. case ProcessFilesMethod::OverwriteAllFiles:
  353. return OnOverwriteFiles(relativePath, oldAbsolutePath);
  354. case ProcessFilesMethod::KeepBothFile:
  355. case ProcessFilesMethod::KeepBothAllFiles:
  356. return OnKeepBothFiles(relativePath, oldAbsolutePath);
  357. case ProcessFilesMethod::SkipProcessingAllFiles:
  358. return false;
  359. }
  360. return false;
  361. }
  362. void AssetImporterManager::ProcessCopyFiles()
  363. {
  364. int numberOfFiles = m_pathMap.size();
  365. int numberOfProcessedFiles = 0;
  366. ProcessFilesMethod processMethod = ProcessFilesMethod::Default;
  367. for (int i = 0; i < m_pathMap.size(); ++i)
  368. {
  369. QString relativePath = m_pathMap.values().at(i);
  370. QString oldAbsolutePath = m_pathMap.keys().at(i);
  371. // this is the absolute path in the destination folder
  372. QString destinationAbsolutePath = GenerateAbsolutePath(relativePath);
  373. // check if the file exists in the destination folder
  374. if (!QFile::exists(destinationAbsolutePath))
  375. {
  376. if (Copy(relativePath, oldAbsolutePath, destinationAbsolutePath))
  377. {
  378. numberOfProcessedFiles++;
  379. }
  380. }
  381. else
  382. {
  383. if (processMethod == ProcessFilesMethod::Default ||
  384. processMethod == ProcessFilesMethod::OverwriteFile ||
  385. processMethod == ProcessFilesMethod::KeepBothFile ||
  386. processMethod == ProcessFilesMethod::SkipProcessingFile)
  387. {
  388. QString fileName = GetFileName(oldAbsolutePath);
  389. QString message = QString("The destination already has a file named \"%1\". What would you like to do?").arg(fileName);
  390. processMethod = OnOpenFilesAlreadyExistDialog(message, numberOfFiles);
  391. }
  392. if (ProcessFileMethod(processMethod, relativePath, oldAbsolutePath))
  393. {
  394. numberOfProcessedFiles++;
  395. }
  396. }
  397. numberOfFiles--;
  398. }
  399. if (numberOfProcessedFiles == 0)
  400. {
  401. reject();
  402. }
  403. else
  404. {
  405. CompleteAssetImporting();
  406. }
  407. }
  408. void AssetImporterManager::ProcessMoveFiles()
  409. {
  410. int numberOfFiles = m_pathMap.size();
  411. int numberOfProcessedFiles = 0;
  412. ProcessFilesMethod processMethod = ProcessFilesMethod::Default;
  413. for (int i = 0; i < m_pathMap.size(); ++i)
  414. {
  415. QString relativePath = m_pathMap.values().at(i);
  416. QString oldAbsolutePath = m_pathMap.keys().at(i);
  417. // this is the absolute path in the destination folder
  418. QString destinationAbsolutePath = GenerateAbsolutePath(relativePath);
  419. // check if the file exists in the destination folder
  420. if (!QFile::exists(destinationAbsolutePath))
  421. {
  422. if (Move(relativePath, oldAbsolutePath, destinationAbsolutePath))
  423. {
  424. numberOfProcessedFiles++;
  425. }
  426. }
  427. else
  428. {
  429. if (processMethod == ProcessFilesMethod::Default ||
  430. processMethod == ProcessFilesMethod::OverwriteFile ||
  431. processMethod == ProcessFilesMethod::KeepBothFile ||
  432. processMethod == ProcessFilesMethod::SkipProcessingFile)
  433. {
  434. QString fileName = GetFileName(oldAbsolutePath);
  435. QString message = QString("The destination already has a file named \"%1\". What would you like to do?").arg(fileName);
  436. processMethod = OnOpenFilesAlreadyExistDialog(message, numberOfFiles);
  437. }
  438. if (ProcessFileMethod(processMethod, relativePath, oldAbsolutePath))
  439. {
  440. numberOfProcessedFiles++;
  441. }
  442. }
  443. numberOfFiles--;
  444. }
  445. if (numberOfProcessedFiles == 0)
  446. {
  447. reject();
  448. }
  449. else
  450. {
  451. CompleteAssetImporting();
  452. }
  453. }
  454. bool AssetImporterManager::Copy(QString relativePath, QString oldAbsolutePath, QString destinationAbsolutePath)
  455. {
  456. QString fileName = GetFileName(destinationAbsolutePath);
  457. QString subPath = QFileInfo(destinationAbsolutePath).absoluteDir().absolutePath();
  458. QDir dir;
  459. bool directoryExistedAlready = QDir(subPath).exists();
  460. if (!directoryExistedAlready)
  461. {
  462. dir.mkpath(subPath);
  463. }
  464. QString newDestinationAbsolutePath = subPath;
  465. newDestinationAbsolutePath = newDestinationAbsolutePath.append('/' + fileName);
  466. // Copy the file from the old path to the new path
  467. if (!QFile::copy(oldAbsolutePath, newDestinationAbsolutePath))
  468. {
  469. QString reason = tr("an unknown issue occurred.");
  470. if (!directoryExistedAlready)
  471. {
  472. dir.rmdir(subPath);
  473. }
  474. // if the original files got deleted at this condition
  475. if (!QFile(oldAbsolutePath).exists())
  476. {
  477. reason = tr("%1 no longer exists.").arg(fileName);
  478. }
  479. // if users manually copy the file into the destination folder at this condition
  480. if (QFile(newDestinationAbsolutePath).exists())
  481. {
  482. reason = tr("%1 already exists in the target directory.").arg(fileName);
  483. }
  484. QMessageBox::critical(AzToolsFramework::GetActiveWindow(), AssetImporterManagerPrivate::g_errorMessageBoxTitle, QObject::tr("We're sorry, but the file failed to process because %1").arg(reason));
  485. return false;
  486. }
  487. // set the destination file to be writable by user himself/herself if it's read-only
  488. QFile destinationFile(newDestinationAbsolutePath);
  489. SetDestinationFileWritable(destinationFile);
  490. return true;
  491. }
  492. bool AssetImporterManager::Move(QString relativePath, QString oldAbsolutePath, QString destinationAbsolutePath)
  493. {
  494. QString fileName = GetFileName(destinationAbsolutePath);
  495. QString subPath = QFileInfo(destinationAbsolutePath).absoluteDir().absolutePath();
  496. QString newDestinationAbsolutePath = subPath;
  497. QDir dir;
  498. bool directoryExistedAlready = QDir(subPath).exists();
  499. if (!directoryExistedAlready)
  500. {
  501. dir.mkpath(subPath);
  502. }
  503. if (QFile::rename(oldAbsolutePath, newDestinationAbsolutePath.append('/' + fileName)))
  504. {
  505. QString oldFileName = GetFileName(oldAbsolutePath);
  506. // Only remove the old directory if the relative path is the file name itself.
  507. // That also means users are dragging and dropping files, but not a folder containing those files.
  508. if (oldFileName.compare(relativePath) != 0)
  509. {
  510. RemoveOldPath(oldAbsolutePath, relativePath);
  511. }
  512. // set the destination file to be writable by user himself/herself if it's read-only
  513. QFile destinationFile(newDestinationAbsolutePath);
  514. SetDestinationFileWritable(destinationFile);
  515. return true;
  516. }
  517. else
  518. {
  519. QString reason = tr("an unknown issue occurred.");
  520. QString oldFileName = GetFileName(oldAbsolutePath);
  521. if (!directoryExistedAlready)
  522. {
  523. dir.rmdir(subPath);
  524. }
  525. // if the original files got deleted at this condition
  526. if (!QFile(oldAbsolutePath).exists())
  527. {
  528. reason = tr("%1 no longer exists.").arg(oldFileName);
  529. }
  530. // if users manually copy the file into the destination folder at this condition
  531. if (QFile(newDestinationAbsolutePath).exists())
  532. {
  533. reason = tr("%1 already exists in the target directory.").arg(oldFileName);
  534. }
  535. QMessageBox::critical(AzToolsFramework::GetActiveWindow(), AssetImporterManagerPrivate::g_errorMessageBoxTitle, QObject::tr("We're sorry, but the file failed to process because %1").arg(reason));
  536. return false;
  537. }
  538. }
  539. bool AssetImporterManager::Overwrite(QString relativePath, QString oldAbsolutePath, QString destinationAbsolutePath)
  540. {
  541. QFile newFile(destinationAbsolutePath);
  542. QFile oldFile(oldAbsolutePath);
  543. // double check if paths are valid
  544. if ((!oldFile.open(QIODevice::ReadOnly)))
  545. {
  546. QString fileName = GetFileName(oldAbsolutePath);
  547. QString reason = tr("%1 no longer exists.").arg(fileName);
  548. QMessageBox::critical(AzToolsFramework::GetActiveWindow(), AssetImporterManagerPrivate::g_errorMessageBoxTitle, QObject::tr("We're sorry, but the file failed to process because %1").arg(reason));
  549. return false;
  550. }
  551. if (!newFile.open(QIODevice::WriteOnly | QIODevice::Truncate))
  552. {
  553. QString reason = tr("We're sorry, but the file failed to process.");
  554. QString fileName = GetFileName(destinationAbsolutePath);
  555. if (!newFile.exists())
  556. {
  557. reason = tr("%1 from the destination directory is removed.").arg(fileName);
  558. }
  559. else
  560. {
  561. reason = tr("%1 from the destination directory cannot be overwritten.").arg(fileName);
  562. }
  563. QMessageBox::critical(AzToolsFramework::GetActiveWindow(), AssetImporterManagerPrivate::g_errorMessageBoxTitle, QObject::tr("We're sorry, but the file failed to process because %1").arg(reason));
  564. return false;
  565. }
  566. QDataStream dataStream(&oldFile);
  567. QDataStream out(&newFile);
  568. int bufferSize = 1024 * 1024;
  569. char* buffer = new char[bufferSize];
  570. while (!dataStream.atEnd())
  571. {
  572. int bytesRead = dataStream.readRawData(buffer, bufferSize);
  573. out.writeRawData(buffer, bytesRead);
  574. }
  575. delete[] buffer;
  576. oldFile.close();
  577. newFile.close();
  578. // if it's the move file method, got to remove the original files
  579. if (m_importMethod == ImportFilesMethod::MoveFiles)
  580. {
  581. QString fileName = GetFileName(oldAbsolutePath);
  582. QFile file(oldAbsolutePath);
  583. QDir absoluteDir = QFileInfo(oldAbsolutePath).absoluteDir();
  584. if (file.exists())
  585. {
  586. // if the original file is read-only,
  587. // then it got to be writable in order to be deleted successfully
  588. SetDestinationFileWritable(file);
  589. absoluteDir.remove(fileName);
  590. }
  591. // Only remove the old directory if the relative path is the file name itself.
  592. // That also means users are dragging and dropping files, but not a folder containing those files.
  593. if (fileName.compare(relativePath) != 0)
  594. {
  595. RemoveOldPath(oldAbsolutePath, relativePath);
  596. }
  597. }
  598. return true;
  599. }
  600. bool AssetImporterManager::GetAndCheckAllFilesInFolder(QString path)
  601. {
  602. QString formattedPath = path;
  603. // Paths ending with '/' return from QFileInfo().fileName() with a value of ""
  604. // Strip a trailing slash so we can correctly get rootFolderName on all platforms
  605. if (formattedPath.endsWith("/"))
  606. {
  607. formattedPath.truncate(formattedPath.lastIndexOf(QChar('/')));
  608. }
  609. QString rootFolderName = GetFileName(formattedPath);
  610. QDirIterator it(formattedPath, QDir::NoDotAndDotDot | QDir::Files, QDirIterator::Subdirectories);
  611. QFileInfo info(formattedPath);
  612. if (!info.isDir() && !it.hasNext() && info.exists())
  613. {
  614. m_pathMap[formattedPath] = rootFolderName;
  615. return true;
  616. }
  617. // Get the index of the last sub folder name in the path
  618. QStringList directoryNameList = formattedPath.split('/');
  619. int lastFolderIndex = directoryNameList.size() - 1;
  620. QString pathToBeRelativeTo = directoryNameList.mid(0, lastFolderIndex).join('/');
  621. while (it.hasNext())
  622. {
  623. QString absolutePath = it.next();
  624. QFileInfo absoluteInfo(absolutePath);
  625. QString extension = absoluteInfo.completeSuffix();
  626. if (QString(AssetImporterManagerPrivate::s_crateFileExtension).compare(extension, Qt::CaseInsensitive) == 0)
  627. {
  628. return false;
  629. }
  630. Q_ASSERT(absolutePath.startsWith(pathToBeRelativeTo));
  631. QString relativePath = absolutePath.mid(pathToBeRelativeTo.size() + 1);
  632. m_pathMap[absolutePath] = relativePath;
  633. }
  634. return true;
  635. }
  636. void AssetImporterManager::RemoveOldPath(QString oldAbsolutePath, QString oldRelativePath)
  637. {
  638. QDir absoluteDir = QFileInfo(oldAbsolutePath).absoluteDir();
  639. QStringList directoryList = oldRelativePath.split('/');
  640. // remove each folder from the leave to the root, based on the relative path
  641. for (int i = 0; i < directoryList.size(); ++i)
  642. {
  643. QString currentDir = absoluteDir.path();
  644. absoluteDir.rmpath(currentDir);
  645. absoluteDir.cdUp();
  646. }
  647. }
  648. void AssetImporterManager::SetDestinationFileWritable(QFile& destinationFile)
  649. {
  650. if (destinationFile.open(QIODevice::ReadOnly))
  651. {
  652. destinationFile.setPermissions(QFile::WriteOwner | destinationFile.permissions());
  653. }
  654. destinationFile.close();
  655. }
  656. QString AssetImporterManager::CreateFileNameWithNumber(int number, QString fileName, int index, QString extension)
  657. {
  658. QString newFileName;
  659. newFileName = fileName.isEmpty() ? fileName : fileName.left(index);
  660. newFileName += "(" + QString::number(number) + ")";
  661. if (extension.size() > 0)
  662. {
  663. newFileName += "." + extension;
  664. }
  665. return newFileName;
  666. }
  667. QString AssetImporterManager::GenerateAbsolutePath(QString relativePath)
  668. {
  669. return QDir(m_destinationRootDirectory).absoluteFilePath(relativePath);
  670. }
  671. QString AssetImporterManager::GetFileName(QString path)
  672. {
  673. return QFileInfo(path).fileName();
  674. }
  675. #include <AssetImporter/AssetImporterManager/moc_AssetImporterManager.cpp>