Browse Source

Added some free functions to help make XML parsing less verbose: parseXML()

tags/2021-05-28
jules 6 years ago
parent
commit
768139a298
23 changed files with 116 additions and 94 deletions
  1. +1
    -1
      examples/GUI/WidgetsDemo.h
  2. +1
    -2
      extras/NetworkGraphicsDemo/Source/Demos.h
  3. +1
    -3
      extras/Projucer/Source/Application/Windows/jucer_SVGPathDataWindowComponent.h
  4. +1
    -1
      extras/Projucer/Source/Application/jucer_CommandLine.cpp
  5. +1
    -5
      extras/Projucer/Source/CodeEditor/jucer_ItemPreviewComponent.h
  6. +2
    -6
      extras/Projucer/Source/ComponentEditor/UI/jucer_JucerDocumentEditor.cpp
  7. +1
    -1
      extras/Projucer/Source/LiveBuildEngine/jucer_CompileEngineClient.cpp
  8. +4
    -2
      extras/Projucer/Source/Project/UI/jucer_ProjectContentComponent.cpp
  9. +1
    -1
      extras/Projucer/Source/Project/jucer_Project.cpp
  10. +10
    -5
      extras/Projucer/Source/ProjectSaving/jucer_ProjectExport_Android.h
  11. +2
    -4
      extras/Projucer/Source/ProjectSaving/jucer_ProjectExport_Xcode.h
  12. +6
    -6
      extras/Projucer/Source/Settings/jucer_AppearanceSettings.cpp
  13. +2
    -4
      extras/Projucer/Source/Wizards/jucer_TemplateThumbnailsComponent.h
  14. +10
    -9
      modules/juce_audio_formats/codecs/juce_WavAudioFormat.cpp
  15. +3
    -3
      modules/juce_audio_processors/format_types/juce_VSTPluginFormat.cpp
  16. +10
    -0
      modules/juce_core/xml/juce_XmlDocument.cpp
  17. +25
    -5
      modules/juce_core/xml/juce_XmlDocument.h
  18. +4
    -4
      modules/juce_events/native/juce_win32_Messaging.cpp
  19. +4
    -6
      modules/juce_graphics/native/juce_linux_Fonts.cpp
  20. +1
    -1
      modules/juce_gui_basics/lookandfeel/juce_LookAndFeel_V2.cpp
  21. +2
    -1
      modules/juce_gui_basics/misc/juce_JUCESplashScreen.cpp
  22. +21
    -19
      modules/juce_gui_basics/widgets/juce_TableHeaderComponent.cpp
  23. +3
    -5
      modules/juce_product_unlocking/marketplace/juce_OnlineUnlockStatus.cpp

+ 1
- 1
examples/GUI/WidgetsDemo.h View File

@@ -1030,7 +1030,7 @@ private:
// this loads the embedded database XML file into memory
void loadData()
{
demoData.reset (XmlDocument::parse (loadEntireAssetIntoString ("demo table data.xml")));
demoData = parseXML (loadEntireAssetIntoString ("demo table data.xml"));
dataList = demoData->getChildByName ("DATA");
columnList = demoData->getChildByName ("COLUMNS");


+ 1
- 2
extras/NetworkGraphicsDemo/Source/Demos.h View File

@@ -84,8 +84,7 @@ struct BackgroundLogo : public AnimatedContent
</svg>
)blahblah";
std::unique_ptr<XmlElement> svg (XmlDocument::parse (logoData));
logo.reset (Drawable::createFromSVG (*svg));
logo.reset (Drawable::createFromSVG (*parseXML (logoData)));
}
String getName() const override { return "Background Image"; }


+ 1
- 3
extras/Projucer/Source/Application/Windows/jucer_SVGPathDataWindowComponent.h View File

@@ -163,9 +163,7 @@ public:
dragOver = false;
repaint();
std::unique_ptr<XmlElement> element (XmlDocument::parse (File (files[0])));
if (element != nullptr)
if (auto element = parseXML (File (files[0])))
{
if (auto* ePath = element->getChildByName ("path"))
userText.setText (ePath->getStringAttribute ("d"), true);


+ 1
- 1
extras/Projucer/Source/Application/jucer_CommandLine.cpp View File

@@ -713,7 +713,7 @@ namespace
#endif
auto settingsFile = userAppData.getChildFile ("Projucer").getChildFile ("Projucer.settings");
std::unique_ptr<XmlElement> xml (XmlDocument::parse (settingsFile));
auto xml = parseXML (settingsFile);
if (xml == nullptr)
ConsoleApplication::fail ("Settings file not valid!");


+ 1
- 5
extras/Projucer/Source/CodeEditor/jucer_ItemPreviewComponent.h View File

@@ -108,12 +108,8 @@ private:
}
if (drawable == nullptr)
{
std::unique_ptr<XmlElement> svg (XmlDocument::parse (file));
if (svg != nullptr)
if (auto svg = parseXML (file))
drawable.reset (Drawable::createFromSVG (*svg));
}
facts.removeEmptyStrings (true);
}


+ 2
- 6
extras/Projucer/Source/ComponentEditor/UI/jucer_JucerDocumentEditor.cpp View File

@@ -938,9 +938,7 @@ void JucerDocumentEditor::getCommandInfo (const CommandID commandID, Application
bool canPaste = false;
std::unique_ptr<XmlElement> doc (XmlDocument::parse (SystemClipboard::getTextFromClipboard()));
if (doc != nullptr)
if (auto doc = parseXML (SystemClipboard::getTextFromClipboard()))
{
if (doc->hasTagName (ComponentLayout::clipboardXmlTag))
canPaste = (currentLayout != nullptr);
@@ -1156,9 +1154,7 @@ bool JucerDocumentEditor::perform (const InvocationInfo& info)
case StandardApplicationCommandIDs::paste:
{
std::unique_ptr<XmlElement> doc (XmlDocument::parse (SystemClipboard::getTextFromClipboard()));
if (doc != nullptr)
if (auto doc = parseXML (SystemClipboard::getTextFromClipboard()))
{
if (doc->hasTagName (ComponentLayout::clipboardXmlTag))
{


+ 1
- 1
extras/Projucer/Source/LiveBuildEngine/jucer_CompileEngineClient.cpp View File

@@ -422,7 +422,7 @@ private:
{
auto liveModules = project.getProjectRoot().getChildWithName (Ids::MODULES);
std::unique_ptr<XmlElement> xml (XmlDocument::parse (project.getFile()));
auto xml = parseXML (project.getFile());
if (xml == nullptr || ! xml->hasTagName (Ids::JUCERPROJECT.toString()))
return false;


+ 4
- 2
extras/Projucer/Source/Project/UI/jucer_ProjectContentComponent.cpp View File

@@ -39,8 +39,10 @@ struct LogoComponent : public Component
{
LogoComponent()
{
std::unique_ptr<XmlElement> svg (XmlDocument::parse (BinaryData::background_logo_svg));
logo.reset (Drawable::createFromSVG (*svg));
if (auto svg = parseXML (BinaryData::background_logo_svg))
logo.reset (Drawable::createFromSVG (*svg));
else
jassertfalse;
}
void paint (Graphics& g) override


+ 1
- 1
extras/Projucer/Source/Project/jucer_Project.cpp View File

@@ -552,7 +552,7 @@ static void forgetRecentFile (const File& file)
//==============================================================================
Result Project::loadDocument (const File& file)
{
std::unique_ptr<XmlElement> xml (XmlDocument::parse (file));
auto xml = parseXML (file);
if (xml == nullptr || ! xml->hasTagName (Ids::JUCERPROJECT.toString()))
return Result::fail ("Not a valid Jucer project!");


+ 10
- 5
extras/Projucer/Source/ProjectSaving/jucer_ProjectExport_Android.h View File

@@ -1404,12 +1404,17 @@ private:
customStringsXmlContent << cfg.getCustomStringsXml();
customStringsXmlContent << "\n</resources>";
std::unique_ptr<XmlElement> strings (XmlDocument::parse (customStringsXmlContent));
String dir = cfg.isDebug() ? "debug" : "release";
String subPath = "app/src/" + dir + "/res/values/string.xml";
if (auto strings = parseXML (customStringsXmlContent))
{
String dir = cfg.isDebug() ? "debug" : "release";
String subPath = "app/src/" + dir + "/res/values/string.xml";
writeXmlOrThrow (*strings, folder.getChildFile (subPath), "utf-8", 100, true);
writeXmlOrThrow (*strings, folder.getChildFile (subPath), "utf-8", 100, true);
}
else
{
jassertfalse; // needs handling?
}
}
}


+ 2
- 4
extras/Projucer/Source/ProjectSaving/jucer_ProjectExport_Xcode.h View File

@@ -1345,7 +1345,7 @@ public:
if (! shouldCreatePList())
return;
std::unique_ptr<XmlElement> plist (XmlDocument::parse (owner.getPListToMergeString()));
auto plist = parseXML (owner.getPListToMergeString());
if (plist == nullptr || ! plist->hasTagName ("plist"))
plist.reset (new XmlElement ("plist"));
@@ -3195,9 +3195,7 @@ private:
bool xcschemeManagementPlistMatchesTargets (const File& plist) const
{
std::unique_ptr<XmlElement> xml (XmlDocument::parse (plist));
if (xml != nullptr)
if (auto xml = parseXML (plist))
if (auto* dict = xml->getChildByName ("dict"))
return parseNamesOfTargetsFromPlist (*dict) == getNamesOfTargets();


+ 6
- 6
extras/Projucer/Source/Settings/jucer_AppearanceSettings.cpp View File

@@ -64,13 +64,11 @@ File AppearanceSettings::getSchemesFolder()
void AppearanceSettings::writeDefaultSchemeFile (const String& xmlString, const String& name)
{
const File file (getSchemesFolder().getChildFile (name).withFileExtension (getSchemeFileSuffix()));
auto file = getSchemesFolder().getChildFile (name).withFileExtension (getSchemeFileSuffix());
AppearanceSettings settings (false);
std::unique_ptr<XmlElement> xml (XmlDocument::parse (xmlString));
if (xml != nullptr)
if (auto xml = parseXML (xmlString))
settings.readFromXML (*xml);
settings.writeToFile (file);
@@ -132,8 +130,10 @@ bool AppearanceSettings::readFromXML (const XmlElement& xml)
bool AppearanceSettings::readFromFile (const File& file)
{
const std::unique_ptr<XmlElement> xml (XmlDocument::parse (file));
return xml != nullptr && readFromXML (*xml);
if (auto xml = parseXML (file))
return readFromXML (*xml);
return false;
}
bool AppearanceSettings::writeToFile (const File& file) const


+ 2
- 4
extras/Projucer/Source/Wizards/jucer_TemplateThumbnailsComponent.h View File

@@ -39,15 +39,13 @@ public:
: DrawableButton (buttonName, buttonStyle)
{
// svg for thumbnail icon
std::unique_ptr<XmlElement> svg (XmlDocument::parse (thumbSvg));
auto svg = parseXML (thumbSvg);
jassert (svg != nullptr);
thumb.reset (Drawable::createFromSVG (*svg));
// svg for thumbnail background highlight
std::unique_ptr<XmlElement> backSvg (XmlDocument::parse (BinaryData::wizard_Highlight_svg));
auto backSvg = parseXML (BinaryData::wizard_Highlight_svg);
jassert (backSvg != nullptr);
hoverBackground.reset (Drawable::createFromSVG (*backSvg));
name = buttonName;


+ 10
- 9
modules/juce_audio_formats/codecs/juce_WavAudioFormat.cpp View File

@@ -849,20 +849,21 @@ namespace WavFileHelpers
{
static void addToMetadata (StringPairArray& destValues, const String& source)
{
std::unique_ptr<XmlElement> xml (XmlDocument::parse (source));
if (xml != nullptr && xml->hasTagName ("ebucore:ebuCoreMain"))
if (auto xml = parseXML (source))
{
if (auto* xml2 = xml->getChildByName ("ebucore:coreMetadata"))
if (xml->hasTagName ("ebucore:ebuCoreMain"))
{
if (auto* xml3 = xml2->getChildByName ("ebucore:identifier"))
if (auto xml2 = xml->getChildByName ("ebucore:coreMetadata"))
{
if (auto* xml4 = xml3->getChildByName ("dc:identifier"))
if (auto xml3 = xml2->getChildByName ("ebucore:identifier"))
{
auto ISRCCode = xml4->getAllSubText().fromFirstOccurrenceOf ("ISRC:", false, true);
if (auto xml4 = xml3->getChildByName ("dc:identifier"))
{
auto ISRCCode = xml4->getAllSubText().fromFirstOccurrenceOf ("ISRC:", false, true);
if (ISRCCode.isNotEmpty())
destValues.set (WavAudioFormat::ISRC, ISRCCode);
if (ISRCCode.isNotEmpty())
destValues.set (WavAudioFormat::ISRC, ISRCCode);
}
}
}
}


+ 3
- 3
modules/juce_audio_processors/format_types/juce_VSTPluginFormat.cpp View File

@@ -661,11 +661,11 @@ struct ModuleHandle : public ReferenceCountedObject
if (moduleMain != nullptr)
{
vstXml.reset (XmlDocument::parse (file.withFileExtension ("vstxml")));
vstXml = parseXML (file.withFileExtension ("vstxml"));
#if JUCE_WINDOWS
if (vstXml == nullptr)
vstXml.reset (XmlDocument::parse (getDLLResource (file, "VSTXML", 1)));
vstXml = parseXML (getDLLResource (file, "VSTXML", 1));
#endif
}
@@ -772,7 +772,7 @@ struct ModuleHandle : public ReferenceCountedObject
.findChildFiles (File::findFiles, false, "*.vstxml");
if (! vstXmlFiles.isEmpty())
vstXml.reset (XmlDocument::parse (vstXmlFiles.getReference(0)));
vstXml = parseXML (vstXmlFiles.getReference(0));
}
}


+ 10
- 0
modules/juce_core/xml/juce_XmlDocument.cpp View File

@@ -40,6 +40,16 @@ XmlElement* XmlDocument::parse (const String& xmlData)
return doc.getDocumentElement();
}
std::unique_ptr<XmlElement> parseXML (const String& textToParse)
{
return std::unique_ptr<XmlElement> (XmlDocument::parse (textToParse));
}
std::unique_ptr<XmlElement> parseXML (const File& fileToParse)
{
return std::unique_ptr<XmlElement> (XmlDocument::parse (fileToParse));
}
void XmlDocument::setInputSource (InputSource* newSource) noexcept
{
inputSource.reset (newSource);


+ 25
- 5
modules/juce_core/xml/juce_XmlDocument.h View File

@@ -47,14 +47,15 @@ namespace juce
@endcode
Or you can use the static helper methods for quick parsing..
Or you can use the helper functions for much less verbose parsing..
@code
std::unique_ptr<XmlElement> xml (XmlDocument::parse (myXmlFile));
if (xml != nullptr && xml->hasTagName ("foobar"))
if (auto xml = parseXML (myXmlFile))
{
...etc
if (xml->hasTagName ("foobar"))
{
...etc
}
}
@endcode
@@ -132,12 +133,14 @@ public:
//==============================================================================
/** A handy static method that parses a file.
This is a shortcut for creating an XmlDocument object and calling getDocumentElement() on it.
An even better shortcut is the juce::parseXML() function, which returns a std::unique_ptr<XmlElement>!
@returns a new XmlElement which the caller will need to delete, or null if there was an error.
*/
static XmlElement* parse (const File& file);
/** A handy static method that parses some XML data.
This is a shortcut for creating an XmlDocument object and calling getDocumentElement() on it.
An even better shortcut is the juce::parseXML() function, which returns a std::unique_ptr<XmlElement>!
@returns a new XmlElement which the caller will need to delete, or null if there was an error.
*/
static XmlElement* parse (const String& xmlData);
@@ -172,4 +175,21 @@ private:
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (XmlDocument)
};
//==============================================================================
/** Attempts to parse some XML text, returning a new XmlElement if it was valid.
If the parse fails, this will return a nullptr - if you need more information about
errors or more parsing options, see the XmlDocument instead.
@see XmlDocument
*/
std::unique_ptr<XmlElement> parseXML (const String& textToParse);
/** Attempts to parse some XML text, returning a new XmlElement if it was valid.
If the parse fails, this will return a nullptr - if you need more information about
errors or more parsing options, see the XmlDocument instead.
@see XmlDocument
*/
std::unique_ptr<XmlElement> parseXML (const File& fileToParse);
} // namespace juce

+ 4
- 4
modules/juce_events/native/juce_win32_Messaging.cpp View File

@@ -46,7 +46,7 @@ namespace WindowsMessageHelpers
void dispatchMessageFromLParam (LPARAM lParam)
{
if (MessageManager::MessageBase* message = reinterpret_cast<MessageManager::MessageBase*> (lParam))
if (auto message = reinterpret_cast<MessageManager::MessageBase*> (lParam))
{
JUCE_TRY
{
@@ -154,7 +154,7 @@ bool MessageManager::dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMes
{
// if it's someone else's window being clicked on, and the focus is
// currently on a juce window, pass the kb focus over..
HWND currentFocus = GetFocus();
auto currentFocus = GetFocus();
if (currentFocus == 0 || JuceWindowIdentifier::isJUCEWindow (currentFocus))
SetFocus (m.hwnd);
@@ -175,14 +175,14 @@ bool MessageManager::postMessageToSystemQueue (MessageManager::MessageBase* cons
#if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client && JucePlugin_Build_Unity
if (juce_isRunningInUnity())
return SendNotifyMessage (juce_messageWindowHandle, WindowsMessageHelpers::customMessageID, 0, (LPARAM) message) != 0;
else
#endif
return PostMessage (juce_messageWindowHandle, WindowsMessageHelpers::customMessageID, 0, (LPARAM) message) != 0;
}
void MessageManager::broadcastMessage (const String& value)
{
const String localCopy (value);
auto localCopy = value;
Array<HWND> windows;
EnumWindows (&WindowsMessageHelpers::broadcastEnumWindowProc, (LPARAM) &windows);


+ 4
- 6
modules/juce_graphics/native/juce_linux_Fonts.cpp View File

@@ -27,16 +27,16 @@
namespace juce
{
static XmlElement* findFontsConfFile()
static std::unique_ptr<XmlElement> findFontsConfFile()
{
static const char* pathsToSearch[] = { "/etc/fonts/fonts.conf",
"/usr/share/fonts/fonts.conf" };
for (auto* path : pathsToSearch)
if (auto* xml = XmlDocument::parse (File (path)))
if (auto xml = parseXML (File (path)))
return xml;
return nullptr;
return {};
}
StringArray FTTypefaceList::getDefaultFontDirectories()
@@ -48,9 +48,7 @@ StringArray FTTypefaceList::getDefaultFontDirectories()
if (fontDirs.isEmpty())
{
std::unique_ptr<XmlElement> fontsInfo (findFontsConfFile());
if (fontsInfo != nullptr)
if (auto fontsInfo = findFontsConfFile())
{
forEachXmlChildElementWithTagName (*fontsInfo, e, "dir")
{


+ 1
- 1
modules/juce_gui_basics/lookandfeel/juce_LookAndFeel_V2.cpp View File

@@ -2655,7 +2655,7 @@ void LookAndFeel_V2::layoutFileBrowserComponent (FileBrowserComponent& browserCo
//==============================================================================
static Drawable* createDrawableFromSVG (const char* data)
{
std::unique_ptr<XmlElement> xml (XmlDocument::parse (data));
auto xml = parseXML (data);
jassert (xml != nullptr);
return Drawable::createFromSVG (*xml);
}


+ 2
- 1
modules/juce_gui_basics/misc/juce_JUCESplashScreen.cpp View File

@@ -294,7 +294,8 @@ std::unique_ptr<Drawable> JUCESplashScreen::getSplashScreenLogo()
</svg>
)JUCESPLASHSCREEN";
std::unique_ptr<XmlElement> svgXml (XmlDocument::parse (svgData));
auto svgXml = parseXML (svgData);
jassert (svgXml != nullptr);
return std::unique_ptr<Drawable> (Drawable::createFromSVG (*svgXml));
}


+ 21
- 19
modules/juce_gui_basics/widgets/juce_TableHeaderComponent.cpp View File

@@ -436,40 +436,42 @@ String TableHeaderComponent::toString() const
void TableHeaderComponent::restoreFromString (const String& storedVersion)
{
std::unique_ptr<XmlElement> storedXml (XmlDocument::parse (storedVersion));
int index = 0;
if (storedXml != nullptr && storedXml->hasTagName ("TABLELAYOUT"))
if (auto storedXML = parseXML (storedVersion))
{
forEachXmlChildElement (*storedXml, col)
if (storedXML->hasTagName ("TABLELAYOUT"))
{
auto tabId = col->getIntAttribute ("id");
int index = 0;
if (auto* ci = getInfoForId (tabId))
forEachXmlChildElement (*storedXML, col)
{
columns.move (columns.indexOf (ci), index);
ci->width = col->getIntAttribute ("width");
setColumnVisible (tabId, col->getBoolAttribute ("visible"));
}
auto tabId = col->getIntAttribute ("id");
++index;
}
if (auto* ci = getInfoForId (tabId))
{
columns.move (columns.indexOf (ci), index);
ci->width = col->getIntAttribute ("width");
setColumnVisible (tabId, col->getBoolAttribute ("visible"));
}
columnsResized = true;
sendColumnsChanged();
++index;
}
setSortColumnId (storedXml->getIntAttribute ("sortedCol"),
storedXml->getBoolAttribute ("sortForwards", true));
columnsResized = true;
sendColumnsChanged();
setSortColumnId (storedXML->getIntAttribute ("sortedCol"),
storedXML->getBoolAttribute ("sortForwards", true));
}
}
}
//==============================================================================
void TableHeaderComponent::addListener (Listener* const newListener)
void TableHeaderComponent::addListener (Listener* newListener)
{
listeners.addIfNotAlreadyThere (newListener);
}
void TableHeaderComponent::removeListener (Listener* const listenerToRemove)
void TableHeaderComponent::removeListener (Listener* listenerToRemove)
{
listeners.removeFirstMatchingValue (listenerToRemove);
}


+ 3
- 5
modules/juce_product_unlocking/marketplace/juce_OnlineUnlockStatus.cpp View File

@@ -120,10 +120,10 @@ struct KeyFileUtils
{
key.applyToValue (val);
const MemoryBlock mb (val.toMemoryBlock());
auto mb = val.toMemoryBlock();
if (CharPointer_UTF8::isValidString (static_cast<const char*> (mb.getData()), (int) mb.getSize()))
xml.reset (XmlDocument::parse (mb.toString()));
xml = parseXML (mb.toString());
}
return xml != nullptr ? *xml : XmlElement("key");
@@ -465,9 +465,7 @@ OnlineUnlockStatus::UnlockResult OnlineUnlockStatus::attemptWebserverUnlock (con
DBG ("Reply from server: " << reply);
std::unique_ptr<XmlElement> xml (XmlDocument::parse (reply));
if (xml != nullptr)
if (auto xml = parseXML (reply))
return handleXmlReply (*xml);
return handleFailedConnection();


Loading…
Cancel
Save