Debian Codegraph @

core/libs/album/manager/albummanager_database.cpp

raw
1 /* ============================================================
2 *
3 * This file is a part of digiKam project
4 * https://www.digikam.org
5 *
6 * Date : 2004-06-15
7 * Description : Albums manager interface - Database helpers.
8 *
9 * SPDX-FileCopyrightText: 2006-2026 by Gilles Caulier <caulier dot gilles at gmail dot com>
10 * SPDX-FileCopyrightText: 2006-2011 by Marcel Wiesweg <marcel dot wiesweg at gmx dot de>
11 * SPDX-FileCopyrightText: 2015 by Mohamed_Anwer <m_dot_anwer at gmx dot com>
12 *
13 * SPDX-License-Identifier: GPL-2.0-or-later
14 *
15 * ============================================================ */
16
17 #include "albummanager_p.h"
18
19 // Qt includes
20
21 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
22 # include <QTextCodec>
23 #else
24 # include <QStringConverter>
25 #endif
26
27 // KDE includes
28
29 #include <kconfiggroup.h>
30 #include <ksharedconfig.h>
31
32 namespace Digikam
33 {
34
35 bool AlbumManager::setDatabase(const DbEngineParameters& params, bool priority, const QString& suggestedAlbumRoot, bool ignoreDisappearedLocations)
36 {
37 // This is to ensure that the setup does not overrule the command line.
38 // TODO: there is a bug that setup is showing something different here.
39
40 if (priority)
41 {
42 d->hasPriorizedDbPath = true;
43 }
44 else if (d->hasPriorizedDbPath)
45 {
46 // ignore change without priority
47
48 return true;
49 }
50
51 d->changed = true;
52
53 QApplication::setOverrideCursor(Qt::WaitCursor);
54
55 DatabaseServerStarter::instance()->stopServerManagerProcess();
56
57 // Shutdown possibly running collection scans.
58 // Must call restartCollectionScan further down.
59
60 ScanController::instance()->cancelAllAndSuspendCollectionScan();
61
62 disconnect(CollectionManager::instance(), nullptr, this, nullptr);
63 CollectionManager::instance()->setWatchDisabled();
64
65 if (CoreDbAccess::databaseWatch())
66 {
67 disconnect(CoreDbAccess::databaseWatch(), nullptr, this, nullptr);
68 }
69
70 ItemAttributesWatch::shutDown();
71 ItemAttributesWatch::cleanUp();
72 d->albumWatch->clear();
73
74 cleanUp();
75
76 d->currentAlbums.clear();
77
78 Q_EMIT signalAlbumCurrentChanged(d->currentAlbums);
79 Q_EMIT signalAlbumsCleared();
80
81 d->albumPathHash.clear();
82 d->allAlbumsIdHash.clear();
83 d->albumRootAlbumHash.clear();
84
85 // deletes all child albums as well
86
87 delete d->rootPAlbum;
88 delete d->rootTAlbum;
89 delete d->rootDAlbum;
90 delete d->rootSAlbum;
91
92 d->rootPAlbum = nullptr;
93 d->rootTAlbum = nullptr;
94 d->rootDAlbum = nullptr;
95 d->rootSAlbum = nullptr;
96
97 // -- Database initialization -------------------------------------------------
98
99 // ensure, embedded database is loaded
100
101 qCDebug(DIGIKAM_GENERAL_LOG) << params;
102
103 QString databaseError;
104
105 const ApplicationSettings* const settings = ApplicationSettings::instance();
106
107 if (params.internalServer && suggestedAlbumRoot.isEmpty())
108 {
109 if (!QFileInfo::exists(params.internalServerPath()))
110 {
111 databaseError = i18n("The MySQL database directory was not found.");
112 }
113 else if (
114 (
115 !QFileInfo::exists(params.internalServerMysqlUpgradeCmd) &&
116 QStandardPaths::findExecutable(params.internalServerMysqlUpgradeCmd).isEmpty()
117 ) ||
118 (
119 !QFileInfo::exists(params.internalServerMysqlServerCmd) &&
120 QStandardPaths::findExecutable(params.internalServerMysqlServerCmd).isEmpty()
121 ) ||
122 (
123 !QFileInfo::exists(params.internalServerMysqlAdminCmd) &&
124 QStandardPaths::findExecutable(params.internalServerMysqlAdminCmd).isEmpty()
125 )
126 )
127 {
128 databaseError = i18n("The MySQL binary tools was not found.");
129 }
130 }
131 else if (params.isSQLite() && suggestedAlbumRoot.isEmpty() && !settings->getDatabaseDirSetAtCmd())
132 {
133 if (!QFileInfo::exists(params.databaseNameCore))
134 {
135 databaseError = i18n("The SQLite core database was not found.");
136 }
137 }
138
139 if (!databaseError.isEmpty())
140 {
141 QString configPath = QStandardPaths::locate(QStandardPaths::GenericConfigLocation,
142 QLatin1String("digikamrc"));
143
144 databaseError += i18n("<p>If you want to start with a new configuration and "
145 "with a first run wizard, delete the file:<br>%1</p>",
146 QDir::toNativeSeparators(configPath));
147
148 return showDatabaseSetupPage(databaseError, priority, suggestedAlbumRoot);
149 }
150
151 if (params.internalServer)
152 {
153 DatabaseServerError result = DatabaseServerStarter::instance()->startServerManagerProcess(params);
154
155 if (result.getErrorType() != DatabaseServerError::NoErrors)
156 {
157 databaseError = i18n("An error occurred during the internal server start."
158 "<p>Details:<br>%1</p>", result.getErrorText());
159
160 return showDatabaseSetupPage(databaseError, priority, suggestedAlbumRoot);
161 }
162 }
163
164 CoreDbAccess::setParameters(params, CoreDbAccess::MainApplication);
165
166 DbEngineGuiErrorHandler* const handler = new DbEngineGuiErrorHandler(CoreDbAccess::parameters());
167 CoreDbAccess::initDbEngineErrorHandler(handler);
168
169 QApplication::restoreOverrideCursor();
170
171 if (!handler->checkDatabaseConnection())
172 {
173 databaseError = i18n("Failed to open the database.");
174
175 if (!showDatabaseSetupPage(databaseError, priority, suggestedAlbumRoot))
176 {
177 if (params.isSQLite())
178 {
179 QMessageBox::critical(qApp->activeWindow(), qApp->applicationName(),
180 i18n("<p>digiKam will attempt to start now, "
181 "but it will <b>not</b> be functional.</p>"));
182
183 CoreDbAccess::setParameters(DbEngineParameters(), CoreDbAccess::DatabaseSlave);
184
185 return true;
186 }
187
188 return false;
189 }
190
191 return true;
192 }
193
194 QApplication::setOverrideCursor(Qt::WaitCursor);
195
196 d->albumWatch->setDbEngineParameters(params);
197
198 ScanController::Advice advice = ScanController::instance()->databaseInitialization();
199 QString errorMsg = CoreDbAccess().lastError();
200
201 QApplication::restoreOverrideCursor();
202
203 switch (advice)
204 {
205 case ScanController::Success:
206 {
207 break;
208 }
209
210 case ScanController::ContinueWithoutDatabase:
211 {
212 if (errorMsg.isEmpty())
213 {
214 QMessageBox::critical(qApp->activeWindow(), qApp->applicationName(),
215 i18n("<p>Failed to open the database.</p>"
216 "<p>You cannot use digiKam without a working database. "
217 "digiKam will attempt to start now, but it will <b>not</b> be functional. "
218 "Please check the database settings in the <b>configuration menu</b>.</p>"
219 ));
220 }
221 else
222 {
223 QMessageBox::critical(qApp->activeWindow(), qApp->applicationName(),
224 i18n("<p>Failed to open the database. Error message from database:</p>"
225 "<p><b>%1</b></p>"
226 "<p>You cannot use digiKam without a working database. "
227 "digiKam will attempt to start now, but it will <b>not</b> be functional. "
228 "Please check the database settings in the <b>configuration menu</b>.</p>",
229 errorMsg));
230 }
231
232 return true;
233 }
234
235 case ScanController::AbortImmediately:
236 {
237 if (!errorMsg.isEmpty())
238 {
239 databaseError = errorMsg;
240 }
241 else
242 {
243 databaseError = i18n("Failed to initialize the database.");
244 }
245
246 return showDatabaseSetupPage(databaseError, priority, suggestedAlbumRoot);
247 }
248 }
249
250 // -- Locale Checking ---------------------------------------------------------
251
252 QString currLocale = CoreDbAccess().db()->getDatabaseEncoding();
253 QString dbLocale = CoreDbAccess().db()->getSetting(QLatin1String("Locale"));
254
255 if (dbLocale.isEmpty())
256 {
257 qCDebug(DIGIKAM_GENERAL_LOG) << "No locale found in database";
258 CoreDbAccess().db()->setSetting(QLatin1String("Locale"), currLocale);
259 }
260 else if (dbLocale != currLocale)
261 {
262 // TODO it would be better to replace all yes/no confirmation dialogs with ones that has custom
263 // buttons that denote the actions directly, i.e.: ["Ignore and Continue"] ["Adjust locale"]
264
265 int result = QMessageBox::warning(qApp->activeWindow(), qApp->applicationName(),
266 i18n("Your database character set has changed since this "
267 "album was last opened.\n"
268 "Old character set: %1, new character set: %2\n"
269 "If you have recently changed your database character set, "
270 "you need not be concerned.\n"
271 "Please note that if you switched to a database character set "
272 "that does not support some of the filenames in your collection, "
273 "these files may no longer be found in the collection. "
274 "If you are sure that you want to "
275 "continue, click 'Yes'. "
276 "Otherwise, click 'No' and correct your "
277 "database character set setting before restarting digiKam.",
278 dbLocale, currLocale),
279 QMessageBox::Yes | QMessageBox::No);
280
281 if (result != QMessageBox::Yes)
282 {
283 return false;
284 }
285
286 CoreDbAccess().db()->setSetting(QLatin1String("Locale"), currLocale);
287 }
288
289 // -- UUID Checking ---------------------------------------------------------
290
291 QList<CollectionLocation> disappearedLocations = CollectionManager::instance()->checkHardWiredLocations();
292
293 for (const CollectionLocation& loc : std::as_const(disappearedLocations))
294 {
295 QString locDescription;
296 QStringList candidateIds, candidateDescriptions;
297 CollectionManager::instance()->migrationCandidates(loc, &locDescription, &candidateIds, &candidateDescriptions);
298 qCDebug(DIGIKAM_GENERAL_LOG) << "Migration candidates for" << locDescription
299 << ":" << candidateIds << candidateDescriptions;
300
301 QDialog* const dialog = new QDialog;
302 QWidget* const widget = new QWidget(dialog);
303 QGridLayout* const mainLayout = new QGridLayout;
304 mainLayout->setColumnStretch(1, 1);
305
306 QLabel* const deviceIconLabel = new QLabel;
307 deviceIconLabel->setPixmap(QIcon::fromTheme(QLatin1String("drive-harddisk")).pixmap(64));
308 mainLayout->addWidget(deviceIconLabel, 0, 0);
309
310 QLabel* const mainLabel = new QLabel(i18n("<p>The collection </p><p><b>%1</b><br>(%2)</p><p> is currently "
311 "not found on your system.<br> Please choose the most "
312 "appropriate option to handle this situation:</p>",
313 loc.label(), QDir::toNativeSeparators(locDescription)));
314 mainLabel->setWordWrap(true);
315 mainLayout->addWidget(mainLabel, 0, 1);
316
317 QGroupBox* const groupBox = new QGroupBox;
318 mainLayout->addWidget(groupBox, 1, 0, 1, 2);
319
320 QGridLayout* const layout = new QGridLayout;
321 layout->setColumnStretch(1, 1);
322
323 QRadioButton* migrateButton = nullptr;
324 QComboBox* migrateChoices = nullptr;
325
326 if (!candidateIds.isEmpty())
327 {
328 migrateButton = new QRadioButton;
329 QLabel* const migrateLabel = new QLabel(i18n("<p>The collection is still available, but the identifier changed.<br>"
330 "This can be caused by restoring a backup, changing the partition layout "
331 "or the file system settings.<br>"
332 "The collection is now located at this place:</p>"));
333 migrateLabel->setWordWrap(true);
334
335 migrateChoices = new QComboBox;
336
337 for (int i = 0 ; i < candidateIds.size() ; ++i)
338 {
339 migrateChoices->addItem(QDir::toNativeSeparators(candidateDescriptions.at(i)), candidateIds.at(i));
340 }
341
342 layout->addWidget(migrateButton, 0, 0, Qt::AlignTop);
343 layout->addWidget(migrateLabel, 0, 1);
344 layout->addWidget(migrateChoices, 1, 1);
345 }
346
347 QRadioButton* const isRemovableButton = new QRadioButton;
348 QLabel* const isRemovableLabel = new QLabel(i18n("The collection is located on a storage device which is not "
349 "always attached. Mark the collection as a removable collection."));
350 isRemovableLabel->setWordWrap(true);
351 layout->addWidget(isRemovableButton, 2, 0, Qt::AlignTop);
352 layout->addWidget(isRemovableLabel, 2, 1);
353
354 QRadioButton* const solveManuallyButton = new QRadioButton;
355 QLabel* const solveManuallyLabel = new QLabel(i18n("Take no action now. I would like to solve the problem "
356 "later using the setup dialog"));
357 solveManuallyLabel->setWordWrap(true);
358 layout->addWidget(solveManuallyButton, 3, 0, Qt::AlignTop);
359 layout->addWidget(solveManuallyLabel, 3, 1);
360
361 groupBox->setLayout(layout);
362 widget->setLayout(mainLayout);
363
364 QVBoxLayout* const vbx = new QVBoxLayout(dialog);
365 QDialogButtonBox* const buttons = new QDialogButtonBox(QDialogButtonBox::Ok, dialog);
366 vbx->addWidget(widget);
367 vbx->addWidget(buttons);
368 dialog->setLayout(vbx);
369 dialog->setWindowTitle(i18nc("@title:window", "Collection not Found"));
370
371 connect(buttons->button(QDialogButtonBox::Ok), SIGNAL(clicked()),
372 dialog, SLOT(accept()));
373
374 // Default option: If there is only one candidate, default to migration.
375 // Otherwise default to do nothing now.
376
377 if (migrateButton && (candidateIds.size() == 1))
378 {
379 migrateButton->setChecked(true);
380 }
381 else
382 {
383 solveManuallyButton->setChecked(true);
384 }
385
386 if (!ignoreDisappearedLocations && dialog->exec())
387 {
388 if (migrateButton && migrateButton->isChecked())
389 {
390 CollectionManager::instance()->migrateToVolume(loc, migrateChoices->itemData(migrateChoices->currentIndex()).toString());
391 }
392 else if (isRemovableButton->isChecked())
393 {
394 CollectionManager::instance()->changeType(loc, CollectionLocation::VolumeRemovable);
395 }
396 }
397
398 delete dialog;
399 }
400
401 // -- ---------------------------------------------------------
402
403 // check that we have one album root
404
405 if (CollectionManager::instance()->allLocations().isEmpty())
406 {
407 if (suggestedAlbumRoot.isEmpty())
408 {
409 Setup::execSinglePage(Setup::CollectionsPage);
410 }
411 else
412 {
413 QUrl albumRoot(QUrl::fromLocalFile(suggestedAlbumRoot));
414 CollectionManager::instance()->addLocation(albumRoot, albumRoot.fileName());
415
416 // Not needed? See bug #188959
417 /*
418 ScanController::instance()->completeCollectionScan();
419 */
420 }
421 }
422
423 // -- ---------------------------------------------------------
424
425 QApplication::setOverrideCursor(Qt::WaitCursor);
426
427 ThumbnailLoadThread::initializeThumbnailDatabase(CoreDbAccess::parameters().thumbnailParameters(),
428 new ThumbsDbInfoProvider());
429
430 DbEngineGuiErrorHandler* const thumbnailsDBHandler = new DbEngineGuiErrorHandler(ThumbsDbAccess::parameters());
431 ThumbsDbAccess::initDbEngineErrorHandler(thumbnailsDBHandler);
432
433 // Activate the similarity database.
434
435 SimilarityDbAccess::setParameters(params.similarityParameters());
436
437 DbEngineGuiErrorHandler* const similarityHandler = new DbEngineGuiErrorHandler(SimilarityDbAccess::parameters());
438 SimilarityDbAccess::initDbEngineErrorHandler(similarityHandler);
439
440 if (SimilarityDbAccess::checkReadyForUse(nullptr))
441 {
442 qCDebug(DIGIKAM_SIMILARITYDB_LOG) << "Similarity database ready for use";
443 }
444 else
445 {
446 qCDebug(DIGIKAM_SIMILARITYDB_LOG) << "Failed to initialize similarity database";
447 }
448
449 QApplication::restoreOverrideCursor();
450
451 // still suspended from above
452
453 ScanController::instance()->restartCollectionScan();
454
455 return true;
456 }
457
458 void AlbumManager::checkDatabaseDirsAfterFirstRun(const QString& dbPath, const QString& albumPath)
459 {
460 // for bug #193522
461
462 QDir newDir(dbPath);
463 QDir albumDir(albumPath);
464 DbEngineParameters newParams = DbEngineParameters::parametersForSQLiteDefaultFile(newDir.path());
465 QFileInfo digikam4DB(newParams.SQLiteDatabaseFile());
466
467 if (!digikam4DB.exists())
468 {
469 QFileInfo digikam3DB(newDir, QLatin1String("digikam3.db"));
470 QFileInfo digikamVeryOldDB(newDir, QLatin1String("digikam.db"));
471
472 if (digikam3DB.exists() || digikamVeryOldDB.exists())
473 {
474 QPointer<QMessageBox> msgBox = new QMessageBox(QMessageBox::Warning,
475 i18nc("@title:window", "Database Folder"),
476 i18n("<p>You have chosen the folder \"%1\" as the place to store the database. "
477 "A database file from an older version of digiKam is found in this folder.</p> "
478 "<p>Would you like to upgrade the old database file - confirming "
479 "that this database file was indeed created for the pictures located in the folder \"%2\" - "
480 "or ignore the old file and start with a new database?</p> ",
481 QDir::toNativeSeparators(newDir.path()),
482 QDir::toNativeSeparators(albumDir.path())),
483 QMessageBox::Yes | QMessageBox::No,
484 qApp->activeWindow());
485
486 msgBox->button(QMessageBox::Yes)->setText(i18nc("@action:button", "Upgrade Database"));
487 msgBox->button(QMessageBox::Yes)->setIcon(QIcon::fromTheme(QLatin1String("view-refresh")));
488 msgBox->button(QMessageBox::No)->setText(i18nc("@action:button", "Create New Database"));
489 msgBox->button(QMessageBox::No)->setIcon(QIcon::fromTheme(QLatin1String("document-new")));
490 msgBox->setDefaultButton(QMessageBox::Yes);
491
492 int result = msgBox->exec();
493
494 if (result == QMessageBox::Yes)
495 {
496 // CoreDbSchemaUpdater expects Album Path to point to the album root of the 0.9 db file.
497 // Restore this situation.
498
499 KSharedConfigPtr config = KSharedConfig::openConfig();
500 KConfigGroup group = config->group(QLatin1String("Album Settings"));
501 group.writeEntry("Album Path", albumDir.path());
502 group.sync();
503 }
504 else if (result == QMessageBox::No)
505 {
506 moveToBackup(digikam3DB);
507 moveToBackup(digikamVeryOldDB);
508 }
509
510 delete msgBox;
511 }
512 }
513 }
514
515 void AlbumManager::changeDatabase(const DbEngineParameters& newParams)
516 {
517 ScanController::instance()->shutDown();
518
519 // if there is no file at the new place, copy old one
520
521 DbEngineParameters params = CoreDbAccess::parameters();
522
523 // New database type SQLITE
524
525 if (newParams.isSQLite())
526 {
527 const bool dbNameChanged = (params.getCoreDatabaseNameOrDir() != newParams.getCoreDatabaseNameOrDir());
528
529 QDir newDir(newParams.getCoreDatabaseNameOrDir());
530 QFileInfo newFile(newDir, QLatin1String("digikam4.db"));
531
532 if (!newFile.exists() && dbNameChanged)
533 {
534 QFileInfo digikam3DB(newDir, QLatin1String("digikam3.db"));
535 QFileInfo digikamVeryOldDB(newDir, QLatin1String("digikam.db"));
536
537 if (digikam3DB.exists() || digikamVeryOldDB.exists())
538 {
539 int result = -1;
540
541 if (params.isSQLite())
542 {
543 QPointer<QMessageBox> msgBox = new QMessageBox(QMessageBox::Warning,
544 i18nc("@title:window", "New Database Folder"),
545 i18n("<p>You have chosen the folder \"%1\" as the new place to store the database. "
546 "A database file from an older version of digiKam is found in this folder.</p> "
547 "<p>Would you like to upgrade the old database file, start with a new database, "
548 "or copy the current database to this location and continue using it?</p> ",
549 QDir::toNativeSeparators(newDir.path())),
550 QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel,
551 qApp->activeWindow());
552
553 msgBox->button(QMessageBox::Yes)->setText(i18nc("@action:button", "Upgrade Database"));
554 msgBox->button(QMessageBox::Yes)->setIcon(QIcon::fromTheme(QLatin1String("view-refresh")));
555 msgBox->button(QMessageBox::No)->setText(i18nc("@action:button", "Create New Database"));
556 msgBox->button(QMessageBox::No)->setIcon(QIcon::fromTheme(QLatin1String("document-new")));
557 msgBox->button(QMessageBox::Cancel)->setText(i18nc("@action:button", "Copy Current Database"));
558 msgBox->button(QMessageBox::Cancel)->setIcon(QIcon::fromTheme(QLatin1String("edit-copy")));
559 msgBox->setDefaultButton(QMessageBox::Yes);
560
561 result = msgBox->exec();
562 delete msgBox;
563 }
564 else
565 {
566 QPointer<QMessageBox> msgBox = new QMessageBox(QMessageBox::Warning,
567 i18nc("@title:window", "New Database Folder"),
568 i18n("<p>You have chosen the folder \"%1\" as the new place to store the database. "
569 "A database file from an older version of digiKam is found in this folder.</p> "
570 "<p>Would you like to upgrade the old database file or start with a new database?</p>",
571 QDir::toNativeSeparators(newDir.path())),
572 QMessageBox::Yes | QMessageBox::No,
573 qApp->activeWindow());
574
575 msgBox->button(QMessageBox::Yes)->setText(i18nc("@action:button", "Upgrade Database"));
576 msgBox->button(QMessageBox::Yes)->setIcon(QIcon::fromTheme(QLatin1String("view-refresh")));
577 msgBox->button(QMessageBox::No)->setText(i18nc("@action:button", "Create New Database"));
578 msgBox->button(QMessageBox::No)->setIcon(QIcon::fromTheme(QLatin1String("document-new")));
579 msgBox->setDefaultButton(QMessageBox::Yes);
580
581 result = msgBox->exec();
582 delete msgBox;
583 }
584
585 if (result == QMessageBox::Yes)
586 {
587 // CoreDbSchemaUpdater expects Album Path to point to the album root of the 0.9 db file.
588 // Restore this situation.
589
590 KSharedConfigPtr config = KSharedConfig::openConfig();
591 KConfigGroup group = config->group(QLatin1String("Album Settings"));
592 group.writeEntry(QLatin1String("Album Path"), newDir.path());
593 group.sync();
594 }
595 else if (result == QMessageBox::No)
596 {
597 moveToBackup(digikam3DB);
598 moveToBackup(digikamVeryOldDB);
599 }
600 else if (result == QMessageBox::Cancel)
601 {
602 QFileInfo oldFile(params.SQLiteDatabaseFile());
603 copyToNewLocation(oldFile, newFile, i18n("Failed to copy the old database file (\"%1\") "
604 "to its new location (\"%2\"). "
605 "Trying to upgrade old databases.",
606 QDir::toNativeSeparators(oldFile.filePath()),
607 QDir::toNativeSeparators(newFile.filePath())));
608 }
609 }
610 else
611 {
612 int result = QMessageBox::Yes;
613
614 if (params.isSQLite())
615 {
616 QPointer<QMessageBox> msgBox = new QMessageBox(QMessageBox::Warning,
617 i18nc("@title:window", "New Database Folder"),
618 i18n("<p>You have chosen the folder \"%1\" as the new place to store the database.</p>"
619 "<p>Would you like to copy the current database to this location "
620 "and continue using it, or start with a new database?</p> ",
621 QDir::toNativeSeparators(newDir.path())),
622 QMessageBox::Yes | QMessageBox::No,
623 qApp->activeWindow());
624
625 msgBox->button(QMessageBox::Yes)->setText(i18nc("@action:button", "Create New Database"));
626 msgBox->button(QMessageBox::Yes)->setIcon(QIcon::fromTheme(QLatin1String("document-new")));
627 msgBox->button(QMessageBox::No)->setText(i18nc("@action:button", "Copy Current Database"));
628 msgBox->button(QMessageBox::No)->setIcon(QIcon::fromTheme(QLatin1String("edit-copy")));
629 msgBox->setDefaultButton(QMessageBox::Yes);
630
631 result = msgBox->exec();
632 delete msgBox;
633 }
634
635 if (result == QMessageBox::No)
636 {
637 QFileInfo oldFile(params.SQLiteDatabaseFile());
638 copyToNewLocation(oldFile, newFile);
639 }
640 }
641 }
642 else if (dbNameChanged)
643 {
644 int result = QMessageBox::No;
645
646 if (params.isSQLite())
647 {
648 QPointer<QMessageBox> msgBox = new QMessageBox(QMessageBox::Warning,
649 i18nc("@title:window", "New Database Folder"),
650 i18n("<p>You have chosen the folder \"%1\" as the new place to store the database. "
651 "There is already a database file in this location.</p> "
652 "<p>Would you like to use this existing file as the new database, or remove it "
653 "and copy the current database to this place?</p> ",
654 QDir::toNativeSeparators(newDir.path())),
655 QMessageBox::Yes | QMessageBox::No,
656 qApp->activeWindow());
657
658 msgBox->button(QMessageBox::Yes)->setText(i18nc("@action:button", "Copy Current Database"));
659 msgBox->button(QMessageBox::Yes)->setIcon(QIcon::fromTheme(QLatin1String("edit-copy")));
660 msgBox->button(QMessageBox::No)->setText(i18nc("@action:button", "Use Existing File"));
661 msgBox->button(QMessageBox::No)->setIcon(QIcon::fromTheme(QLatin1String("document-open")));
662 msgBox->setDefaultButton(QMessageBox::Yes);
663
664 result = msgBox->exec();
665 delete msgBox;
666 }
667
668 if (result == QMessageBox::Yes)
669 {
670 // first backup
671
672 if (moveToBackup(newFile))
673 {
674 QFileInfo oldFile(params.SQLiteDatabaseFile());
675
676 // then copy
677
678 copyToNewLocation(oldFile, newFile);
679 }
680 }
681 }
682 }
683
684 ScanController::instance()->restart();
685
686 if (setDatabase(newParams, false))
687 {
688 QApplication::setOverrideCursor(Qt::WaitCursor);
689 startScan();
690 QApplication::restoreOverrideCursor();
691 ScanController::instance()->completeCollectionScan();
692 }
693 }
694
695 bool AlbumManager::databaseEqual(const DbEngineParameters& parameters) const
696 {
697 DbEngineParameters params = CoreDbAccess::parameters();
698
699 return (params == parameters);
700 }
701
702 bool AlbumManager::moveToBackup(const QFileInfo& info)
703 {
704 if (info.exists())
705 {
706 QFileInfo backup(info.dir(), info.fileName() +
707 QLatin1String("-backup-") +
708 QDateTime::currentDateTime().toString(Qt::ISODate));
709
710 bool ret = QDir().rename(info.filePath(), backup.filePath());
711
712 if (!ret)
713 {
714 QMessageBox::critical(qApp->activeWindow(), qApp->applicationName(),
715 i18n("Failed to backup the existing database file (\"%1\"). "
716 "Refusing to replace file without backup, using the existing file.",
717 QDir::toNativeSeparators(info.filePath())));
718 return false;
719 }
720 }
721
722 return true;
723 }
724
725 bool AlbumManager::copyToNewLocation(const QFileInfo& oldFile,
726 const QFileInfo& newFile,
727 const QString& otherMessage)
728 {
729 QString message = otherMessage;
730
731 if (message.isNull())
732 {
733 message = i18n("Failed to copy the old database file (\"%1\") "
734 "to its new location (\"%2\"). "
735 "Starting with an empty database.",
736 QDir::toNativeSeparators(oldFile.filePath()),
737 QDir::toNativeSeparators(newFile.filePath()));
738 }
739
740 bool ret = QFile::copy(oldFile.filePath(), newFile.filePath());
741
742 if (!ret)
743 {
744 QMessageBox::critical(qApp->activeWindow(), qApp->applicationName(), message);
745
746 return false;
747 }
748
749 return true;
750 }
751
752 bool AlbumManager::showDatabaseSetupPage(const QString& error, bool priority, const QString& suggestedAlbumRoot)
753 {
754 QApplication::restoreOverrideCursor();
755
756 QString errorMsg = error + i18n("<p><b>Please check the database settings in this dialog.</b></p>");
757
758 // We cannot use Setup::execSinglePage() as this already requires a core database.
759
760 QPointer<QDialog> setup = new QDialog(qApp->activeWindow());
761 QVBoxLayout* const layout = new QVBoxLayout(setup);
762 QLabel* const errorLabel = new QLabel(errorMsg, setup);
763 errorLabel->setWordWrap(true);
764 errorLabel->setTextFormat(Qt::RichText);
765 errorLabel->setAlignment(Qt::AlignCenter);
766 errorLabel->setFrameStyle(QFrame::StyledPanel | QFrame::Raised);
767 errorLabel->setStyleSheet(QLatin1String("QLabel { background-color: #FFDDDD; color: black; }"));
768 DatabaseSettingsWidget* const dbsettings = new DatabaseSettingsWidget(setup);
769 QDialogButtonBox* const buttons = new QDialogButtonBox(QDialogButtonBox::Ok |
770 QDialogButtonBox::Reset |
771 QDialogButtonBox::Cancel, setup);
772 buttons->button(QDialogButtonBox::Reset)->setText(i18nc("@action:button", "New database"));
773 buttons->button(QDialogButtonBox::Ok)->setDefault(true);
774
775 layout->addWidget(errorLabel);
776 layout->addWidget(dbsettings);
777 layout->addStretch(10);
778 layout->addWidget(buttons);
779
780 bool newDatabase = false;
781
782 connect(buttons->button(QDialogButtonBox::Ok), SIGNAL(clicked()),
783 setup, SLOT(accept()));
784
785 connect(buttons->button(QDialogButtonBox::Cancel), SIGNAL(clicked()),
786 setup, SLOT(reject()));
787
788 connect(buttons->button(QDialogButtonBox::Reset), &QPushButton::clicked,
789 this, [&newDatabase, setup]() // clazy:exclude=lambda-in-connect
790 {
791 newDatabase = true;
792 setup->accept();
793 }
794 );
795
796 ApplicationSettings* const settings = ApplicationSettings::instance();
797 dbsettings->setParametersFromSettings(settings);
798
799 if (setup->exec() != QDialog::Accepted)
800 {
801 delete setup;
802
803 return false;
804 }
805
806 DbEngineParameters dbParams = dbsettings->getDbEngineParameters();
807 settings->setDbEngineParameters(dbParams);
808 settings->saveSettings();
809
810 delete setup;
811
812 if (newDatabase)
813 {
814 if (dbParams.internalServer)
815 {
816 DatabaseServerError result = DatabaseServerStarter::instance()->startServerManagerProcess(dbParams);
817
818 if (result.getErrorType() != DatabaseServerError::NoErrors)
819 {
820 return false;
821 }
822 }
823
824 CoreDbAccess::setParameters(dbParams);
825
826 if (!CoreDbAccess::checkReadyForUse())
827 {
828 return false;
829 }
830 }
831
832 return (setDatabase(dbParams, priority, suggestedAlbumRoot));
833 }
834
835 } // namespace Digikam