Version 6.4.0.3, tag libreoffice-6.4.0.3
[LibreOffice.git] / desktop / source / migration / migration.cxx
blobbe21788c40d152f5ffe2446ae4371f55a0a71a7e
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 * This file incorporates work covered by the following license notice:
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
20 #include <sal/config.h>
22 #include <algorithm>
23 #include <iterator>
24 #include <map>
25 #include <new>
26 #include <set>
28 #include <migration.hxx>
29 #include "migration_impl.hxx"
31 #include <sal/log.hxx>
32 #include <unotools/textsearch.hxx>
33 #include <comphelper/processfactory.hxx>
34 #include <comphelper/sequence.hxx>
35 #include <unotools/bootstrap.hxx>
36 #include <rtl/bootstrap.hxx>
37 #include <rtl/uri.hxx>
38 #include <i18nlangtag/lang.h>
39 #include <tools/diagnose_ex.h>
40 #include <tools/urlobj.hxx>
41 #include <osl/file.hxx>
42 #include <osl/security.hxx>
43 #include <unotools/configmgr.hxx>
45 #include <com/sun/star/configuration/Update.hpp>
46 #include <com/sun/star/configuration/theDefaultProvider.hpp>
47 #include <com/sun/star/lang/XInitialization.hpp>
48 #include <com/sun/star/task/XJob.hpp>
49 #include <com/sun/star/beans/NamedValue.hpp>
50 #include <com/sun/star/beans/XPropertySet.hpp>
51 #include <com/sun/star/util/XRefreshable.hpp>
52 #include <com/sun/star/util/XChangesBatch.hpp>
53 #include <com/sun/star/util/XStringSubstitution.hpp>
54 #include <com/sun/star/embed/ElementModes.hpp>
55 #include <com/sun/star/embed/FileSystemStorageFactory.hpp>
56 #include <com/sun/star/embed/XStorage.hpp>
57 #include <com/sun/star/ui/theModuleUIConfigurationManagerSupplier.hpp>
58 #include <com/sun/star/frame/theUICommandDescription.hpp>
59 #include <com/sun/star/ui/UIConfigurationManager.hpp>
60 #include <com/sun/star/ui/XUIConfiguration.hpp>
61 #include <com/sun/star/ui/XUIConfigurationStorage.hpp>
62 #include <com/sun/star/ui/XUIConfigurationPersistence.hpp>
64 using namespace osl;
65 using namespace std;
66 using namespace com::sun::star::task;
67 using namespace com::sun::star::lang;
68 using namespace com::sun::star::beans;
69 using namespace com::sun::star::util;
70 using namespace com::sun::star::container;
71 using com::sun::star::uno::Exception;
72 using namespace com::sun::star;
75 namespace desktop
78 static const char ITEM_DESCRIPTOR_COMMANDURL[] = "CommandURL";
79 static const char ITEM_DESCRIPTOR_CONTAINER[] = "ItemDescriptorContainer";
80 static const char ITEM_DESCRIPTOR_LABEL[] = "Label";
82 static OUString retrieveLabelFromCommand(const OUString& sCommand, const OUString& sModuleIdentifier)
84 OUString sLabel;
86 uno::Reference< container::XNameAccess > xUICommands;
87 uno::Reference< container::XNameAccess > const xNameAccess(
88 frame::theUICommandDescription::get(
89 ::comphelper::getProcessComponentContext()) );
90 xNameAccess->getByName( sModuleIdentifier ) >>= xUICommands;
91 if (xUICommands.is()) {
92 if ( !sCommand.isEmpty() ) {
93 OUString aStr;
94 ::uno::Sequence< beans::PropertyValue > aPropSeq;
95 try {
96 uno::Any a( xUICommands->getByName( sCommand ));
97 if ( a >>= aPropSeq ) {
98 for ( sal_Int32 i = 0; i < aPropSeq.getLength(); i++ ) {
99 if ( aPropSeq[i].Name == "Label" ) {
100 aPropSeq[i].Value >>= aStr;
101 break;
106 sLabel = aStr;
107 } catch (const container::NoSuchElementException&) {
108 sLabel = sCommand;
109 sal_Int32 nIndex = sLabel.indexOf(':');
110 if (nIndex>=0 && nIndex <= sLabel.getLength()-1)
111 sLabel = sLabel.copy(nIndex+1);
117 return sLabel;
120 static OUString mapModuleShortNameToIdentifier(const OUString& sShortName)
122 OUString sIdentifier;
124 if ( sShortName == "StartModule" )
125 sIdentifier = "com.sun.star.frame.StartModule";
127 else if ( sShortName == "swriter" )
128 sIdentifier = "com.sun.star.text.TextDocument";
130 else if ( sShortName == "scalc" )
131 sIdentifier = "com.sun.star.sheet.SpreadsheetDocument";
133 else if ( sShortName == "sdraw" )
134 sIdentifier = "com.sun.star.drawing.DrawingDocument";
136 else if ( sShortName == "simpress" )
137 sIdentifier = "com.sun.star.presentation.PresentationDocument";
139 else if ( sShortName == "smath" )
140 sIdentifier = "com.sun.star.formula.FormulaProperties";
142 else if ( sShortName == "schart" )
143 sIdentifier = "com.sun.star.chart2.ChartDocument";
145 else if ( sShortName == "BasicIDE" )
146 sIdentifier = "com.sun.star.script.BasicIDE";
148 else if ( sShortName == "dbapp" )
149 sIdentifier = "com.sun.star.sdb.OfficeDatabaseDocument";
151 else if ( sShortName == "sglobal" )
152 sIdentifier = "com.sun.star.text.GlobalDocument";
154 else if ( sShortName == "sweb" )
155 sIdentifier = "com.sun.star.text.WebDocument";
157 else if ( sShortName == "swxform" )
158 sIdentifier = "com.sun.star.xforms.XMLFormDocument";
160 else if ( sShortName == "sbibliography" )
161 sIdentifier = "com.sun.star.frame.Bibliography";
163 return sIdentifier;
166 bool MigrationImpl::alreadyMigrated()
168 OUString const MIGRATION_STAMP_NAME("/MIGRATED4");
169 OUString aStr = m_aInfo.userdata + MIGRATION_STAMP_NAME;
170 File aFile(aStr);
171 // create migration stamp, and/or check its existence
172 bool bRet = aFile.open (osl_File_OpenFlag_Write | osl_File_OpenFlag_Create | osl_File_OpenFlag_NoLock) == FileBase::E_EXIST;
173 SAL_INFO( "desktop.migration", "File '" << aStr << "' exists? " << bRet );
174 return bRet;
177 bool MigrationImpl::initializeMigration()
179 bool bRet = false;
181 if (!checkMigrationCompleted()) {
182 readAvailableMigrations(m_vMigrationsAvailable);
183 sal_Int32 nIndex = findPreferredMigrationProcess(m_vMigrationsAvailable);
184 // m_aInfo is now set to the preferred migration source
185 if ( nIndex >= 0 ) {
186 if (alreadyMigrated())
187 return false;
188 m_vrMigrations = readMigrationSteps(m_vMigrationsAvailable[nIndex].name);
191 bRet = !m_aInfo.userdata.isEmpty();
194 SAL_INFO( "desktop.migration", "Migration " << ( bRet ? "needed" : "not required" ) );
196 return bRet;
199 void Migration::migrateSettingsIfNecessary()
201 MigrationImpl aImpl;
203 if (! aImpl.initializeMigration() )
204 return;
206 bool bResult = false;
207 try {
208 bResult = aImpl.doMigration();
209 } catch (const Exception&) {
210 TOOLS_WARN_EXCEPTION( "desktop", "doMigration()");
212 OSL_ENSURE(bResult, "Migration has not been successful");
215 MigrationImpl::MigrationImpl()
219 MigrationImpl::~MigrationImpl()
223 // The main entry point for migrating settings
224 bool MigrationImpl::doMigration()
226 // compile file list for migration
227 m_vrFileList = compileFileList();
229 bool result = false;
230 try {
231 NewVersionUIInfo aNewVersionUIInfo;
232 std::vector< MigrationModuleInfo > vModulesInfo = dectectUIChangesForAllModules();
233 aNewVersionUIInfo.init(vModulesInfo);
235 copyFiles();
237 const OUString sMenubarResourceURL("private:resource/menubar/menubar");
238 const OUString sToolbarResourcePre("private:resource/toolbar/");
239 for (MigrationModuleInfo & i : vModulesInfo) {
240 OUString sModuleIdentifier = mapModuleShortNameToIdentifier(i.sModuleShortName);
241 if (sModuleIdentifier.isEmpty())
242 continue;
245 OUString aOldCfgDataPath = m_aInfo.userdata + "/user/config/soffice.cfg/modules/" + i.sModuleShortName;
246 uno::Sequence< uno::Any > lArgs {uno::makeAny(aOldCfgDataPath), uno::makeAny(embed::ElementModes::READ)};
248 uno::Reference< uno::XComponentContext > xContext(comphelper::getProcessComponentContext());
249 uno::Reference< lang::XSingleServiceFactory > xStorageFactory(embed::FileSystemStorageFactory::create(xContext));
250 uno::Reference< embed::XStorage > xModules(xStorageFactory->createInstanceWithArguments(lArgs), uno::UNO_QUERY);
251 uno::Reference< ui::XUIConfigurationManager2 > xOldCfgManager = ui::UIConfigurationManager::create(xContext);
253 if ( xModules.is() ) {
254 xOldCfgManager->setStorage( xModules );
255 xOldCfgManager->reload();
258 uno::Reference< ui::XUIConfigurationManager > xCfgManager = aNewVersionUIInfo.getConfigManager(i.sModuleShortName);
260 if (i.bHasMenubar) {
261 uno::Reference< container::XIndexContainer > xOldVersionMenuSettings(xOldCfgManager->getSettings(sMenubarResourceURL, true), uno::UNO_QUERY);
262 uno::Reference< container::XIndexContainer > xNewVersionMenuSettings = aNewVersionUIInfo.getNewMenubarSettings(i.sModuleShortName);
263 compareOldAndNewConfig(OUString(), xOldVersionMenuSettings, xNewVersionMenuSettings, sMenubarResourceURL);
264 mergeOldToNewVersion(xCfgManager, xNewVersionMenuSettings, sModuleIdentifier, sMenubarResourceURL);
267 sal_Int32 nToolbars = i.m_vToolbars.size();
268 if (nToolbars >0) {
269 for (sal_Int32 j=0; j<nToolbars; ++j) {
270 OUString sToolbarName = i.m_vToolbars[j];
271 OUString sToolbarResourceURL = sToolbarResourcePre + sToolbarName;
273 uno::Reference< container::XIndexContainer > xOldVersionToolbarSettings(xOldCfgManager->getSettings(sToolbarResourceURL, true), uno::UNO_QUERY);
274 uno::Reference< container::XIndexContainer > xNewVersionToolbarSettings = aNewVersionUIInfo.getNewToolbarSettings(i.sModuleShortName, sToolbarName);
275 compareOldAndNewConfig(OUString(), xOldVersionToolbarSettings, xNewVersionToolbarSettings, sToolbarResourceURL);
276 mergeOldToNewVersion(xCfgManager, xNewVersionToolbarSettings, sModuleIdentifier, sToolbarResourceURL);
280 m_aOldVersionItemsHashMap.clear();
283 // execute the migration items from Setup.xcu
284 copyConfig();
286 // execute custom migration services from Setup.xcu
287 // and refresh the cache
288 runServices();
289 uno::Reference< XRefreshable >(
290 configuration::theDefaultProvider::get(comphelper::getProcessComponentContext()),
291 uno::UNO_QUERY_THROW)->refresh();
293 result = true;
294 } catch (const css::uno::Exception &) {
295 TOOLS_WARN_EXCEPTION(
296 "desktop.migration",
297 "ignored Exception while migrating from version \"" << m_aInfo.productname
298 << "\" data \"" << m_aInfo.userdata << "\"");
301 // prevent running the migration multiple times
302 setMigrationCompleted();
303 return result;
306 void MigrationImpl::setMigrationCompleted()
308 try {
309 uno::Reference< XPropertySet > aPropertySet(getConfigAccess("org.openoffice.Setup/Office", true), uno::UNO_QUERY_THROW);
310 aPropertySet->setPropertyValue("MigrationCompleted", uno::makeAny(true));
311 uno::Reference< XChangesBatch >(aPropertySet, uno::UNO_QUERY_THROW)->commitChanges();
312 } catch (...) {
313 // fail silently
317 bool MigrationImpl::checkMigrationCompleted()
319 bool bMigrationCompleted = false;
320 try {
321 uno::Reference< XPropertySet > aPropertySet(
322 getConfigAccess("org.openoffice.Setup/Office"), uno::UNO_QUERY_THROW);
323 aPropertySet->getPropertyValue("MigrationCompleted") >>= bMigrationCompleted;
325 if( !bMigrationCompleted && getenv("SAL_DISABLE_USERMIGRATION" ) ) {
326 // migration prevented - fake its success
327 setMigrationCompleted();
328 bMigrationCompleted = true;
330 } catch (const Exception&) {
331 // just return false...
333 SAL_INFO( "desktop.migration", "Migration " << ( bMigrationCompleted ? "already completed" : "not done" ) );
335 return bMigrationCompleted;
338 static void insertSorted(migrations_available& rAvailableMigrations, supported_migration const & aSupportedMigration)
340 migrations_available::iterator pIter = std::find_if(rAvailableMigrations.begin(), rAvailableMigrations.end(),
341 [&aSupportedMigration](const supported_migration& rMigration) { return rMigration.nPriority < aSupportedMigration.nPriority; });
342 if (pIter != rAvailableMigrations.end())
343 rAvailableMigrations.insert(pIter, aSupportedMigration );
344 else
345 rAvailableMigrations.push_back( aSupportedMigration );
348 void MigrationImpl::readAvailableMigrations(migrations_available& rAvailableMigrations)
350 // get supported version names
351 uno::Reference< XNameAccess > aMigrationAccess(getConfigAccess("org.openoffice.Setup/Migration/SupportedVersions"), uno::UNO_SET_THROW);
352 uno::Sequence< OUString > seqSupportedVersions = aMigrationAccess->getElementNames();
354 const OUString aVersionIdentifiers( "VersionIdentifiers" );
355 const OUString aPriorityIdentifier( "Priority" );
357 for (sal_Int32 i=0; i<seqSupportedVersions.getLength(); i++) {
358 sal_Int32 nPriority( 0 );
359 uno::Sequence< OUString > seqVersions;
360 uno::Reference< XNameAccess > xMigrationData( aMigrationAccess->getByName(seqSupportedVersions[i]), uno::UNO_QUERY_THROW );
361 xMigrationData->getByName( aVersionIdentifiers ) >>= seqVersions;
362 xMigrationData->getByName( aPriorityIdentifier ) >>= nPriority;
364 supported_migration aSupportedMigration;
365 aSupportedMigration.name = seqSupportedVersions[i];
366 aSupportedMigration.nPriority = nPriority;
367 for (sal_Int32 j=0; j<seqVersions.getLength(); j++)
368 aSupportedMigration.supported_versions.push_back(seqVersions[j].trim());
369 insertSorted( rAvailableMigrations, aSupportedMigration );
370 SAL_INFO( "desktop.migration", " available migration '" << aSupportedMigration.name << "'" );
374 migrations_vr MigrationImpl::readMigrationSteps(const OUString& rMigrationName)
376 // get migration access
377 uno::Reference< XNameAccess > aMigrationAccess(getConfigAccess("org.openoffice.Setup/Migration/SupportedVersions"), uno::UNO_SET_THROW);
378 uno::Reference< XNameAccess > xMigrationData( aMigrationAccess->getByName(rMigrationName), uno::UNO_QUERY_THROW );
380 // get migration description from org.openoffice.Setup/Migration
381 // and build vector of migration steps
382 uno::Reference< XNameAccess > theNameAccess(xMigrationData->getByName("MigrationSteps"), uno::UNO_QUERY_THROW);
383 uno::Reference< XNameAccess > tmpAccess;
384 uno::Sequence< OUString > tmpSeq;
385 migrations_vr vrMigrations(new migrations_v);
386 const css::uno::Sequence<OUString> aMigrationSteps = theNameAccess->getElementNames();
387 for (const OUString& rMigrationStep : aMigrationSteps) {
388 // get current migration step
389 theNameAccess->getByName(rMigrationStep) >>= tmpAccess;
390 migration_step tmpStep;
392 // read included files from current step description
393 if (tmpAccess->getByName("IncludedFiles") >>= tmpSeq) {
394 for (const OUString& rSeqEntry : std::as_const(tmpSeq))
395 tmpStep.includeFiles.push_back(rSeqEntry);
398 // excluded files...
399 if (tmpAccess->getByName("ExcludedFiles") >>= tmpSeq) {
400 for (const OUString& rSeqEntry : std::as_const(tmpSeq))
401 tmpStep.excludeFiles.push_back(rSeqEntry);
404 // included nodes...
405 if (tmpAccess->getByName("IncludedNodes") >>= tmpSeq) {
406 for (const OUString& rSeqEntry : std::as_const(tmpSeq))
407 tmpStep.includeConfig.push_back(rSeqEntry);
410 // excluded nodes...
411 if (tmpAccess->getByName("ExcludedNodes") >>= tmpSeq) {
412 for (const OUString& rSeqEntry : std::as_const(tmpSeq))
413 tmpStep.excludeConfig.push_back(rSeqEntry);
416 // excluded extensions...
417 if (tmpAccess->getByName("ExcludedExtensions") >>= tmpSeq) {
418 for (const OUString& rSeqEntry : std::as_const(tmpSeq))
419 tmpStep.excludeExtensions.push_back(rSeqEntry);
422 // generic service
423 tmpAccess->getByName("MigrationService") >>= tmpStep.service;
425 vrMigrations->push_back(tmpStep);
427 return vrMigrations;
430 static FileBase::RC _checkAndCreateDirectory(INetURLObject const & dirURL)
432 FileBase::RC result = Directory::create(dirURL.GetMainURL(INetURLObject::DecodeMechanism::ToIUri));
433 if (result == FileBase::E_NOENT) {
434 INetURLObject baseURL(dirURL);
435 baseURL.removeSegment();
436 _checkAndCreateDirectory(baseURL);
437 return Directory::create(dirURL.GetMainURL(INetURLObject::DecodeMechanism::ToIUri));
438 } else
439 return result;
442 #if defined UNX && ! defined MACOSX
444 static const char XDG_CONFIG_PART[] = "/.config/";
446 OUString MigrationImpl::preXDGConfigDir(const OUString& rConfigDir)
448 OUString aPreXDGConfigPath;
449 const char* pXDGCfgHome = getenv("XDG_CONFIG_HOME");
451 // cater for XDG_CONFIG_HOME change
452 // If XDG_CONFIG_HOME is set then we;
453 // assume the user knows what they are doing ( room for improvement here, we could
454 // of course search the default config dir etc. also - but this is more complex,
455 // we would need to weigh results from the current config dir against matches in
456 // the 'old' config dir etc. ) - currently we just use the returned config dir.
457 // If XDG_CONFIG_HOME is NOT set;
458 // assume then we should now using the default $HOME/.config config location for
459 // our user profiles, however *all* previous libreoffice and openoffice.org
460 // configurations will be in the 'old' config directory and that's where we need
461 // to search - we convert the returned config dir to the 'old' dir
462 if ( !pXDGCfgHome && rConfigDir.endsWith( XDG_CONFIG_PART ) )
463 // remove trailing '.config/' but leave the terminating '/'
464 aPreXDGConfigPath = rConfigDir.copy( 0, rConfigDir.getLength() - sizeof( XDG_CONFIG_PART ) + 2 );
465 else
466 aPreXDGConfigPath = rConfigDir;
468 // the application-specific config dir is no longer prefixed by '.' because it is hidden under ".config"
469 // we have to add the '.' for the pre-XDG directory names
470 aPreXDGConfigPath += ".";
472 return aPreXDGConfigPath;
474 #endif
476 void MigrationImpl::setInstallInfoIfExist(
477 install_info& aInfo,
478 const OUString& rConfigDir,
479 const OUString& rVersion)
481 OUString url(INetURLObject(rConfigDir).GetMainURL(INetURLObject::DecodeMechanism::NONE));
482 osl::DirectoryItem item;
483 osl::FileStatus stat(osl_FileStatus_Mask_Type);
485 if (osl::DirectoryItem::get(url, item) == osl::FileBase::E_None
486 && item.getFileStatus(stat) == osl::FileBase::E_None
487 && stat.getFileType() == osl::FileStatus::Directory) {
488 aInfo.userdata = url;
489 aInfo.productname = rVersion;
493 install_info MigrationImpl::findInstallation(const strings_v& rVersions)
496 OUString aTopConfigDir;
497 osl::Security().getConfigDir( aTopConfigDir );
498 if ( !aTopConfigDir.isEmpty() && aTopConfigDir[ aTopConfigDir.getLength()-1 ] != '/' )
499 aTopConfigDir += "/";
501 #if defined UNX && ! defined MACOSX
502 OUString aPreXDGTopConfigDir = preXDGConfigDir(aTopConfigDir);
503 #endif
505 install_info aInfo;
506 for (auto const& elem : rVersions)
508 OUString aVersion, aProfileName;
509 sal_Int32 nSeparatorIndex = elem.indexOf('=');
510 if ( nSeparatorIndex != -1 ) {
511 aVersion = elem.copy( 0, nSeparatorIndex );
512 aProfileName = elem.copy( nSeparatorIndex+1 );
515 if ( !aVersion.isEmpty() && !aProfileName.isEmpty() &&
516 ( aInfo.userdata.isEmpty() ||
517 aProfileName.equalsIgnoreAsciiCase(
518 utl::ConfigManager::getProductName() ) ) ) {
519 setInstallInfoIfExist(aInfo, aTopConfigDir + aProfileName, aVersion);
520 #if defined UNX && ! defined MACOSX
521 //try preXDG path if the new one does not exist
522 if ( aInfo.userdata.isEmpty())
523 setInstallInfoIfExist(aInfo, aPreXDGTopConfigDir + aProfileName, aVersion);
524 #endif
528 return aInfo;
531 sal_Int32 MigrationImpl::findPreferredMigrationProcess(const migrations_available& rAvailableMigrations)
533 sal_Int32 nIndex( -1 );
534 sal_Int32 i( 0 );
536 for (auto const& availableMigration : rAvailableMigrations)
538 install_info aInstallInfo = findInstallation(availableMigration.supported_versions);
539 if (!aInstallInfo.productname.isEmpty() ) {
540 m_aInfo = aInstallInfo;
541 nIndex = i;
542 break;
544 ++i;
547 SAL_INFO( "desktop.migration", " preferred migration is from product '" << m_aInfo.productname << "'");
548 SAL_INFO( "desktop.migration", " and settings directory '" << m_aInfo.userdata << "'");
550 return nIndex;
553 strings_vr MigrationImpl::applyPatterns(const strings_v& vSet, const strings_v& vPatterns)
555 using namespace utl;
556 strings_vr vrResult(new strings_v);
557 for (auto const& pattern : vPatterns)
559 // find matches for this pattern in input set
560 // and copy them to the result
561 SearchParam param(pattern, SearchParam::SearchType::Regexp);
562 TextSearch ts(param, LANGUAGE_DONTKNOW);
563 sal_Int32 start = 0;
564 sal_Int32 end = 0;
565 for (auto const& elem : vSet)
567 end = elem.getLength();
568 if (ts.SearchForward(elem, &start, &end))
569 vrResult->push_back(elem);
572 return vrResult;
575 strings_vr MigrationImpl::getAllFiles(const OUString& baseURL) const
577 strings_vr vrResult(new strings_v);
579 // get sub dirs
580 Directory dir(baseURL);
581 if (dir.open() == FileBase::E_None) {
582 strings_v vSubDirs;
583 strings_vr vrSubResult;
585 // work through directory contents...
586 DirectoryItem item;
587 FileStatus fs(osl_FileStatus_Mask_Type | osl_FileStatus_Mask_FileURL);
588 while (dir.getNextItem(item) == FileBase::E_None) {
589 if (item.getFileStatus(fs) == FileBase::E_None) {
590 if (fs.getFileType() == FileStatus::Directory)
591 vSubDirs.push_back(fs.getFileURL());
592 else
593 vrResult->push_back(fs.getFileURL());
597 // recurse subfolders
598 for (auto const& subDir : vSubDirs)
600 vrSubResult = getAllFiles(subDir);
601 vrResult->insert(vrResult->end(), vrSubResult->begin(), vrSubResult->end());
604 return vrResult;
607 namespace
610 // removes elements of vector 2 in vector 1
611 strings_v subtract(strings_v const & va, strings_v const & vb)
613 strings_v a(va);
614 std::sort(a.begin(), a.end());
615 strings_v::iterator ae(std::unique(a.begin(), a.end()));
616 strings_v b(vb);
617 std::sort(b.begin(), b.end());
618 strings_v::iterator be(std::unique(b.begin(), b.end()));
619 strings_v c;
620 std::set_difference(a.begin(), ae, b.begin(), be, std::back_inserter(c));
621 return c;
626 strings_vr MigrationImpl::compileFileList()
629 strings_vr vrResult(new strings_v);
630 strings_vr vrInclude;
631 strings_vr vrExclude;
633 // get a list of all files:
634 strings_vr vrFiles = getAllFiles(m_aInfo.userdata);
636 // get a file list result for each migration step
637 for (auto const& rMigration : *m_vrMigrations)
639 vrInclude = applyPatterns(*vrFiles, rMigration.includeFiles);
640 vrExclude = applyPatterns(*vrFiles, rMigration.excludeFiles);
641 strings_v sub(subtract(*vrInclude, *vrExclude));
642 vrResult->insert(vrResult->end(), sub.begin(), sub.end());
644 return vrResult;
647 namespace
650 struct componentParts {
651 std::set< OUString > includedPaths;
652 std::set< OUString > excludedPaths;
655 typedef std::map< OUString, componentParts > Components;
657 bool getComponent(OUString const & path, OUString * component)
659 OSL_ASSERT(component != nullptr);
660 if (path.isEmpty() || path[0] != '/') {
661 SAL_INFO( "desktop.migration", "configuration migration in/exclude path " << path << " ignored (does not start with slash)" );
662 return false;
664 sal_Int32 i = path.indexOf('/', 1);
665 *component = i < 0 ? path.copy(1) : path.copy(1, i - 1);
666 return true;
671 void MigrationImpl::copyConfig()
673 Components comps;
674 for (auto const& rMigrationStep : *m_vrMigrations) {
675 for (const OUString& rIncludePath : rMigrationStep.includeConfig) {
676 OUString comp;
677 if (getComponent(rIncludePath, &comp)) {
678 comps[comp].includedPaths.insert(rIncludePath);
681 for (const OUString& rExcludePath : rMigrationStep.excludeConfig) {
682 OUString comp;
683 if (getComponent(rExcludePath, &comp)) {
684 comps[comp].excludedPaths.insert(rExcludePath);
689 // check if the shared registrymodifications.xcu file exists
690 bool bRegistryModificationsXcuExists = false;
691 OUString regFilePath = m_aInfo.userdata + "/user/registrymodifications.xcu";
692 File regFile(regFilePath);
693 ::osl::FileBase::RC nError = regFile.open(osl_File_OpenFlag_Read);
694 if ( nError == ::osl::FileBase::E_None ) {
695 bRegistryModificationsXcuExists = true;
696 regFile.close();
699 for (auto const& comp : comps)
701 if (!comp.second.includedPaths.empty()) {
702 if (!bRegistryModificationsXcuExists) {
703 // shared registrymodifications.xcu does not exists
704 // the configuration is split in many registry files
705 // determine the file names from the first element in included paths
706 OUStringBuffer buf(m_aInfo.userdata);
707 buf.append("/user/registry/data");
708 sal_Int32 n = 0;
709 do {
710 OUString seg(comp.first.getToken(0, '.', n));
711 OUString enc(
712 rtl::Uri::encode(
713 seg, rtl_UriCharClassPchar, rtl_UriEncodeStrict,
714 RTL_TEXTENCODING_UTF8));
715 if (enc.isEmpty() && !seg.isEmpty()) {
716 SAL_INFO( "desktop.migration", "configuration migration component " << comp.first << " ignored (cannot be encoded as file path)" );
717 goto next;
719 buf.append('/');
720 buf.append(enc);
721 } while (n >= 0);
722 buf.append(".xcu");
723 regFilePath = buf.toString();
725 configuration::Update::get(
726 comphelper::getProcessComponentContext())->
727 insertModificationXcuFile(
728 regFilePath,
729 comphelper::containerToSequence(comp.second.includedPaths),
730 comphelper::containerToSequence(comp.second.excludedPaths));
731 } else {
732 SAL_INFO( "desktop.migration", "configuration migration component " << comp.first << " ignored (only excludes, no includes)" );
734 next:
739 uno::Reference< XNameAccess > MigrationImpl::getConfigAccess(const sal_Char* pPath, bool bUpdate)
741 uno::Reference< XNameAccess > xNameAccess;
742 try {
743 OUString sAccessSrvc;
744 if (bUpdate)
745 sAccessSrvc = "com.sun.star.configuration.ConfigurationUpdateAccess";
746 else
747 sAccessSrvc = "com.sun.star.configuration.ConfigurationAccess";
749 OUString sConfigURL = OUString::createFromAscii(pPath);
751 uno::Reference< XMultiServiceFactory > theConfigProvider(
752 configuration::theDefaultProvider::get(
753 comphelper::getProcessComponentContext()));
755 // access the provider
756 uno::Sequence< uno::Any > theArgs {uno::makeAny(sConfigURL)};
757 xNameAccess.set(
758 theConfigProvider->createInstanceWithArguments(
759 sAccessSrvc, theArgs ), uno::UNO_QUERY_THROW );
760 } catch (const css::uno::Exception&) {
761 TOOLS_WARN_EXCEPTION("desktop.migration", "ignoring");
763 return xNameAccess;
766 void MigrationImpl::copyFiles()
768 OUString localName;
769 OUString destName;
770 OUString userInstall;
771 utl::Bootstrap::PathStatus aStatus;
772 aStatus = utl::Bootstrap::locateUserInstallation(userInstall);
773 if (aStatus == utl::Bootstrap::PATH_EXISTS) {
774 for (auto const& rFile : *m_vrFileList)
776 // remove installation prefix from file
777 localName = rFile.copy(m_aInfo.userdata.getLength());
778 if (localName.endsWith( "/autocorr/acor_.dat")) {
779 // Previous versions used an empty language tag for
780 // LANGUAGE_DONTKNOW with the "[All]" autocorrection entry.
781 // As of LibreOffice 4.0 it is 'und' for LANGUAGE_UNDETERMINED
782 // so the file name is "acor_und.dat".
783 localName = localName.copy( 0, localName.getLength() - 4) + "und.dat";
785 destName = userInstall + localName;
786 INetURLObject aURL(destName);
787 // check whether destination directory exists
788 aURL.removeSegment();
789 _checkAndCreateDirectory(aURL);
790 FileBase::RC copyResult = File::copy(rFile, destName);
791 if (copyResult != FileBase::E_None) {
792 SAL_WARN( "desktop", "Cannot copy " << rFile << " to " << destName);
795 } else {
796 OSL_FAIL("copyFiles: UserInstall does not exist");
800 void MigrationImpl::runServices()
802 // Build argument array
803 uno::Sequence< uno::Any > seqArguments(3);
804 seqArguments[0] <<= NamedValue("Productname",
805 uno::makeAny(m_aInfo.productname));
806 seqArguments[1] <<= NamedValue("UserData",
807 uno::makeAny(m_aInfo.userdata));
810 // create an instance of every migration service
811 // and execute the migration job
812 uno::Reference< XJob > xMigrationJob;
814 uno::Reference< uno::XComponentContext > xContext(comphelper::getProcessComponentContext());
815 for (auto const& rMigration : *m_vrMigrations)
817 if( !rMigration.service.isEmpty()) {
819 try {
820 // set black list for extension migration
821 uno::Sequence< OUString > seqExtBlackList;
822 sal_uInt32 nSize = rMigration.excludeExtensions.size();
823 if ( nSize > 0 )
824 seqExtBlackList = comphelper::arrayToSequence< OUString >(
825 rMigration.excludeExtensions.data(), nSize );
826 seqArguments[2] <<= NamedValue("ExtensionBlackList",
827 uno::makeAny( seqExtBlackList ));
829 xMigrationJob.set(
830 xContext->getServiceManager()->createInstanceWithArgumentsAndContext(rMigration.service, seqArguments, xContext),
831 uno::UNO_QUERY_THROW);
833 xMigrationJob->execute(uno::Sequence< NamedValue >());
836 } catch (const Exception&) {
837 TOOLS_WARN_EXCEPTION( "desktop", "Execution of migration service failed. Service: "
838 << rMigration.service);
839 } catch (...) {
840 SAL_WARN( "desktop", "Execution of migration service failed (Exception caught).\nService: "
841 << rMigration.service << "\nNo message available");
848 std::vector< MigrationModuleInfo > MigrationImpl::dectectUIChangesForAllModules() const
850 std::vector< MigrationModuleInfo > vModulesInfo;
851 const OUString MENUBAR("menubar");
852 const OUString TOOLBAR("toolbar");
854 uno::Sequence< uno::Any > lArgs {uno::makeAny(m_aInfo.userdata + "/user/config/soffice.cfg/modules"),
855 uno::makeAny(embed::ElementModes::READ)};
857 uno::Reference< lang::XSingleServiceFactory > xStorageFactory(
858 embed::FileSystemStorageFactory::create(comphelper::getProcessComponentContext()));
859 uno::Reference< embed::XStorage > xModules;
861 xModules.set(xStorageFactory->createInstanceWithArguments(lArgs), uno::UNO_QUERY);
862 if (!xModules.is())
863 return vModulesInfo;
865 uno::Sequence< OUString > lNames = xModules->getElementNames();
866 sal_Int32 nLength = lNames.getLength();
867 for (sal_Int32 i=0; i<nLength; ++i) {
868 OUString sModuleShortName = lNames[i];
869 uno::Reference< embed::XStorage > xModule = xModules->openStorageElement(sModuleShortName, embed::ElementModes::READ);
870 if (xModule.is()) {
871 MigrationModuleInfo aModuleInfo;
873 uno::Reference< embed::XStorage > xMenubar = xModule->openStorageElement(MENUBAR, embed::ElementModes::READ);
874 if (xMenubar.is()) {
875 if (xMenubar->getElementNames().hasElements()) {
876 aModuleInfo.sModuleShortName = sModuleShortName;
877 aModuleInfo.bHasMenubar = true;
881 uno::Reference< embed::XStorage > xToolbar = xModule->openStorageElement(TOOLBAR, embed::ElementModes::READ);
882 if (xToolbar.is()) {
883 const OUString RESOURCEURL_CUSTOM_ELEMENT("custom_");
884 sal_Int32 nCustomLen = 7;
886 ::uno::Sequence< OUString > lToolbars = xToolbar->getElementNames();
887 for (sal_Int32 j=0; j<lToolbars.getLength(); ++j) {
888 OUString sToolbarName = lToolbars[j];
889 if (sToolbarName.getLength()>=nCustomLen &&
890 sToolbarName.copy(0, nCustomLen) == RESOURCEURL_CUSTOM_ELEMENT)
891 continue;
893 aModuleInfo.sModuleShortName = sModuleShortName;
894 sal_Int32 nIndex = sToolbarName.lastIndexOf('.');
895 if (nIndex > 0) {
896 OUString sExtension(sToolbarName.copy(nIndex));
897 OUString sToolbarResourceName(sToolbarName.copy(0, nIndex));
898 if (!sToolbarResourceName.isEmpty() && sExtension == ".xml")
899 aModuleInfo.m_vToolbars.push_back(sToolbarResourceName);
904 if (!aModuleInfo.sModuleShortName.isEmpty())
905 vModulesInfo.push_back(aModuleInfo);
909 return vModulesInfo;
912 void MigrationImpl::compareOldAndNewConfig(const OUString& sParent,
913 const uno::Reference< container::XIndexContainer >& xIndexOld,
914 const uno::Reference< container::XIndexContainer >& xIndexNew,
915 const OUString& sResourceURL)
917 const OUString MENU_SEPARATOR(" | ");
919 std::vector< MigrationItem > vOldItems;
920 std::vector< MigrationItem > vNewItems;
921 uno::Sequence< beans::PropertyValue > aProp;
922 sal_Int32 nOldCount = xIndexOld->getCount();
923 sal_Int32 nNewCount = xIndexNew->getCount();
925 for (int n=0; n<nOldCount; ++n) {
926 MigrationItem aMigrationItem;
927 if (xIndexOld->getByIndex(n) >>= aProp) {
928 for(int i=0; i<aProp.getLength(); ++i) {
929 if ( aProp[i].Name == ITEM_DESCRIPTOR_COMMANDURL )
930 aProp[i].Value >>= aMigrationItem.m_sCommandURL;
931 else if ( aProp[i].Name == ITEM_DESCRIPTOR_CONTAINER )
932 aProp[i].Value >>= aMigrationItem.m_xPopupMenu;
935 if (!aMigrationItem.m_sCommandURL.isEmpty())
936 vOldItems.push_back(aMigrationItem);
940 for (int n=0; n<nNewCount; ++n) {
941 MigrationItem aMigrationItem;
942 if (xIndexNew->getByIndex(n) >>= aProp) {
943 for(int i=0; i<aProp.getLength(); ++i) {
944 if ( aProp[i].Name == ITEM_DESCRIPTOR_COMMANDURL )
945 aProp[i].Value >>= aMigrationItem.m_sCommandURL;
946 else if ( aProp[i].Name == ITEM_DESCRIPTOR_CONTAINER )
947 aProp[i].Value >>= aMigrationItem.m_xPopupMenu;
950 if (!aMigrationItem.m_sCommandURL.isEmpty())
951 vNewItems.push_back(aMigrationItem);
955 OUString sSibling;
956 for (auto const& oldItem : vOldItems)
958 std::vector< MigrationItem >::iterator pFound = std::find(vNewItems.begin(), vNewItems.end(), oldItem);
959 if (pFound != vNewItems.end() && oldItem.m_xPopupMenu.is()) {
960 OUString sName;
961 if (!sParent.isEmpty())
962 sName = sParent + MENU_SEPARATOR + oldItem.m_sCommandURL;
963 else
964 sName = oldItem.m_sCommandURL;
965 compareOldAndNewConfig(sName, oldItem.m_xPopupMenu, pFound->m_xPopupMenu, sResourceURL);
966 } else if (pFound == vNewItems.end()) {
967 MigrationItem aMigrationItem(sParent, sSibling, oldItem.m_sCommandURL, oldItem.m_xPopupMenu);
968 if (m_aOldVersionItemsHashMap.find(sResourceURL)==m_aOldVersionItemsHashMap.end()) {
969 std::vector< MigrationItem > vMigrationItems;
970 m_aOldVersionItemsHashMap.emplace(sResourceURL, vMigrationItems);
971 m_aOldVersionItemsHashMap[sResourceURL].push_back(aMigrationItem);
972 } else {
973 if (std::find(m_aOldVersionItemsHashMap[sResourceURL].begin(), m_aOldVersionItemsHashMap[sResourceURL].end(), aMigrationItem)==m_aOldVersionItemsHashMap[sResourceURL].end())
974 m_aOldVersionItemsHashMap[sResourceURL].push_back(aMigrationItem);
978 sSibling = oldItem.m_sCommandURL;
982 void MigrationImpl::mergeOldToNewVersion(const uno::Reference< ui::XUIConfigurationManager >& xCfgManager,
983 const uno::Reference< container::XIndexContainer>& xIndexContainer,
984 const OUString& sModuleIdentifier,
985 const OUString& sResourceURL)
987 MigrationHashMap::iterator pFound = m_aOldVersionItemsHashMap.find(sResourceURL);
988 if (pFound==m_aOldVersionItemsHashMap.end())
989 return;
991 for (auto const& elem : pFound->second)
993 uno::Reference< container::XIndexContainer > xTemp = xIndexContainer;
995 OUString sParentNodeName = elem.m_sParentNodeName;
996 sal_Int32 nIndex = 0;
997 do {
998 OUString sToken = sParentNodeName.getToken(0, '|', nIndex).trim();
999 if (sToken.isEmpty())
1000 break;
1002 sal_Int32 nCount = xTemp->getCount();
1003 for (sal_Int32 i=0; i<nCount; ++i) {
1004 OUString sCommandURL;
1005 OUString sLabel;
1006 uno::Reference< container::XIndexContainer > xChild;
1008 uno::Sequence< beans::PropertyValue > aPropSeq;
1009 xTemp->getByIndex(i) >>= aPropSeq;
1010 for (sal_Int32 j=0; j<aPropSeq.getLength(); ++j) {
1011 OUString sPropName = aPropSeq[j].Name;
1012 if ( sPropName == ITEM_DESCRIPTOR_COMMANDURL )
1013 aPropSeq[j].Value >>= sCommandURL;
1014 else if ( sPropName == ITEM_DESCRIPTOR_LABEL )
1015 aPropSeq[j].Value >>= sLabel;
1016 else if ( sPropName == ITEM_DESCRIPTOR_CONTAINER )
1017 aPropSeq[j].Value >>= xChild;
1020 if (sCommandURL == sToken) {
1021 xTemp = xChild;
1022 break;
1026 } while (nIndex >= 0);
1028 if (nIndex == -1) {
1029 uno::Sequence< beans::PropertyValue > aPropSeq {
1030 beans::PropertyValue(ITEM_DESCRIPTOR_COMMANDURL, 0, uno::makeAny(elem.m_sCommandURL), beans::PropertyState_DIRECT_VALUE),
1031 beans::PropertyValue(ITEM_DESCRIPTOR_LABEL, 0, uno::makeAny(retrieveLabelFromCommand(elem.m_sCommandURL, sModuleIdentifier)), beans::PropertyState_DIRECT_VALUE),
1032 beans::PropertyValue(ITEM_DESCRIPTOR_CONTAINER, 0, uno::makeAny(elem.m_xPopupMenu), beans::PropertyState_DIRECT_VALUE)
1035 if (elem.m_sPrevSibling.isEmpty())
1036 xTemp->insertByIndex(0, uno::makeAny(aPropSeq));
1037 else {
1038 sal_Int32 nCount = xTemp->getCount();
1039 sal_Int32 i = 0;
1040 for (; i<nCount; ++i) {
1041 OUString sCmd;
1042 uno::Sequence< beans::PropertyValue > aTempPropSeq;
1043 xTemp->getByIndex(i) >>= aTempPropSeq;
1044 for (sal_Int32 j=0; j<aTempPropSeq.getLength(); ++j) {
1045 if ( aTempPropSeq[j].Name == ITEM_DESCRIPTOR_COMMANDURL ) {
1046 aTempPropSeq[j].Value >>= sCmd;
1047 break;
1051 if (sCmd == elem.m_sPrevSibling)
1052 break;
1055 xTemp->insertByIndex(i+1, uno::makeAny(aPropSeq));
1060 if (xIndexContainer.is())
1061 xCfgManager->replaceSettings(sResourceURL, xIndexContainer);
1063 uno::Reference< ui::XUIConfigurationPersistence > xUIConfigurationPersistence(xCfgManager, uno::UNO_QUERY);
1064 if (xUIConfigurationPersistence.is())
1065 xUIConfigurationPersistence->store();
1068 uno::Reference< ui::XUIConfigurationManager > NewVersionUIInfo::getConfigManager(const OUString& sModuleShortName) const
1070 uno::Reference< ui::XUIConfigurationManager > xCfgManager;
1072 for ( const css::beans::PropertyValue& rProp : m_lCfgManagerSeq) {
1073 if (rProp.Name == sModuleShortName) {
1074 rProp.Value >>= xCfgManager;
1075 break;
1079 return xCfgManager;
1082 uno::Reference< container::XIndexContainer > NewVersionUIInfo::getNewMenubarSettings(const OUString& sModuleShortName) const
1084 uno::Reference< container::XIndexContainer > xNewMenuSettings;
1086 for (sal_Int32 i=0; i<m_lNewVersionMenubarSettingsSeq.getLength(); ++i) {
1087 if (m_lNewVersionMenubarSettingsSeq[i].Name == sModuleShortName) {
1088 m_lNewVersionMenubarSettingsSeq[i].Value >>= xNewMenuSettings;
1089 break;
1093 return xNewMenuSettings;
1096 uno::Reference< container::XIndexContainer > NewVersionUIInfo::getNewToolbarSettings(const OUString& sModuleShortName, const OUString& sToolbarName) const
1098 uno::Reference< container::XIndexContainer > xNewToolbarSettings;
1100 for (sal_Int32 i=0; i<m_lNewVersionToolbarSettingsSeq.getLength(); ++i) {
1101 if (m_lNewVersionToolbarSettingsSeq[i].Name == sModuleShortName) {
1102 uno::Sequence< beans::PropertyValue > lToolbarSettingsSeq;
1103 m_lNewVersionToolbarSettingsSeq[i].Value >>= lToolbarSettingsSeq;
1104 for (sal_Int32 j=0; j<lToolbarSettingsSeq.getLength(); ++j) {
1105 if (lToolbarSettingsSeq[j].Name == sToolbarName) {
1106 lToolbarSettingsSeq[j].Value >>= xNewToolbarSettings;
1107 break;
1111 break;
1115 return xNewToolbarSettings;
1118 void NewVersionUIInfo::init(const std::vector< MigrationModuleInfo >& vModulesInfo)
1120 m_lCfgManagerSeq.resize(vModulesInfo.size());
1121 m_lNewVersionMenubarSettingsSeq.realloc(vModulesInfo.size());
1122 m_lNewVersionToolbarSettingsSeq.realloc(vModulesInfo.size());
1124 const OUString sMenubarResourceURL("private:resource/menubar/menubar");
1125 const OUString sToolbarResourcePre("private:resource/toolbar/");
1127 uno::Reference< ui::XModuleUIConfigurationManagerSupplier > xModuleCfgSupplier = ui::theModuleUIConfigurationManagerSupplier::get( ::comphelper::getProcessComponentContext() );
1129 for (size_t i=0; i<vModulesInfo.size(); ++i) {
1130 OUString sModuleIdentifier = mapModuleShortNameToIdentifier(vModulesInfo[i].sModuleShortName);
1131 if (!sModuleIdentifier.isEmpty()) {
1132 uno::Reference< ui::XUIConfigurationManager > xCfgManager = xModuleCfgSupplier->getUIConfigurationManager(sModuleIdentifier);
1133 m_lCfgManagerSeq[i].Name = vModulesInfo[i].sModuleShortName;
1134 m_lCfgManagerSeq[i].Value <<= xCfgManager;
1136 if (vModulesInfo[i].bHasMenubar) {
1137 m_lNewVersionMenubarSettingsSeq[i].Name = vModulesInfo[i].sModuleShortName;
1138 m_lNewVersionMenubarSettingsSeq[i].Value <<= xCfgManager->getSettings(sMenubarResourceURL, true);
1141 sal_Int32 nToolbars = vModulesInfo[i].m_vToolbars.size();
1142 if (nToolbars > 0) {
1143 uno::Sequence< beans::PropertyValue > lPropSeq(nToolbars);
1144 for (sal_Int32 j=0; j<nToolbars; ++j) {
1145 OUString sToolbarName = vModulesInfo[i].m_vToolbars[j];
1146 OUString sToolbarResourceURL = sToolbarResourcePre + sToolbarName;
1148 lPropSeq[j].Name = sToolbarName;
1149 lPropSeq[j].Value <<= xCfgManager->getSettings(sToolbarResourceURL, true);
1152 m_lNewVersionToolbarSettingsSeq[i].Name = vModulesInfo[i].sModuleShortName;
1153 m_lNewVersionToolbarSettingsSeq[i].Value <<= lPropSeq;
1159 } // namespace desktop
1161 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */