File indexing completed on 2024-12-22 05:05:19

0001 // SPDX-FileCopyrightText: 2004 Marc Mutz <mutz@kde.org>
0002 // SPDX-FileCopyrightText: 2004 Ingo Kloecker <kloecker@kde.org>
0003 // SPDX-License-Identifier: GPL-2.0-or-later
0004 
0005 #include "bodypartformatterbasefactory.h"
0006 #include "bodypartformatter.h"
0007 #include "bodypartformatterbasefactory_p.h"
0008 #include "mimetreeparser_core_debug.h"
0009 
0010 #include <assert.h>
0011 
0012 using namespace MimeTreeParser;
0013 
0014 BodyPartFormatterBaseFactoryPrivate::BodyPartFormatterBaseFactoryPrivate(BodyPartFormatterBaseFactory *factory)
0015     : q(factory)
0016 {
0017 }
0018 
0019 BodyPartFormatterBaseFactoryPrivate::~BodyPartFormatterBaseFactoryPrivate()
0020 {
0021 }
0022 
0023 void BodyPartFormatterBaseFactoryPrivate::setup()
0024 {
0025     if (!all) {
0026         all = std::make_optional<TypeRegistry>();
0027         messageviewer_create_builtin_bodypart_formatters();
0028     }
0029 }
0030 
0031 void BodyPartFormatterBaseFactoryPrivate::insert(const char *type, const char *subtype, Interface::BodyPartFormatter *formatter)
0032 {
0033     if (!type || !*type || !subtype || !*subtype || !formatter || !all) {
0034         return;
0035     }
0036 
0037     auto type_it = all->find(type);
0038     if (type_it == all->end()) {
0039         type_it = all->insert(std::make_pair(type, SubtypeRegistry())).first;
0040         assert(type_it != all->end());
0041     }
0042 
0043     SubtypeRegistry &subtype_reg = type_it->second;
0044 
0045     subtype_reg.insert(std::make_pair(subtype, formatter));
0046 }
0047 
0048 BodyPartFormatterBaseFactory::BodyPartFormatterBaseFactory()
0049     : d(std::make_unique<BodyPartFormatterBaseFactoryPrivate>(this))
0050 {
0051 }
0052 
0053 BodyPartFormatterBaseFactory::~BodyPartFormatterBaseFactory() = default;
0054 
0055 void BodyPartFormatterBaseFactory::insert(const char *type, const char *subtype, Interface::BodyPartFormatter *formatter)
0056 {
0057     d->insert(type, subtype, formatter);
0058 }
0059 
0060 const SubtypeRegistry &BodyPartFormatterBaseFactory::subtypeRegistry(const char *type) const
0061 {
0062     if (!type || !*type) {
0063         type = "*"; // krazy:exclude=doublequote_chars
0064     }
0065 
0066     d->setup();
0067     assert(d->all);
0068 
0069     static SubtypeRegistry emptyRegistry;
0070     if (d->all->empty()) {
0071         return emptyRegistry;
0072     }
0073 
0074     auto type_it = d->all->find(type);
0075     if (type_it == d->all->end()) {
0076         type_it = d->all->find("*");
0077     }
0078     if (type_it == d->all->end()) {
0079         return emptyRegistry;
0080     }
0081 
0082     const SubtypeRegistry &subtype_reg = type_it->second;
0083     if (subtype_reg.empty()) {
0084         return emptyRegistry;
0085     }
0086     return subtype_reg;
0087 }