diff --git a/REUSE.toml b/REUSE.toml index f5c0a3815..dc2ccfa6f 100644 --- a/REUSE.toml +++ b/REUSE.toml @@ -5,11 +5,6 @@ path = [ "src/lua/src/*.*", "src/lua/src/Makefile" ] SPDX-FileCopyrightText = "Copyright (C) 1994-2020 Lua.org, PUC-Rio." SPDX-License-Identifier = "MIT" -[[annotations]] -path = [ "src/dlfcn*.*" ] -SPDX-FileCopyrightText = "Copyright (c) 2007 Ramiro Polla" -SPDX-License-Identifier = "MIT" - [[annotations]] path = "data/fonts/Roboto-Regular.ttf" SPDX-FileCopyrightText = "Copyright 2011 Google Inc." diff --git a/include/element/arc.hpp b/include/element/arc.hpp index 842f9a7f7..9fe409098 100644 --- a/include/element/arc.hpp +++ b/include/element/arc.hpp @@ -5,6 +5,7 @@ #include +#include #include namespace element { @@ -39,7 +40,7 @@ struct JUCE_API Arc { JUCE_LEAK_DETECTOR (Arc) }; -struct ArcSorter { +struct EL_API ArcSorter { static inline int compareElements (const Arc* const first, const Arc* const second) noexcept { if (first->sourceNode < second->sourceNode) @@ -65,7 +66,7 @@ struct ArcSorter { /** Holds a fast lookup table for checking which arcs are inputs to others. */ template -class ArcTable { +class EL_API ArcTable { public: explicit ArcTable (const juce::OwnedArray& arcs) { diff --git a/include/element/audioengine.hpp b/include/element/audioengine.hpp index 78d009b58..97dac35fc 100644 --- a/include/element/audioengine.hpp +++ b/include/element/audioengine.hpp @@ -38,7 +38,7 @@ class AudioEngine final : public juce::ReferenceCountedObject { by a MidiInputDevice callback (don't use except for debugging) */ - void addMidiMessage (const MidiMessage msg, bool handleOnDeviceQueue = false); + void addMidiMessage (const juce::MidiMessage msg, bool handleOnDeviceQueue = false); void applySettings (Settings&); @@ -58,22 +58,22 @@ class AudioEngine final : public juce::ReferenceCountedObject { void setPlaying (const bool shouldBePlaying); void setRecording (const bool shouldBeRecording); - void seekToAudioFrame (const int64 frame); + void seekToAudioFrame (const int64_t frame); void setMeter (int beatsPerBar, int beatDivisor); void togglePlayPause(); - MidiKeyboardState& getKeyboardState(); + juce::MidiKeyboardState& getKeyboardState(); Transport::MonitorPtr getTransportMonitor() const; - AudioIODeviceCallback& getAudioIODeviceCallback(); - MidiInputCallback& getMidiInputCallback(); + juce::AudioIODeviceCallback& getAudioIODeviceCallback(); + juce::MidiInputCallback& getMidiInputCallback(); /** For use by external systems only! e.g. the AU/VST version of Element and possibly things like rendering in the future */ void prepareExternalPlayback (const double sampleRate, const int blockSize, const int numIns, const int numOuts); - void processExternalBuffers (AudioBuffer& buffer, MidiBuffer& midi); - void processExternalPlayhead (AudioPlayHead* playhead, const int nframes); + void processExternalBuffers (juce::AudioBuffer& buffer, juce::MidiBuffer& midi); + void processExternalPlayhead (juce::AudioPlayHead* playhead, const int nframes); void releaseExternalResources(); void updateExternalLatencySamples(); int getExternalLatencySamples() const; @@ -88,11 +88,11 @@ class AudioEngine final : public juce::ReferenceCountedObject { private: friend class AudioEngine; - Atomic _level { 0 }; + juce::Atomic _level { 0 }; void updateLevel (const float* const*, int numChannels, int numSamples) noexcept; }; - using LevelMeterPtr = ReferenceCountedObjectPtr; + using LevelMeterPtr = juce::ReferenceCountedObjectPtr; LevelMeterPtr getLevelMeter (int channel, bool input); int getNumChannels (bool input) const noexcept; @@ -104,6 +104,6 @@ class AudioEngine final : public juce::ReferenceCountedObject { RunMode runMode; }; -using AudioEnginePtr = ReferenceCountedObjectPtr; +using AudioEnginePtr = juce::ReferenceCountedObjectPtr; } // namespace element diff --git a/include/element/context.hpp b/include/element/context.hpp index 66783ca0a..c343eca40 100644 --- a/include/element/context.hpp +++ b/include/element/context.hpp @@ -40,12 +40,6 @@ class Context { Settings& settings(); - //========================================================================= - void openModule (const std::string& path); - void loadModules(); - void addModulePath (const std::string& path); - void discoverModules(); - private: friend class Application; class Impl; diff --git a/include/element/element.h b/include/element/element.h index e5abdfb5e..5c9e31ddd 100644 --- a/include/element/element.h +++ b/include/element/element.h @@ -63,34 +63,6 @@ typedef enum { #define EL_MT_MIDI_PIPE "el.MidiPipe" #define EL_MT_VECTOR "el.Vector" -//============================================================================= -typedef void* elHandle; - -typedef struct elFeature { - const char* ID; - void* data; -} elFeature; - -/** NULL terminated array of elFeature pointers */ -typedef const elFeature* const* elFeatures; -#define EL_FEATURES_FOREACH(features, f) \ - for (const elFeature* f = *features; f != NULL; f = *(++features)) - -/** Descriptor for an Element module */ -typedef struct elDescriptor { - const char* ID; - elHandle (*create)(); - const void* (*extension) (elHandle handle, const char* name); - void (*load) (elHandle handle, elFeatures features); - void (*unload) (elHandle handle); - void (*destroy) (elHandle handle); -} elDescriptor; - -typedef const elDescriptor* (*elDescriptorFunction)(); - -EL_PLUGIN_EXPORT -const elDescriptor* element_descriptor(); - #ifdef __cplusplus } // extern "C" #endif diff --git a/include/element/engine.hpp b/include/element/engine.hpp index e389edcf8..8b2b8826b 100644 --- a/include/element/engine.hpp +++ b/include/element/engine.hpp @@ -45,17 +45,17 @@ class EngineService : public Service { Node addNode (const Node& node, const Node& target, const ConnectionBuilder&); /** Adds a plugin by description to the current graph */ - Node addPlugin (const PluginDescription& desc, const bool verified = true, const float rx = 0.5f, const float ry = 0.5f, bool dontShowUI = false); + Node addPlugin (const juce::PluginDescription& desc, const bool verified = true, const float rx = 0.5f, const float ry = 0.5f, bool dontShowUI = false); /** Adds a plugin to a specific graph */ - Node addPlugin (const Node& graph, const PluginDescription& desc); + Node addPlugin (const Node& graph, const juce::PluginDescription& desc); /** Adds a plugin to a specific graph and adds connections from a ConnectionBuilder */ - Node addPlugin (const Node& graph, const PluginDescription& desc, const ConnectionBuilder& builder, const bool verified = true); + Node addPlugin (const Node& graph, const juce::PluginDescription& desc, const ConnectionBuilder& builder, const bool verified = true); /** Adds a midi device node to the current root graph */ - Node addMidiDeviceNode (const MidiDeviceInfo& device, const bool isInput); + Node addMidiDeviceNode (const juce::MidiDeviceInfo& device, const bool isInput); /** Removes a node from the current graph */ void removeNode (const uint32); @@ -64,7 +64,7 @@ class EngineService : public Service { void removeNode (const Node& node); /** remove a node by Uuid */ - void removeNode (const Uuid&); + void removeNode (const juce::Uuid&); /** Adds a new root graph */ void addGraph(); @@ -123,9 +123,9 @@ class EngineService : public Service { void sessionReloaded(); /** replace a node with a given plugin */ - void replace (const Node&, const PluginDescription&); + void replace (const Node&, const juce::PluginDescription&); - void changeBusesLayout (const Node& node, const AudioProcessor::BusesLayout& layout); + void changeBusesLayout (const Node& node, const juce::AudioProcessor::BusesLayout& layout); Signal sigNodeRemoved; @@ -136,7 +136,7 @@ class EngineService : public Service { std::unique_ptr graphs; friend class ChangeBroadcaster; - Node addPlugin (GraphManager& controller, const PluginDescription& desc); + Node addPlugin (GraphManager& controller, const juce::PluginDescription& desc); }; } // namespace element diff --git a/include/element/juce.hpp b/include/element/juce.hpp index 407709db8..c38a4681d 100644 --- a/include/element/juce.hpp +++ b/include/element/juce.hpp @@ -21,6 +21,6 @@ #include #include -using namespace juce; // FIXME: +using namespace juce; // FIXME: namespace juce namespace element { } diff --git a/include/element/node.hpp b/include/element/node.hpp index 04a96c3a1..e1b535815 100644 --- a/include/element/node.hpp +++ b/include/element/node.hpp @@ -29,7 +29,7 @@ class Script; class EL_API Port : public Model { public: Port() : Model (types::Port, EL_PORT_VERSION) {} - Port (const ValueTree& p) + Port (const juce::ValueTree& p) : Model (p) { jassert (p.hasType (types::Port)); } Port (const juce::String& name, const juce::Identifier& type, const juce::Identifier& flow, uint32 index = 0) : Model (types::Port, EL_PORT_VERSION) @@ -45,7 +45,7 @@ class EL_API Port : public Model { /** Returns the ValueTree of the Node containing this port will not always be valid */ - inline ValueTree getNodeValueTree() const { return objectData.getParent().getParent(); } + inline juce::ValueTree getNodeValueTree() const { return objectData.getParent().getParent(); } /** Returns the Node containing this port */ Node getNode() const; @@ -66,7 +66,7 @@ class EL_API Port : public Model { } /** Returns the port name. */ - const String getName() const { return getProperty (tags::name, "Port"); } + const juce::String getName() const { return getProperty (tags::name, "Port"); } /** Returns the type of this Port. */ const PortType getType() const { return PortType (getProperty (tags::type, "unknown").toString()); } @@ -77,7 +77,7 @@ class EL_API Port : public Model { uint32 index() const noexcept; /** Returns the symbol for this Port. */ - const String symbol() const noexcept; + const juce::String symbol() const noexcept; /** Returns the coresponding channel for this port's index */ int channel() const noexcept; @@ -96,10 +96,10 @@ class EL_API Node : public Model { Node(); /** Create a node with existing data */ - Node (const ValueTree& data, const bool setMissing = true); + Node (const juce::ValueTree& data, const bool setMissing = true); /** Creates a node with specific type */ - Node (const Identifier& nodeType); + Node (const juce::Identifier& nodeType); /** Destructor */ ~Node() noexcept; @@ -109,10 +109,10 @@ class EL_API Node : public Model { bool isValid() const noexcept; /** Returns the user-modifiable name of this node */ - const String getName() const noexcept; + const juce::String getName() const noexcept; /** Change the user-defined name */ - void setName (const String& name); + void setName (const juce::String& name); /** Returns the node name defined by the user. If not set it returns the node name set when loaded. @@ -127,13 +127,13 @@ class EL_API Node : public Model { //========================================================================= /** Returns the nodeId as defined in the engine */ - const uint32 getNodeId() const { return (uint32) (int64) getProperty (tags::id); } + const uint32_t getNodeId() const { return (uint32_t) (juce::int64) getProperty (tags::id); } /** Returns this Node's UUID as a string */ - String getUuidString() const { return objectData.getProperty (tags::uuid).toString(); } + juce::String getUuidString() const { return objectData.getProperty (tags::uuid).toString(); } /** Returns this Node's UUID */ - Uuid getUuid() const { return Uuid (getUuidString()); } + juce::Uuid getUuid() const { return juce::Uuid (getUuidString()); } //========================================================================= /** Returns true if this node is probably a graph */ @@ -189,14 +189,14 @@ class EL_API Node : public Model { bool isBypassed() const { return objectData.getProperty (tags::bypass, false); } /** Returns the Value object for the bypass property */ - Value getBypassedValue() { return getPropertyAsValue (tags::bypass); } + juce::Value getBypassedValue() { return getPropertyAsValue (tags::bypass); } //========================================================================= /** Returns true if this Node is muted */ bool isMuted() const { return (bool) getProperty (tags::mute, false); } /** Returns the Value object for the mute property */ - Value getMutedValue() { return getPropertyAsValue (tags::mute); } + juce::Value getMutedValue() { return getPropertyAsValue (tags::mute); } /** Returns true if inputs are muted */ bool isMutingInputs() const { return (bool) getProperty ("muteInput", false); } @@ -212,10 +212,10 @@ class EL_API Node : public Model { int getNumConnections() const; /** Returns a Value tree containing connection information */ - ValueTree getConnectionValueTree (const int index) const; + juce::ValueTree getConnectionValueTree (const int index) const; /** Get an array of Arcs contained on this Node (graph) */ - void getArcs (OwnedArray&) const; + void getArcs (juce::OwnedArray&) const; //========================================================================= /** Set relative position */ @@ -287,13 +287,13 @@ class EL_API Node : public Model { bool isMidiDevice() { return isMidiInputDevice() || isMidiOutputDevice(); } /** Returns the format of this node */ - inline const var& getFormat() const { return objectData.getProperty (tags::format); } + inline const juce::var& getFormat() const { return objectData.getProperty (tags::format); } /** Returns this nodes identifier */ - inline const var& getIdentifier() const { return objectData.getProperty (tags::identifier); } + inline const juce::var& getIdentifier() const { return objectData.getProperty (tags::identifier); } /** Returns a file property if exists, otherwise the identifier property */ - inline const var& getFileOrIdentifier() const + inline const juce::var& getFileOrIdentifier() const { return objectData.hasProperty (tags::file) ? objectData.getProperty (tags::file) @@ -301,7 +301,7 @@ class EL_API Node : public Model { } /** returns the first node by format and identifier */ - inline Node getNodeByFormat (const var& format, const var& identifier) const + inline Node getNodeByFormat (const juce::var& format, const juce::var& identifier) const { auto nodes = getNodesValueTree(); @@ -324,7 +324,7 @@ class EL_API Node : public Model { return getNodeByFormat ("Internal", identifier); } - bool hasChildNode (const var& format, const var& identifier) const + bool hasChildNode (const juce::var& format, const juce::var& identifier) const { auto nodes = getNodesValueTree(); for (int i = 0; i < nodes.getNumChildren(); ++i) { @@ -348,14 +348,14 @@ class EL_API Node : public Model { bool hasMidiOutputNode() const { return hasChildNode ("Internal", "midi.output"); } /** Fill a plugin Description for loading with the plugin manager */ - void getPluginDescription (PluginDescription&) const; + void getPluginDescription (juce::PluginDescription&) const; //========================================================================= /** Write the contents of this node to file */ - bool writeToFile (const File& file) const; + bool writeToFile (const juce::File& file) const; /** Save this node as a preset to file */ - bool savePresetTo (const DataPath& path, const String& name) const; + bool savePresetTo (const DataPath& path, const juce::String& name) const; /** Get an array of possible sources that can connect to this Node */ void getPossibleSources (NodeArray& nodes) const; @@ -367,7 +367,7 @@ class EL_API Node : public Model { Node getNodeById (const uint32 nodeId) const; /** Returns a child node by UUID */ - Node getNodeByUuid (const Uuid& uuid, const bool recursive = true) const; + Node getNodeByUuid (const juce::Uuid& uuid, const bool recursive = true) const; //========================================================================= /** Rebuild this node's ports based on it's Processor object */ @@ -425,20 +425,20 @@ class EL_API Node : public Model { void setMidiProgramName (int program, const String& name); //========================================================================= - ValueTree getArcsValueTree() const { return objectData.getChildWithName (tags::arcs); } - ValueTree getNodesValueTree() const { return objectData.getChildWithName (tags::nodes); } - ValueTree getParentArcsNode() const; - ValueTree getPortsValueTree() const { return objectData.getChildWithName (tags::ports); } - ValueTree getUIValueTree() const { return objectData.getChildWithName (tags::ui); } - ValueTree getBlockValueTree() const noexcept { return getUIValueTree().getChildWithName (types::Block); } - ValueTree getScriptsValueTree() const noexcept { return objectData.getChildWithName (tags::scripts); } + juce::ValueTree getArcsValueTree() const { return objectData.getChildWithName (tags::arcs); } + juce::ValueTree getNodesValueTree() const { return objectData.getChildWithName (tags::nodes); } + juce::ValueTree getParentArcsNode() const; + juce::ValueTree getPortsValueTree() const { return objectData.getChildWithName (tags::ports); } + juce::ValueTree getUIValueTree() const { return objectData.getChildWithName (tags::ui); } + juce::ValueTree getBlockValueTree() const noexcept { return getUIValueTree().getChildWithName (types::Block); } + juce::ValueTree getScriptsValueTree() const noexcept { return objectData.getChildWithName (tags::scripts); } //========================================================================= const bool operator== (const Node& o) const { return this->objectData == o.objectData; } const bool operator!= (const Node& o) const { return this->objectData != o.objectData; } /** Iterate over all ValueTree's recursively */ - void forEach (std::function) const; + void forEach (std::function) const; /** Change the block color */ void setColor (const juce::Colour& color) @@ -461,7 +461,7 @@ class EL_API Node : public Model { /** Add a script to this node. If failure, the returned will be invalid; */ - ValueTree addScript (const Script& script); + juce::ValueTree addScript (const Script& script); //========================================================================== /** Returns true if the connection exists in the provided ValueTree @@ -473,44 +473,44 @@ class EL_API Node : public Model { @param destPort The target port index @param checkMissing If true, will return false if found but has the missing property */ - static bool connectionExists (const ValueTree& arcs, const uint32 sourceNode, const uint32 sourcePort, const uint32 destNode, const uint32 destPort, const bool checkMissing = false); + static bool connectionExists (const juce::ValueTree& arcs, const uint32 sourceNode, const uint32 sourcePort, const uint32 destNode, const uint32 destPort, const bool checkMissing = false); /** Creates a default graph structure with optional name */ - static Node createDefaultGraph (const String& name = String()); + static Node createDefaultGraph (const juce::String& name = String()); /** Creates an empty graph model */ - static Node createGraph (const String& name = String()); + static Node createGraph (const juce::String& name = String()); /** Returns true if the value tree is probably a graph node */ - static bool isProbablyGraphNode (const ValueTree& data); + static bool isProbablyGraphNode (const juce::ValueTree& data); /** Removes unused id properties and resets the uuid */ - static ValueTree resetIds (const ValueTree& data); + static juce::ValueTree resetIds (const juce::ValueTree& data); /** Load node data from file */ - static ValueTree parse (const File& file); + static juce::ValueTree parse (const juce::File& file); /** Removes properties that can't be saved to a file. e.g. object properties */ - static void sanitizeProperties (ValueTree node, const bool recursive = false); + static void sanitizeProperties (juce::ValueTree node, const bool recursive = false); /** This is just an alias right now */ - static void sanitizeRuntimeProperties (ValueTree node, const bool recursive = false); + static void sanitizeRuntimeProperties (juce::ValueTree node, const bool recursive = false); /** Create a value tree version of an arc */ - static ValueTree makeArc (const Arc& arc); + static juce::ValueTree makeArc (const Arc& arc); /** Create an Arc from a ValueTree */ static Arc arcFromValueTree (const juce::ValueTree& data); /** Migrate an old data format to the current one. */ - static ValueTree migrate (const juce::ValueTree& data, juce::String& error) noexcept; + static juce::ValueTree migrate (const juce::ValueTree& data, juce::String& error) noexcept; private: void setMissingProperties(); void forEach (const juce::ValueTree tree, std::function) const; }; -class NodeObjectSync final : private ValueTree::Listener { +class NodeObjectSync final : private juce::ValueTree::Listener { public: NodeObjectSync(); NodeObjectSync (const Node& node); @@ -523,26 +523,26 @@ class NodeObjectSync final : private ValueTree::Listener { private: Node node; - ValueTree data; + juce::ValueTree data; bool frozen = false; - void valueTreePropertyChanged (ValueTree& tree, const Identifier& property) override; - void valueTreeChildAdded (ValueTree& parent, ValueTree& child) override; - void valueTreeChildRemoved (ValueTree& parent, ValueTree& child, int index) override; - void valueTreeChildOrderChanged (ValueTree& parent, int oldIndex, int newIndex) override; - void valueTreeParentChanged (ValueTree& tree) override; - void valueTreeRedirected (ValueTree& tree) override; + void valueTreePropertyChanged (juce::ValueTree& tree, const juce::Identifier& property) override; + void valueTreeChildAdded (juce::ValueTree& parent, juce::ValueTree& child) override; + void valueTreeChildRemoved (juce::ValueTree& parent, juce::ValueTree& child, int index) override; + void valueTreeChildOrderChanged (juce::ValueTree& parent, int oldIndex, int newIndex) override; + void valueTreeParentChanged (juce::ValueTree& tree) override; + void valueTreeRedirected (juce::ValueTree& tree) override; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NodeObjectSync) }; -class PortArray : public Array { +class PortArray : public juce::Array { public: PortArray() {} ~PortArray() {} }; -class NodeArray : public Array { +class NodeArray : public juce::Array { public: NodeArray() {} ~NodeArray() {} @@ -593,9 +593,9 @@ struct ConnectionBuilder { dstOffset = 0; for (int i = 0; i < 2; ++i) { - ValueTree connection (types::Arc); - connection.setProperty (tags::sourceNode, (int64) src.getNodeId(), 0) - .setProperty (tags::destNode, (int64) dst.getNodeId(), 0) + juce::ValueTree connection (types::Arc); + connection.setProperty (tags::sourceNode, (juce::int64) src.getNodeId(), 0) + .setProperty (tags::destNode, (juce::int64) dst.getNodeId(), 0) .setProperty (tags::sourceChannel, i + srcOffset, 0) .setProperty (tags::destChannel, i + dstOffset, 0); arcs.addChild (connection, -1, 0); @@ -607,7 +607,7 @@ struct ConnectionBuilder { String getError() const { return lastError; } private: - ValueTree arcs; + juce::ValueTree arcs; Node target; mutable String lastError; @@ -628,7 +628,7 @@ struct ConnectionBuilder { const int targetChannel; }; - OwnedArray portChannelMap; + juce::OwnedArray portChannelMap; }; } // namespace element diff --git a/include/element/nodefactory.hpp b/include/element/nodefactory.hpp index 461a0dec8..8be83bef6 100644 --- a/include/element/nodefactory.hpp +++ b/include/element/nodefactory.hpp @@ -21,15 +21,15 @@ class NodeProvider { /** Create the instance by ID string. */ virtual Processor* create (const String&) = 0; /** return a list of types contained in this provider. */ - virtual StringArray findTypes (const FileSearchPath& path, + virtual StringArray findTypes (const juce::FileSearchPath& path, bool recursive, bool allowAsync) = 0; /** Return a list of types that should be hidden in the UI by default. */ - virtual StringArray getHiddenTypes() { return {}; } + virtual juce::StringArray getHiddenTypes() { return {}; } - virtual FileSearchPath defaultSearchPath() { return {}; } + virtual juce::FileSearchPath defaultSearchPath() { return {}; } - virtual void scan (const String& fileOrID, OwnedArray& out) {} + virtual void scan (const juce::String& fileOrID, juce::OwnedArray& out) {} }; //========================================================================== @@ -41,18 +41,18 @@ class NodeFactory final { ~NodeFactory(); /** Fill a list of Element type plugin descriptions. public */ - void getPluginDescriptions (OwnedArray& out, - const String& identifier, + void getPluginDescriptions (juce::OwnedArray& out, + const juce::String& identifier, bool includeHidden = false); /** Fill a list of plugin descriptions. public */ - void getPluginDescriptions (OwnedArray& out, - const String& format, - const String& identifier, + void getPluginDescriptions (juce::OwnedArray& out, + const juce::String& format, + const juce::String& identifier, bool includeHidden = false); /** Returns a list of known Node IDs public and private. */ - const StringArray& knownIDs() const noexcept; + const juce::StringArray& knownIDs() const noexcept; //========================================================================== /** Add a new provider to the factory. */ @@ -60,26 +60,26 @@ class NodeFactory final { //========================================================================== /** Mark a type as hidden in the UI. */ - void hideType (const String& tp); + void hideType (const juce::String& tp); /** Hide all types in the UI. */ void hideAllTypes(); /** Returns true if a type is hidden in the UI. */ - bool isTypeHidden (const String& tp) const noexcept; + bool isTypeHidden (const juce::String& tp) const noexcept; /** Remove a type from the hidden list. */ - void removeHiddenType (const String& tp); + void removeHiddenType (const juce::String& tp); //========================================================================== /** Instantiate a node processor. */ - Processor* instantiate (const PluginDescription&); + Processor* instantiate (const juce::PluginDescription&); /** Instantiate a node processor. */ - Processor* instantiate (const String& identifier); + Processor* instantiate (const juce::String& identifier); /** Wrap an audio plugin instance as a node processor. */ - static Processor* wrap (AudioProcessor*); + static Processor* wrap (juce::AudioProcessor*); //========================================================================== /** Return the list of providers registered with this factory. */ - const OwnedArray& providers() const noexcept; + const juce::OwnedArray& providers() const noexcept; private: class Impl; diff --git a/include/element/processor.hpp b/include/element/processor.hpp index c8be71fe9..e78902a7d 100644 --- a/include/element/processor.hpp +++ b/include/element/processor.hpp @@ -3,6 +3,7 @@ #pragma once +#include // FIXME: namespace juce #include #include #include @@ -17,8 +18,6 @@ namespace element { -using namespace juce; - /* So render tasks can be friends of graph node */ namespace GraphRender { class ProcessBufferOp; @@ -46,9 +45,9 @@ struct RenderContext { midi (sharedMidi, midiIndexes) {} - RenderContext (AudioSampleBuffer& audioRef, - AudioSampleBuffer& cvRef, - MidiBuffer& midiRef, + RenderContext (juce::AudioSampleBuffer& audioRef, + juce::AudioSampleBuffer& cvRef, + juce::MidiBuffer& midiRef, int numSamples) : audio (audioRef.getArrayOfWritePointers(), audioRef.getNumChannels(), numSamples), cv (cvRef.getArrayOfWritePointers(), cvRef.getNumChannels(), numSamples), @@ -57,7 +56,7 @@ struct RenderContext { // clang-format on }; -class Processor : public ReferenceCountedObject { +class Processor : public juce::ReferenceCountedObject { public: /** Special parameter indexes when mapping universal node settings */ enum SpecialParameter { @@ -99,7 +98,7 @@ class Processor : public ReferenceCountedObject { //========================================================================= /** Returns an audio processor if available */ - virtual AudioProcessor* getAudioProcessor() const noexcept { return nullptr; } + virtual juce::AudioProcessor* getAudioProcessor() const noexcept { return nullptr; } /** The actual processor object dynamic_cast'd to T */ template @@ -109,11 +108,11 @@ class Processor : public ReferenceCountedObject { } /** Returns the processor as an Audio Plugin Instance */ - AudioPluginInstance* getAudioPluginInstance() const noexcept { return processor(); } + juce::AudioPluginInstance* getAudioPluginInstance() const noexcept { return processor(); } /** Set the audio play head */ - virtual void setPlayHead (AudioPlayHead* playhead) { _playhead = playhead; } - AudioPlayHead* getPlayHead() const noexcept { return _playhead; } + virtual void setPlayHead (juce::AudioPlayHead* playhead) { _playhead = playhead; } + juce::AudioPlayHead* getPlayHead() const noexcept { return _playhead; } //========================================================================== virtual void prepareToRender (double sampleRate, int maxBufferSize) = 0; @@ -219,7 +218,7 @@ class Processor : public ReferenceCountedObject { bool containsParameter (const int index) const; /** Fill the details... */ - virtual void getPluginDescription (PluginDescription& desc) const; + virtual void getPluginDescription (juce::PluginDescription& desc) const; /** Returns true if the processor is suspended */ bool isSuspended() const; @@ -249,7 +248,7 @@ class Processor : public ReferenceCountedObject { lastInputGain = inputGain; } - ValueTree createPortsData() const; + juce::ValueTree createPortsData() const; bool isAudioIONode() const; bool isAudioInputNode() const; @@ -282,15 +281,15 @@ class Processor : public ReferenceCountedObject { inline void setKeyRange (const int low, const int high) { jassert (low <= high); - jassert (isPositiveAndBelow (low, 128)); - jassert (isPositiveAndBelow (high, 128)); + jassert (juce::isPositiveAndBelow (low, 128)); + jassert (juce::isPositiveAndBelow (high, 128)); keyRangeLow.set (low); keyRangeHigh.set (high); } - inline void setKeyRange (const Range& range) { setKeyRange (range.getStart(), range.getEnd()); } + inline void setKeyRange (const juce::Range& range) { setKeyRange (range.getStart(), range.getEnd()); } - inline Range getKeyRange() const { return Range { keyRangeLow.get(), keyRangeHigh.get() }; } + inline juce::Range getKeyRange() const { return juce::Range { keyRangeLow.get(), keyRangeHigh.get() }; } //========================================================================= inline void setTransposeOffset (const int value) @@ -301,11 +300,11 @@ class Processor : public ReferenceCountedObject { inline int getTransposeOffset() const { return transposeOffset.get(); } - const CriticalSection& getPropertyLock() const { return propertyLock; } + const juce::CriticalSection& getPropertyLock() const { return propertyLock; } //========================================================================= /** Returns the file used for the current global MIDI Program */ - File getMidiProgramFile (int program = -1) const; + juce::File getMidiProgramFile (int program = -1) const; /** Returns true if this node should use global MIDI programs */ inline bool useGlobalMidiPrograms() const { return globalMidiPrograms.get() == 1; } @@ -330,7 +329,7 @@ class Processor : public ReferenceCountedObject { void setMidiProgramName (const int program, const String& name); /** Gets the MIDI program's name */ - String getMidiProgramName (const int program) const; + juce::String getMidiProgramName (const int program) const; /** Reloads the active MIDI program */ void reloadMidiProgram(); @@ -342,19 +341,19 @@ class Processor : public ReferenceCountedObject { void removeMidiProgram (int program, bool global); /** Get all MIDI program states stored directly on the node */ - void getMidiProgramsState (String& state) const; + void getMidiProgramsState (juce::String& state) const; /** Load all MIDI program states to be stored on the node. @param state The state to set. If this is empty, the midi programs on the node will be cleared. */ - void setMidiProgramsState (const String& state); + void setMidiProgramsState (const juce::String& state); //========================================================================= - inline void setMidiChannels (const BigInteger& ch) + inline void setMidiChannels (const juce::BigInteger& ch) { - ScopedLock sl (propertyLock); + juce::ScopedLock sl (propertyLock); midiChannels.setChannels (ch); } @@ -375,7 +374,7 @@ class Processor : public ReferenceCountedObject { return 0; } - inline virtual const String getProgramName (int index) const + inline virtual const juce::String getProgramName (int index) const { if (auto* const proc = getAudioProcessor()) return proc->getProgramName (index); @@ -395,7 +394,7 @@ class Processor : public ReferenceCountedObject { bool isMutingInputs() const { return muteInput.get() == 1; } //========================================================================== - virtual void getState (MemoryBlock&) = 0; + virtual void getState (juce::MemoryBlock&) = 0; virtual void setState (const void*, int sizeInBytes) = 0; //========================================================================== @@ -479,41 +478,41 @@ class Processor : public ReferenceCountedObject { GraphNode* parent = nullptr; bool isPrepared = false; - Atomic enabled { 1 }; - Atomic bypassed { 0 }; - Atomic mute { 0 }; - Atomic muteInput { 0 }; + juce::Atomic enabled { 1 }; + juce::Atomic bypassed { 0 }; + juce::Atomic mute { 0 }; + juce::Atomic muteInput { 0 }; double sampleRate = 0.0; int blockSize = 0; int latencySamples = 0; - String name; + juce::String name; ParameterArray parameters, parametersOut; PatchParameterArray _patches; - Atomic gain, lastGain, inputGain, lastInputGain; - OwnedArray> inRMS, outRMS; + juce::Atomic gain, lastGain, inputGain, lastInputGain; + juce::OwnedArray> inRMS, outRMS; - Atomic keyRangeLow { 0 }; - Atomic keyRangeHigh { 127 }; - Atomic transposeOffset { 0 }; + juce::Atomic keyRangeLow { 0 }; + juce::Atomic keyRangeHigh { 127 }; + juce::Atomic transposeOffset { 0 }; MidiChannels midiChannels; - Atomic midiProgram { 0 }; - Atomic lastMidiProgram { -1 }; - Atomic midiProgramsEnabled { 0 }; - Atomic globalMidiPrograms { 0 }; + juce::Atomic midiProgram { 0 }; + juce::Atomic lastMidiProgram { -1 }; + juce::Atomic midiProgramsEnabled { 0 }; + juce::Atomic globalMidiPrograms { 0 }; - CriticalSection propertyLock; - struct EnablementUpdater : public AsyncUpdater { + juce::CriticalSection propertyLock; + struct EnablementUpdater : public juce::AsyncUpdater { EnablementUpdater (Processor& g) : graph (g) {} ~EnablementUpdater() {} void handleAsyncUpdate() override; Processor& graph; } enablement; - struct MidiProgramLoader : public AsyncUpdater { + struct MidiProgramLoader : public juce::AsyncUpdater { MidiProgramLoader (Processor& n) : node (n) {} ~MidiProgramLoader() { cancelPendingUpdate(); } void handleAsyncUpdate() override; @@ -521,7 +520,7 @@ class Processor : public ReferenceCountedObject { } midiProgramLoader; friend struct PortResetter; - struct PortResetter : public AsyncUpdater { + struct PortResetter : public juce::AsyncUpdater { PortResetter (Processor& n) : node (n) {} ~PortResetter() { cancelPendingUpdate(); } void handleAsyncUpdate() override; @@ -530,10 +529,10 @@ class Processor : public ReferenceCountedObject { struct MidiProgram { int program; - String name; - MemoryBlock state; + juce::String name; + juce::MemoryBlock state; }; - mutable OwnedArray midiPrograms; + mutable juce::OwnedArray midiPrograms; MidiProgram* getMidiProgram (int) const; void setParentGraph (GraphNode*); @@ -544,7 +543,7 @@ class Processor : public ReferenceCountedObject { std::unique_ptr> oversampler; int osPow = 0; float osLatency = 0.0f; - dsp::Oversampling* getOversamplingProcessor(); + juce::dsp::Oversampling* getOversamplingProcessor(); ParameterPtr getOrCreateParameter (const PortDescription&); @@ -557,6 +556,6 @@ class Processor : public ReferenceCountedObject { }; /** A convenient typedef for referring to a pointer to a node object. */ -using ProcessorPtr = ReferenceCountedObjectPtr; +using ProcessorPtr = juce::ReferenceCountedObjectPtr; } // namespace element diff --git a/include/element/session.hpp b/include/element/session.hpp index e16a2c58f..a9ca73d88 100644 --- a/include/element/session.hpp +++ b/include/element/session.hpp @@ -50,26 +50,26 @@ class Session : public Model, bool addGraph (const Node& node, const bool setActive); - ValueTree getValueTree() const { return objectData; } - bool loadData (const ValueTree& data); + juce::ValueTree getValueTree() const { return objectData; } + bool loadData (const juce::ValueTree& data); void clear(); - inline void setName (const String& name) { setProperty (tags::name, name); } - inline String getName() const { return objectData.getProperty (tags::name, "Invalid Session"); } - inline Value getNameValue() { return getPropertyAsValue (tags::name); } + inline void setName (const juce::String& name) { setProperty (tags::name, name); } + inline juce::String getName() const { return objectData.getProperty (tags::name, "Invalid Session"); } + inline juce::Value getNameValue() { return getPropertyAsValue (tags::name); } inline bool useExternalClock() const { return (bool) getProperty ("externalSync", false); } inline bool notificationsFrozen() const { return freezeChangeNotification; } - std::unique_ptr createXml() const; + std::unique_ptr createXml() const; void saveGraphState(); void restoreGraphState(); inline int getNumControllers() const { return getControllersValueTree().getNumChildren(); } - inline ValueTree getControllerValueTree (const int i) const + inline juce::ValueTree getControllerValueTree (const int i) const { return getControllersValueTree().getChild (i); } @@ -89,54 +89,54 @@ class Session : public Model, inline ControllerMap getControllerMap (const int index) const { return ControllerMap (getControllerMapsValueTree().getChild (index)); } inline int indexOf (const ControllerMap& controllerMap) const { return getControllerMapsValueTree().indexOf (controllerMap.data()); } - Node findNodeById (const Uuid&); - Controller findControllerById (const Uuid&); + Node findNodeById (const juce::Uuid&); + Controller findControllerById (const juce::Uuid&); void cleanOrphanControllerMaps(); - typedef std::function ValueTreeFunction; + typedef std::function ValueTreeFunction; void forEach (ValueTreeFunction handler) const; void setActiveGraph (int index); bool containsGraph (const Node& graph) const; /** Writes an encoded file */ - bool writeToFile (const File&) const; - static ValueTree readFromFile (const File&); + bool writeToFile (const juce::File&) const; + static juce::ValueTree readFromFile (const juce::File&); - Value getActiveGraphIndexObject (bool syncUpdate = false) const + juce::Value getActiveGraphIndexObject (bool syncUpdate = false) const { return getGraphsValueTree().getPropertyAsValue (tags::active, nullptr, syncUpdate); } - static ValueTree migrate (const ValueTree&, String& error); + static juce::ValueTree migrate (const juce::ValueTree&, juce::String& error); protected: - void forEach (const ValueTree tree, ValueTreeFunction handler) const; + void forEach (const juce::ValueTree tree, ValueTreeFunction handler) const; Session(); friend class Context; /** Set a property. */ - inline void setProperty (const Identifier& prop, const var& val) { objectData.setProperty (prop, val, nullptr); } + inline void setProperty (const juce::Identifier& prop, const juce::var& val) { objectData.setProperty (prop, val, nullptr); } - friend class ValueTree; - virtual void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& property); - virtual void valueTreeChildAdded (ValueTree& parentTree, ValueTree& childWhichHasBeenAdded); - virtual void valueTreeChildRemoved (ValueTree& parentTree, ValueTree& childWhichHasBeenRemoved, int); - virtual void valueTreeChildOrderChanged (ValueTree& parentTreeWhoseChildrenHaveMoved, int, int); - virtual void valueTreeParentChanged (ValueTree& treeWhoseParentHasChanged); - virtual void valueTreeRedirected (ValueTree& treeWhichHasBeenChanged); + friend class juce::ValueTree; + virtual void valueTreePropertyChanged (juce::ValueTree& treeWhosePropertyHasChanged, const juce::Identifier& property); + virtual void valueTreeChildAdded (juce::ValueTree& parentTree, juce::ValueTree& childWhichHasBeenAdded); + virtual void valueTreeChildRemoved (juce::ValueTree& parentTree, juce::ValueTree& childWhichHasBeenRemoved, int); + virtual void valueTreeChildOrderChanged (juce::ValueTree& parentTreeWhoseChildrenHaveMoved, int, int); + virtual void valueTreeParentChanged (juce::ValueTree& treeWhoseParentHasChanged); + virtual void valueTreeRedirected (juce::ValueTree& treeWhichHasBeenChanged); private: class Impl; std::unique_ptr impl; void setMissingProperties (bool resetExisting = false); - inline ValueTree getGraphsValueTree() const { return objectData.getChildWithName (tags::graphs); } - inline ValueTree getGraphValueTree (const int index) const { return getGraphsValueTree().getChild (index); } - inline ValueTree getControllersValueTree() const { return objectData.getChildWithName (tags::controllers); } - inline ValueTree getControllerMapsValueTree() const { return objectData.getChildWithName (tags::maps); } + inline juce::ValueTree getGraphsValueTree() const { return objectData.getChildWithName (tags::graphs); } + inline juce::ValueTree getGraphValueTree (const int index) const { return getGraphsValueTree().getChild (index); } + inline juce::ValueTree getControllersValueTree() const { return objectData.getChildWithName (tags::controllers); } + inline juce::ValueTree getControllerMapsValueTree() const { return objectData.getChildWithName (tags::maps); } friend class SessionService; friend class SessionImportWizard; @@ -153,7 +153,7 @@ class Session : public Model, Signal controlRemoved; }; -typedef ReferenceCountedObjectPtr SessionPtr; +typedef juce::ReferenceCountedObjectPtr SessionPtr; typedef SessionPtr SessionRef; struct ControllerMapObjects { @@ -162,9 +162,9 @@ struct ControllerMapObjects { : session (s), controllerMap (m) { if (session != nullptr) { - device = session->findControllerById (Uuid (controllerMap.getProperty (tags::controller))); - control = device.findControlById (Uuid (controllerMap.getProperty (tags::control))); - node = session->findNodeById (Uuid (controllerMap.getProperty (tags::node))); + device = session->findControllerById (juce::Uuid (controllerMap.getProperty (tags::controller))); + control = device.findControlById (juce::Uuid (controllerMap.getProperty (tags::control))); + node = session->findNodeById (juce::Uuid (controllerMap.getProperty (tags::node))); } } diff --git a/include/element/ui.hpp b/include/element/ui.hpp index cbbaa6ecc..c3605b22a 100644 --- a/include/element/ui.hpp +++ b/include/element/ui.hpp @@ -50,17 +50,17 @@ class GuiService : public Service, void launchUpdater(); Services& services() const { return controller; } - KeyListener* getKeyListener() const; + juce::KeyListener* getKeyListener() const; void closeAllWindows(); MainWindow* getMainWindow() const noexcept; void refreshMainMenu(); - void showPreferencesDialog (const String& section = {}); + void showPreferencesDialog (const juce::String& section = {}); - void runDialog (const String& uri); - void runDialog (Component* c, const String& title = String()); + void runDialog (const juce::String& uri); + void runDialog (juce::Component* c, const String& title = String()); /** Get a reference to Sesison data */ SessionRef session(); @@ -86,9 +86,9 @@ class GuiService : public Service, bool haveActiveWindows() const; /* Command manager... */ - ApplicationCommandTarget* getNextCommandTarget() override; - void getAllCommands (Array& commands) override; - void getCommandInfo (CommandID commandID, ApplicationCommandInfo& result) override; + juce::ApplicationCommandTarget* getNextCommandTarget() override; + void getAllCommands (juce::Array& commands) override; + void getCommandInfo (juce::CommandID commandID, juce::ApplicationCommandInfo& result) override; bool perform (const InvocationInfo& info) override; /** Returns the content component for this instance */ @@ -152,12 +152,12 @@ class GuiService : public Service, Services& controller; Context& world; SessionRef sessionRef; - OwnedArray pluginWindows; + juce::OwnedArray pluginWindows; std::unique_ptr windowManager; std::unique_ptr mainWindow; std::unique_ptr _content; - std::unique_ptr about; + std::unique_ptr about; std::unique_ptr factory; std::unique_ptr designer; @@ -167,19 +167,19 @@ class GuiService : public Service, std::unique_ptr keys; AboutInfo appInfo; - struct ForegroundCheck : public Timer { + struct ForegroundCheck : public juce::Timer { ForegroundCheck (GuiService& _ui) : ui (_ui) {} void timerCallback() override; GuiService& ui; } foregroundCheck; - friend class ChangeBroadcaster; - void changeListenerCallback (ChangeBroadcaster*) override; + friend class juce::ChangeBroadcaster; + void changeListenerCallback (juce::ChangeBroadcaster*) override; void showSplash(); void toggleAboutScreen(); - void saveProperties (PropertiesFile* props); + void saveProperties (juce::PropertiesFile* props); void setMainWindowTitler (std::function); }; diff --git a/src/application.cpp b/src/application.cpp index c8b8e4a88..bed07cb46 100644 --- a/src/application.cpp +++ b/src/application.cpp @@ -1,8 +1,6 @@ // SPDX-FileCopyrightText: Copyright (C) Kushview, LLC. // SPDX-License-Identifier: GPL-3.0-or-later -#include "ElementApp.h" - #include #include #include diff --git a/src/common.hpp b/src/common.hpp index 1493fad51..ccbb3e602 100644 --- a/src/common.hpp +++ b/src/common.hpp @@ -5,23 +5,19 @@ // !!!! DO NOT INCLUDE THIS IN OTHER HEADERS !!!! // -#include "ElementApp.h" - #include -#include "services/deviceservice.hpp" #include #include -#include "services/mappingservice.hpp" -#include "services/sessionservice.hpp" -#include "services/presetservice.hpp" - -#include "nodes/nodetypes.hpp" - #include #include - #include -#include "messages.hpp" #include #include + +#include "services/deviceservice.hpp" +#include "services/mappingservice.hpp" +#include "services/sessionservice.hpp" +#include "services/presetservice.hpp" +#include "nodes/nodetypes.hpp" #include "utils.hpp" +#include "messages.hpp" diff --git a/src/context.cpp b/src/context.cpp index 204a1e630..ffdd2a863 100644 --- a/src/context.cpp +++ b/src/context.cpp @@ -17,7 +17,6 @@ #include "appinfo.hpp" #include "log.hpp" -#include "module.hpp" #include "scripting.hpp" namespace element { @@ -64,7 +63,6 @@ class Context::Impl std::unique_ptr midi; std::unique_ptr lua; std::unique_ptr log; - std::unique_ptr modules; private: friend class Context; @@ -191,76 +189,4 @@ void Context::setEngine (AudioEnginePtr engine) devices().attach (engine); } -void Context::openModule (const std::string& ID) -{ - if (impl->modules->contains (ID)) - return; - - auto it = impl->modules->discovered.find (ID); - if (it == impl->modules->discovered.end()) - { - std::clog << "module not found: " << ID << std::endl; - return; - } - - if (auto mod = std::make_unique (it->second, *this, *impl->lua)) - { - if (mod->open()) - { - std::clog << "module opened: " << mod->name() << std::endl; - impl->modules->add (std::move (mod)); - } - else - { - std::clog << "could not open module: " << mod->name() << std::endl; - } - } -} - -void Context::loadModules() -{ - std::vector features; - - for (const auto& mod : *impl->modules) - { - for (const auto& e : mod->public_extensions()) - { - auto f = (elFeature*) std::malloc (sizeof (elFeature)); - features.push_back (f); - f->ID = strdup (e.first.c_str()); - f->data = (void*) e.second; - } - } - - auto ctxfeature = (elFeature*) malloc (sizeof (elFeature)); - ctxfeature->ID = strdup ("el.Context"); - ctxfeature->data = this; - features.push_back (ctxfeature); - features.push_back ((elFeature*) nullptr); - elFeatures fptr = &features.front(); - - for (const auto& mod : *impl->modules) - { - if (! mod->loaded()) - mod->load (fptr); - } - - for (auto f : features) - { - if (nullptr == f) - continue; - std::free ((void*) f->ID); - std::free ((void*) f); - } - features.clear(); -} - -void Context::addModulePath (const std::string& path) -{ - auto& sp = impl->modules->searchpath; - sp.add (path); -} - -void Context::discoverModules() { impl->modules->discover(); } - } // namespace element diff --git a/src/datapath.cpp b/src/datapath.cpp index 7392e6d87..21128bc90 100644 --- a/src/datapath.cpp +++ b/src/datapath.cpp @@ -10,6 +10,8 @@ #define EL_INSTALL_DIR_AWARE 1 #endif +using namespace juce; + namespace element { namespace detail { inline static StringArray getSubDirs() diff --git a/src/dlfcn-win32.c b/src/dlfcn-win32.c deleted file mode 100644 index fb4b04ca0..000000000 --- a/src/dlfcn-win32.c +++ /dev/null @@ -1,791 +0,0 @@ -// clang-format off -/* - * dlfcn-win32 - * Copyright (c) 2007 Ramiro Polla - * Copyright (c) 2015 Tiancheng "Timothy" Gu - * Copyright (c) 2019 Pali Rohár - * Copyright (c) 2020 Ralf Habacker - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#ifdef WIN32 - -#ifdef _DEBUG -#define _CRTDBG_MAP_ALLOC -#include -#include -#endif -#include -#include -#include - -/* Older versions do not have this type */ -#if _WIN32_WINNT < 0x0500 -typedef ULONG ULONG_PTR; -#endif - -/* Older SDK versions do not have these macros */ -#ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS -#define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 0x4 -#endif -#ifndef GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT -#define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 0x2 -#endif - -#ifdef _MSC_VER -/* https://docs.microsoft.com/en-us/cpp/intrinsics/returnaddress */ -#pragma intrinsic( _ReturnAddress ) -#else -/* https://gcc.gnu.org/onlinedocs/gcc/Return-Address.html */ -#ifndef _ReturnAddress -#define _ReturnAddress( ) ( __builtin_extract_return_addr( __builtin_return_address( 0 ) ) ) -#endif -#endif - -#ifdef DLFCN_WIN32_SHARED -#define DLFCN_WIN32_EXPORTS -#endif -#include "dynlib.h" - -#if defined( _MSC_VER ) && _MSC_VER >= 1300 -/* https://docs.microsoft.com/en-us/cpp/cpp/noinline */ -#define DLFCN_NOINLINE __declspec( noinline ) -#elif defined( __GNUC__ ) && ( ( __GNUC__ > 3 ) || ( __GNUC__ == 3 && __GNUC_MINOR__ >= 1 ) ) -/* https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html */ -#define DLFCN_NOINLINE __attribute__(( noinline )) -#else -#define DLFCN_NOINLINE -#endif - -/* Note: - * MSDN says these functions are not thread-safe. We make no efforts to have - * any kind of thread safety. - */ - -typedef struct local_object { - HMODULE hModule; - struct local_object *previous; - struct local_object *next; -} local_object; - -static local_object first_object; - -/* These functions implement a double linked list for the local objects. */ -static local_object *local_search( HMODULE hModule ) -{ - local_object *pobject; - - if( hModule == NULL ) - return NULL; - - for( pobject = &first_object; pobject; pobject = pobject->next ) - if( pobject->hModule == hModule ) - return pobject; - - return NULL; -} - -static BOOL local_add( HMODULE hModule ) -{ - local_object *pobject; - local_object *nobject; - - if( hModule == NULL ) - return TRUE; - - pobject = local_search( hModule ); - - /* Do not add object again if it's already on the list */ - if( pobject != NULL ) - return TRUE; - - for( pobject = &first_object; pobject->next; pobject = pobject->next ); - - nobject = (local_object *) malloc( sizeof( local_object ) ); - - if( !nobject ) - return FALSE; - - pobject->next = nobject; - nobject->next = NULL; - nobject->previous = pobject; - nobject->hModule = hModule; - - return TRUE; -} - -static void local_rem( HMODULE hModule ) -{ - local_object *pobject; - - if( hModule == NULL ) - return; - - pobject = local_search( hModule ); - - if( pobject == NULL ) - return; - - if( pobject->next ) - pobject->next->previous = pobject->previous; - if( pobject->previous ) - pobject->previous->next = pobject->next; - - free( pobject ); -} - -/* POSIX says dlerror( ) doesn't have to be thread-safe, so we use one - * static buffer. - * MSDN says the buffer cannot be larger than 64K bytes, so we set it to - * the limit. - */ -static char error_buffer[65535]; -static BOOL error_occurred; - -static void save_err_str( const char *str, DWORD dwMessageId ) -{ - DWORD ret; - size_t pos, len; - - len = strlen( str ); - if( len > sizeof( error_buffer ) - 5 ) - len = sizeof( error_buffer ) - 5; - - /* Format error message to: - * "": - */ - pos = 0; - error_buffer[pos++] = '"'; - memcpy( error_buffer + pos, str, len ); - pos += len; - error_buffer[pos++] = '"'; - error_buffer[pos++] = ':'; - error_buffer[pos++] = ' '; - - ret = FormatMessageA( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwMessageId, - MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), - error_buffer + pos, (DWORD) ( sizeof( error_buffer ) - pos ), NULL ); - pos += ret; - - /* When FormatMessageA() fails it returns zero and does not touch buffer - * so add trailing null byte */ - if( ret == 0 ) - error_buffer[pos] = '\0'; - - if( pos > 1 ) - { - /* POSIX says the string must not have trailing */ - if( error_buffer[pos-2] == '\r' && error_buffer[pos-1] == '\n' ) - error_buffer[pos-2] = '\0'; - } - - error_occurred = TRUE; -} - -static void save_err_ptr_str( const void *ptr, DWORD dwMessageId ) -{ - char ptr_buf[2 + 2 * sizeof( ptr ) + 1]; - char num; - size_t i; - - ptr_buf[0] = '0'; - ptr_buf[1] = 'x'; - - for( i = 0; i < 2 * sizeof( ptr ); i++ ) - { - num = (char) ( ( ( (ULONG_PTR) ptr ) >> ( 8 * sizeof( ptr ) - 4 * ( i + 1 ) ) ) & 0xF ); - ptr_buf[2 + i] = num + ( ( num < 0xA ) ? '0' : ( 'A' - 0xA ) ); - } - - ptr_buf[2 + 2 * sizeof( ptr )] = 0; - - save_err_str( ptr_buf, dwMessageId ); -} - -static HMODULE MyGetModuleHandleFromAddress( const void *addr ) -{ - static BOOL (WINAPI *GetModuleHandleExAPtr)(DWORD, LPCSTR, HMODULE *) = NULL; - static BOOL failed = FALSE; - HMODULE kernel32; - HMODULE hModule; - MEMORY_BASIC_INFORMATION info; - SIZE_T sLen; - - if( !failed && GetModuleHandleExAPtr == NULL ) - { - kernel32 = GetModuleHandleA( "Kernel32.dll" ); - if( kernel32 != NULL ) - GetModuleHandleExAPtr = (BOOL (WINAPI *)(DWORD, LPCSTR, HMODULE *)) GetProcAddress( kernel32, "GetModuleHandleExA" ); - if( GetModuleHandleExAPtr == NULL ) - failed = TRUE; - } - - if( !failed ) - { - /* If GetModuleHandleExA is available use it with GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS */ - if( !GetModuleHandleExAPtr( GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, addr, &hModule ) ) - return NULL; - } - else - { - /* To get HMODULE from address use undocumented hack from https://stackoverflow.com/a/2396380 - * The HMODULE of a DLL is the same value as the module's base address. - */ - sLen = VirtualQuery( addr, &info, sizeof( info ) ); - if( sLen != sizeof( info ) ) - return NULL; - hModule = (HMODULE) info.AllocationBase; - } - - return hModule; -} - -/* Load Psapi.dll at runtime, this avoids linking caveat */ -static BOOL MyEnumProcessModules( HANDLE hProcess, HMODULE *lphModule, DWORD cb, LPDWORD lpcbNeeded ) -{ - static BOOL (WINAPI *EnumProcessModulesPtr)(HANDLE, HMODULE *, DWORD, LPDWORD) = NULL; - static BOOL failed = FALSE; - UINT uMode; - HMODULE psapi; - - if( failed ) - return FALSE; - - if( EnumProcessModulesPtr == NULL ) - { - /* Windows 7 and newer versions have K32EnumProcessModules in Kernel32.dll which is always pre-loaded */ - psapi = GetModuleHandleA( "Kernel32.dll" ); - if( psapi != NULL ) - EnumProcessModulesPtr = (BOOL (WINAPI *)(HANDLE, HMODULE *, DWORD, LPDWORD)) GetProcAddress( psapi, "K32EnumProcessModules" ); - - /* Windows Vista and older version have EnumProcessModules in Psapi.dll which needs to be loaded */ - if( EnumProcessModulesPtr == NULL ) - { - /* Do not let Windows display the critical-error-handler message box */ - uMode = SetErrorMode( SEM_FAILCRITICALERRORS ); - psapi = LoadLibraryA( "Psapi.dll" ); - if( psapi != NULL ) - { - EnumProcessModulesPtr = (BOOL (WINAPI *)(HANDLE, HMODULE *, DWORD, LPDWORD)) GetProcAddress( psapi, "EnumProcessModules" ); - if( EnumProcessModulesPtr == NULL ) - FreeLibrary( psapi ); - } - SetErrorMode( uMode ); - } - - if( EnumProcessModulesPtr == NULL ) - { - failed = TRUE; - return FALSE; - } - } - - return EnumProcessModulesPtr( hProcess, lphModule, cb, lpcbNeeded ); -} - -DLFCN_EXPORT -void *dlopen( const char *file, int mode ) -{ - HMODULE hModule; - UINT uMode; - - error_occurred = FALSE; - - /* Do not let Windows display the critical-error-handler message box */ - uMode = SetErrorMode( SEM_FAILCRITICALERRORS ); - - if( file == NULL ) - { - /* POSIX says that if the value of file is NULL, a handle on a global - * symbol object must be provided. That object must be able to access - * all symbols from the original program file, and any objects loaded - * with the RTLD_GLOBAL flag. - * The return value from GetModuleHandle( ) allows us to retrieve - * symbols only from the original program file. EnumProcessModules() is - * used to access symbols from other libraries. For objects loaded - * with the RTLD_LOCAL flag, we create our own list later on. They are - * excluded from EnumProcessModules() iteration. - */ - hModule = GetModuleHandle( NULL ); - - if( !hModule ) - save_err_str( "(null)", GetLastError( ) ); - } - else - { - HANDLE hCurrentProc; - DWORD dwProcModsBefore, dwProcModsAfter; - char lpFileName[MAX_PATH]; - size_t i, len; - - len = strlen( file ); - - if( len >= sizeof( lpFileName ) ) - { - save_err_str( file, ERROR_FILENAME_EXCED_RANGE ); - hModule = NULL; - } - else - { - /* MSDN says backslashes *must* be used instead of forward slashes. */ - for( i = 0; i < len; i++ ) - { - if( file[i] == '/' ) - lpFileName[i] = '\\'; - else - lpFileName[i] = file[i]; - } - lpFileName[len] = '\0'; - - hCurrentProc = GetCurrentProcess( ); - - if( MyEnumProcessModules( hCurrentProc, NULL, 0, &dwProcModsBefore ) == 0 ) - dwProcModsBefore = 0; - - /* POSIX says the search path is implementation-defined. - * LOAD_WITH_ALTERED_SEARCH_PATH is used to make it behave more closely - * to UNIX's search paths (start with system folders instead of current - * folder). - */ - hModule = LoadLibraryExA( lpFileName, NULL, LOAD_WITH_ALTERED_SEARCH_PATH ); - - if( !hModule ) - { - save_err_str( lpFileName, GetLastError( ) ); - } - else - { - if( MyEnumProcessModules( hCurrentProc, NULL, 0, &dwProcModsAfter ) == 0 ) - dwProcModsAfter = 0; - - /* If the object was loaded with RTLD_LOCAL, add it to list of local - * objects, so that its symbols cannot be retrieved even if the handle for - * the original program file is passed. POSIX says that if the same - * file is specified in multiple invocations, and any of them are - * RTLD_GLOBAL, even if any further invocations use RTLD_LOCAL, the - * symbols will remain global. If number of loaded modules was not - * changed after calling LoadLibraryEx(), it means that library was - * already loaded. - */ - if( (mode & RTLD_LOCAL) && dwProcModsBefore != dwProcModsAfter ) - { - if( !local_add( hModule ) ) - { - save_err_str( lpFileName, ERROR_NOT_ENOUGH_MEMORY ); - FreeLibrary( hModule ); - hModule = NULL; - } - } - else if( !(mode & RTLD_LOCAL) && dwProcModsBefore == dwProcModsAfter ) - { - local_rem( hModule ); - } - } - } - } - - /* Return to previous state of the error-mode bit flags. */ - SetErrorMode( uMode ); - - return (void *) hModule; -} - -DLFCN_EXPORT -int dlclose( void *handle ) -{ - HMODULE hModule = (HMODULE) handle; - BOOL ret; - - error_occurred = FALSE; - - ret = FreeLibrary( hModule ); - - /* If the object was loaded with RTLD_LOCAL, remove it from list of local - * objects. - */ - if( ret ) - local_rem( hModule ); - else - save_err_ptr_str( handle, GetLastError( ) ); - - /* dlclose's return value in inverted in relation to FreeLibrary's. */ - ret = !ret; - - return (int) ret; -} - -DLFCN_NOINLINE /* Needed for _ReturnAddress() */ -DLFCN_EXPORT -void *dlsym( void *handle, const char *name ) -{ - FARPROC symbol; - HMODULE hCaller; - HMODULE hModule; - DWORD dwMessageId; - - error_occurred = FALSE; - - symbol = NULL; - hCaller = NULL; - hModule = GetModuleHandle( NULL ); - dwMessageId = 0; - - if( handle == RTLD_DEFAULT ) - { - /* The symbol lookup happens in the normal global scope; that is, - * a search for a symbol using this handle would find the same - * definition as a direct use of this symbol in the program code. - * So use same lookup procedure as when filename is NULL. - */ - handle = hModule; - } - else if( handle == RTLD_NEXT ) - { - /* Specifies the next object after this one that defines name. - * This one refers to the object containing the invocation of dlsym(). - * The next object is the one found upon the application of a load - * order symbol resolution algorithm. To get caller function of dlsym() - * use _ReturnAddress() intrinsic. To get HMODULE of caller function - * use MyGetModuleHandleFromAddress() which calls either standard - * GetModuleHandleExA() function or hack via VirtualQuery(). - */ - hCaller = MyGetModuleHandleFromAddress( _ReturnAddress( ) ); - - if( hCaller == NULL ) - { - dwMessageId = ERROR_INVALID_PARAMETER; - goto end; - } - } - - if( handle != RTLD_NEXT ) - { - symbol = GetProcAddress( (HMODULE) handle, name ); - - if( symbol != NULL ) - goto end; - } - - /* If the handle for the original program file is passed, also search - * in all globally loaded objects. - */ - - if( hModule == handle || handle == RTLD_NEXT ) - { - HANDLE hCurrentProc; - HMODULE *modules; - DWORD cbNeeded; - DWORD dwSize; - size_t i; - - hCurrentProc = GetCurrentProcess( ); - - /* GetModuleHandle( NULL ) only returns the current program file. So - * if we want to get ALL loaded module including those in linked DLLs, - * we have to use EnumProcessModules( ). - */ - if( MyEnumProcessModules( hCurrentProc, NULL, 0, &dwSize ) != 0 ) - { - modules = malloc( dwSize ); - if( modules ) - { - if( MyEnumProcessModules( hCurrentProc, modules, dwSize, &cbNeeded ) != 0 && dwSize == cbNeeded ) - { - for( i = 0; i < dwSize / sizeof( HMODULE ); i++ ) - { - if( handle == RTLD_NEXT && hCaller ) - { - /* Next modules can be used for RTLD_NEXT */ - if( hCaller == modules[i] ) - hCaller = NULL; - continue; - } - if( local_search( modules[i] ) ) - continue; - symbol = GetProcAddress( modules[i], name ); - if( symbol != NULL ) - { - free( modules ); - goto end; - } - } - - } - free( modules ); - } - else - { - dwMessageId = ERROR_NOT_ENOUGH_MEMORY; - goto end; - } - } - } - -end: - if( symbol == NULL ) - { - if( !dwMessageId ) - dwMessageId = ERROR_PROC_NOT_FOUND; - save_err_str( name, dwMessageId ); - } - - return *(void **) (&symbol); -} - -DLFCN_EXPORT -char *dlerror( void ) -{ - /* If this is the second consecutive call to dlerror, return NULL */ - if( !error_occurred ) - return NULL; - - /* POSIX says that invoking dlerror( ) a second time, immediately following - * a prior invocation, shall result in NULL being returned. - */ - error_occurred = FALSE; - - return error_buffer; -} - -/* See https://docs.microsoft.com/en-us/archive/msdn-magazine/2002/march/inside-windows-an-in-depth-look-into-the-win32-portable-executable-file-format-part-2 - * for details */ - -/* Get specific image section */ -static BOOL get_image_section( HMODULE module, int index, void **ptr, DWORD *size ) -{ - IMAGE_DOS_HEADER *dosHeader; - IMAGE_OPTIONAL_HEADER *optionalHeader; - - dosHeader = (IMAGE_DOS_HEADER *) module; - - if( dosHeader->e_magic != 0x5A4D ) - return FALSE; - - optionalHeader = (IMAGE_OPTIONAL_HEADER *) ( (BYTE *) module + dosHeader->e_lfanew + 24 ); - - if( optionalHeader->Magic != IMAGE_NT_OPTIONAL_HDR_MAGIC ) - return FALSE; - - if( index < 0 || index > IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR ) - return FALSE; - - if( optionalHeader->DataDirectory[index].Size == 0 || optionalHeader->DataDirectory[index].VirtualAddress == 0 ) - return FALSE; - - if( size != NULL ) - *size = optionalHeader->DataDirectory[index].Size; - - *ptr = (void *)( (BYTE *) module + optionalHeader->DataDirectory[index].VirtualAddress ); - - return TRUE; -} - -/* Return symbol name for a given address from export table */ -static const char *get_export_symbol_name( HMODULE module, IMAGE_EXPORT_DIRECTORY *ied, const void *addr, void **func_address ) -{ - DWORD i; - void *candidateAddr = NULL; - int candidateIndex = -1; - BYTE *base = (BYTE *) module; - DWORD *functionAddressesOffsets = (DWORD *) (base + ied->AddressOfFunctions); - DWORD *functionNamesOffsets = (DWORD *) (base + ied->AddressOfNames); - USHORT *functionNameOrdinalsIndexes = (USHORT *) (base + ied->AddressOfNameOrdinals); - - for( i = 0; i < ied->NumberOfFunctions; i++ ) - { - if( (void *) ( base + functionAddressesOffsets[i] ) > addr || candidateAddr >= (void *) ( base + functionAddressesOffsets[i] ) ) - continue; - - candidateAddr = (void *) ( base + functionAddressesOffsets[i] ); - candidateIndex = i; - } - - if( candidateIndex == -1 ) - return NULL; - - *func_address = candidateAddr; - - for( i = 0; i < ied->NumberOfNames; i++ ) - { - if( functionNameOrdinalsIndexes[i] == candidateIndex ) - return (const char *) ( base + functionNamesOffsets[i] ); - } - - return NULL; -} - -static BOOL is_valid_address( const void *addr ) -{ - MEMORY_BASIC_INFORMATION info; - SIZE_T result; - - if( addr == NULL ) - return FALSE; - - /* check valid pointer */ - result = VirtualQuery( addr, &info, sizeof( info ) ); - - if( result == 0 || info.AllocationBase == NULL || info.AllocationProtect == 0 || info.AllocationProtect == PAGE_NOACCESS ) - return FALSE; - - return TRUE; -} - -/* Return state if address points to an import thunk - * - * An import thunk is setup with a 'jmp' instruction followed by an - * absolute address (32bit) or relative offset (64bit) pointing into - * the import address table (iat), which is partially maintained by - * the runtime linker. - */ -static BOOL is_import_thunk( const void *addr ) -{ - return *(short *) addr == 0x25ff ? TRUE : FALSE; -} - -/* Return adress from the import address table (iat), - * if the original address points to a thunk table entry. - */ -static void *get_address_from_import_address_table( void *iat, DWORD iat_size, const void *addr ) -{ - BYTE *thkp = (BYTE *) addr; - /* Get offset from thunk table (after instruction 0xff 0x25) - * 4018c8 <_VirtualQuery>: ff 25 4a 8a 00 00 - */ - ULONG offset = *(ULONG *)( thkp + 2 ); -#ifdef _WIN64 - /* On 64 bit the offset is relative - * 4018c8: ff 25 4a 8a 00 00 jmpq *0x8a4a(%rip) # 40a318 <__imp_VirtualQuery> - * And can be also negative (MSVC in WDK) - * 100002f20: ff 25 3a e1 ff ff jmpq *-0x1ec6(%rip) # 0x100001060 - * So cast to signed LONG type - */ - BYTE *ptr = (BYTE *)( thkp + 6 + (LONG) offset ); -#else - /* On 32 bit the offset is absolute - * 4019b4: ff 25 90 71 40 00 jmp *0x40719 - */ - BYTE *ptr = (BYTE *) offset; -#endif - - if( !is_valid_address( ptr ) || ptr < (BYTE *) iat || ptr > (BYTE *) iat + iat_size ) - return NULL; - - return *(void **) ptr; -} - -/* Holds module filename */ -static char module_filename[2*MAX_PATH]; - -static BOOL fill_info( const void *addr, Dl_info *info ) -{ - HMODULE hModule; - DWORD dwSize; - IMAGE_EXPORT_DIRECTORY *ied; - void *funcAddress = NULL; - - /* Get module of the specified address */ - hModule = MyGetModuleHandleFromAddress( addr ); - - if( hModule == NULL ) - return FALSE; - - dwSize = GetModuleFileNameA( hModule, module_filename, sizeof( module_filename ) ); - - if( dwSize == 0 || dwSize == sizeof( module_filename ) ) - return FALSE; - - info->dli_fname = module_filename; - info->dli_fbase = (void *) hModule; - - /* Find function name and function address in module's export table */ - if( get_image_section( hModule, IMAGE_DIRECTORY_ENTRY_EXPORT, (void **) &ied, NULL ) ) - info->dli_sname = get_export_symbol_name( hModule, ied, addr, &funcAddress ); - else - info->dli_sname = NULL; - - info->dli_saddr = info->dli_sname == NULL ? NULL : funcAddress != NULL ? funcAddress : (void *) addr; - - return TRUE; -} - -DLFCN_EXPORT -int dladdr( const void *addr, Dl_info *info ) -{ - if( info == NULL ) - return 0; - - if( !is_valid_address( addr ) ) - return 0; - - if( is_import_thunk( addr ) ) - { - void *iat; - DWORD iatSize; - HMODULE hModule; - - /* Get module of the import thunk address */ - hModule = MyGetModuleHandleFromAddress( addr ); - - if( hModule == NULL ) - return 0; - - if( !get_image_section( hModule, IMAGE_DIRECTORY_ENTRY_IAT, &iat, &iatSize ) ) - { - /* Fallback for cases where the iat is not defined, - * for example i586-mingw32msvc-gcc */ - IMAGE_IMPORT_DESCRIPTOR *iid; - DWORD iidSize; - - if( !get_image_section( hModule, IMAGE_DIRECTORY_ENTRY_IMPORT, (void **) &iid, &iidSize ) ) - return 0; - - if( iid == NULL || iid->Characteristics == 0 || iid->FirstThunk == 0 ) - return 0; - - iat = (void *)( (BYTE *) hModule + iid->FirstThunk ); - /* We assume that in this case iid and iat's are in linear order */ - iatSize = iidSize - (DWORD) ( (BYTE *) iat - (BYTE *) iid ); - } - - addr = get_address_from_import_address_table( iat, iatSize, addr ); - - if( !is_valid_address( addr ) ) - return 0; - } - - if( !fill_info( addr, info ) ) - return 0; - - return 1; -} - -#ifdef DLFCN_WIN32_SHARED -BOOL WINAPI DllMain( HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved ) -{ - (void) hinstDLL; - (void) fdwReason; - (void) lpvReserved; - return TRUE; -} -#endif -// clang-format on - -#endif diff --git a/src/dlfcn-win32.h b/src/dlfcn-win32.h deleted file mode 100644 index ce9b137b4..000000000 --- a/src/dlfcn-win32.h +++ /dev/null @@ -1,104 +0,0 @@ - -#ifndef EL_DYNLIB_H -#error "don't include dlfcn-win32.h directly, use dynlib.h instead" -#endif -#undef DLFCN_WIN32_SHARED - -// clang-format off - -/* - * dlfcn-win32 - * Copyright (c) 2007 Ramiro Polla - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#ifndef DLFCN_H -#define DLFCN_H - -#ifdef __cplusplus -extern "C" { -#endif - -#if defined(DLFCN_WIN32_SHARED) -#if defined(DLFCN_WIN32_EXPORTS) -# define DLFCN_EXPORT __declspec(dllexport) -#else -# define DLFCN_EXPORT __declspec(dllimport) -#endif -#else -# define DLFCN_EXPORT -#endif - -/* Relocations are performed when the object is loaded. */ -#define RTLD_NOW 0 - -/* Relocations are performed at an implementation-defined time. - * Windows API does not support lazy symbol resolving (when first reference - * to a given symbol occurs). So RTLD_LAZY implementation is same as RTLD_NOW. - */ -#define RTLD_LAZY RTLD_NOW - -/* All symbols are available for relocation processing of other modules. */ -#define RTLD_GLOBAL (1 << 1) - -/* All symbols are not made available for relocation processing by other modules. */ -#define RTLD_LOCAL (1 << 2) - -/* These two were added in The Open Group Base Specifications Issue 6. - * Note: All other RTLD_* flags in any dlfcn.h are not standard compliant. - */ - -/* The symbol lookup happens in the normal global scope. */ -#define RTLD_DEFAULT ((void *)0) - -/* Specifies the next object after this one that defines name. */ -#define RTLD_NEXT ((void *)-1) - -/* Structure filled in by dladdr() */ -typedef struct dl_info -{ - const char *dli_fname; /* Filename of defining object (thread unsafe and reused on every call to dladdr) */ - void *dli_fbase; /* Load address of that object */ - const char *dli_sname; /* Name of nearest lower symbol */ - void *dli_saddr; /* Exact value of nearest symbol */ -} Dl_info; - -/* Open a symbol table handle. */ -DLFCN_EXPORT void *dlopen(const char *file, int mode); - -/* Close a symbol table handle. */ -DLFCN_EXPORT int dlclose(void *handle); - -/* Get the address of a symbol from a symbol table handle. */ -DLFCN_EXPORT void *dlsym(void *handle, const char *name); - -/* Get diagnostic information. */ -DLFCN_EXPORT char *dlerror(void); - -/* Translate address to symbolic information (no POSIX standard) */ -DLFCN_EXPORT int dladdr(const void *addr, Dl_info *info); - -#ifdef __cplusplus -} -#endif - -#endif /* DLFCN_H */ - -// clang-format on diff --git a/src/dynlib.h b/src/dynlib.h deleted file mode 100644 index 23a87823d..000000000 --- a/src/dynlib.h +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2023 Kushview, LLC -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef EL_DYNLIB_H -#define EL_DYNLIB_H - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef _WIN32 -#include "dlfcn-win32.h" -#else -#include -#endif - -inline static void* element_openlib (const char* path) -{ - return dlopen (path, RTLD_LOCAL | RTLD_LAZY); -} - -inline static void element_closelib (void* handle) -{ - dlclose (handle); -} - -inline static void* element_getsym (void* handle, const char* f) -{ - return dlsym (handle, f); -} - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/src/el/Session.cpp b/src/el/Session.cpp index 6ce053e8b..40c18482c 100644 --- a/src/el/Session.cpp +++ b/src/el/Session.cpp @@ -12,6 +12,8 @@ #include "sol_helpers.hpp" +using namespace juce; + // clang-format off EL_PLUGIN_EXPORT int luaopen_el_Session (lua_State* L) diff --git a/src/el/View.cpp b/src/el/View.cpp index 437951c55..040db44ea 100644 --- a/src/el/View.cpp +++ b/src/el/View.cpp @@ -13,6 +13,8 @@ #define EL_TYPE_NAME_VIEW "View" +using namespace juce; + namespace element { namespace lua { diff --git a/src/el/widget.hpp b/src/el/widget.hpp index e3bc72d2d..19a2587a2 100644 --- a/src/el/widget.hpp +++ b/src/el/widget.hpp @@ -8,10 +8,9 @@ #pragma once #include -#include "sol_helpers.hpp" -#include +#include -using namespace juce; +#include "sol_helpers.hpp" namespace element { namespace lua { @@ -42,18 +41,18 @@ class WidgetProxy /// Draw your widget here. // @function Widget:paint // @tparam el.Graphics g The graphics object to paint with - void paint (Graphics& g) + void paint (juce::Graphics& g) { if (sol::safe_function f = widget["paint"]) { - f (widget, std::ref (g)); + f (widget, std::ref (g)); } } /// Called when the mouse is moving. // @function Widget:mouseMove // @tparam el.MouseEvent ev The event to process - void mouseMove (const MouseEvent& ev) + void mouseMove (const juce::MouseEvent& ev) { if (sol::safe_function f = widget["mouseMove"]) f (widget, ev); @@ -62,7 +61,7 @@ class WidgetProxy /// Called when the mouse enters your widget. // @function Widget:mouseEnter // @tparam el.MouseEvent ev The event to process - void mouseEnter (const MouseEvent& ev) + void mouseEnter (const juce::MouseEvent& ev) { if (sol::safe_function f = widget["mouseEnter"]) f (widget, ev); @@ -71,7 +70,7 @@ class WidgetProxy /// Called when the mouse exits your widget. // @function Widget:mouseExit // @tparam el.MouseEvent ev The event to process - void mouseExit (const MouseEvent& ev) + void mouseExit (const juce::MouseEvent& ev) { if (sol::safe_function f = widget["mouseExit"]) f (widget, ev); @@ -80,7 +79,7 @@ class WidgetProxy /// Called when the mouse is dragging. // @function Widget:mouseDrag // @tparam el.MouseEvent ev The event to process - void mouseDrag (const MouseEvent& ev) + void mouseDrag (const juce::MouseEvent& ev) { if (sol::safe_function f = widget["mouseDrag"]) f (widget, ev); @@ -89,7 +88,7 @@ class WidgetProxy /// Called when the mouse is pressed down. // @function Widget:mouseDown // @tparam el.MouseEvent ev The event to process - void mouseDown (const MouseEvent& ev) + void mouseDown (const juce::MouseEvent& ev) { if (sol::safe_function f = widget["mouseDown"]) f (widget, ev); @@ -98,7 +97,7 @@ class WidgetProxy /// Called when the mouse has been released. // @function Widget:mouseUp // @tparam el.MouseEvent ev The event to process - void mouseUp (const MouseEvent& ev) + void mouseUp (const juce::MouseEvent& ev) { if (sol::safe_function f = widget["mouseUp"]) f (widget, ev); @@ -107,7 +106,7 @@ class WidgetProxy /// Called when the mouse is double clicked. // @function Widget:mouseDoubleClick // @tparam el.MouseEvent ev The event to process - void mouseDoubleClick (const MouseEvent& ev) + void mouseDoubleClick (const juce::MouseEvent& ev) { if (sol::safe_function f = widget["mouseDoubleClick"]) f (widget, ev); @@ -117,7 +116,7 @@ class WidgetProxy // @function Widget:mouseWheelMove // @tparam el.MouseEvent ev The event to process // @tparam mixed details Wheel info to process - void mouseWheelMove (const MouseEvent& ev, const MouseWheelDetails& details) + void mouseWheelMove (const juce::MouseEvent& ev, const juce::MouseWheelDetails& details) { if (sol::safe_function f = widget["mouseWheelMove"]) f (widget, ev, details); @@ -127,7 +126,7 @@ class WidgetProxy // @function Widget:mouseWheelMove // @tparam el.MouseEvent ev The event to process // @param scale The scale to magnify by, 1.0 being no scale - void mouseMagnify (const MouseEvent& ev, float scale) + void mouseMagnify (const juce::MouseEvent& ev, float scale) { if (sol::safe_function f = widget["mouseMagnify"]) f (widget, ev, static_cast (scale)); @@ -136,9 +135,9 @@ class WidgetProxy sol::table addWithZ (const sol::object& child, int zorder) { jassert (child.valid()); - if (auto* const w = object_userdata (widget)) + if (auto* const w = object_userdata (widget)) { - if (Component* const impl = object_userdata (child)) + if (juce::Component* const impl = object_userdata (child)) { w->addAndMakeVisible (*impl, zorder); } @@ -154,7 +153,7 @@ class WidgetProxy void init (const sol::table& proxy) { widget = proxy; - data = object_userdata (widget); + data = object_userdata (widget); } sol::table getBoundsTable() @@ -169,11 +168,11 @@ class WidgetProxy return t; } - Component* component() noexcept { return data; } + juce::Component* component() noexcept { return data; } private: sol::table widget; - Component* data = nullptr; + juce::Component* data = nullptr; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WidgetProxy) }; @@ -281,7 +280,7 @@ inline static sol::table defineWidget (lua_State* L, const char* name, Args&&... // }) "setBounds", sol::overload ( [] (Widget& self, double x, double y, double w, double h) { - self.setBounds (Rectangle (x, y, w, h).toNearestInt()); }, + self.setBounds (juce::Rectangle (x, y, w, h).toNearestInt()); }, [] (Widget& self, const sol::object& obj) { widget_setbounds (self, obj); } ), diff --git a/src/engine/audioengine.cpp b/src/engine/audioengine.cpp index ebcfe4f77..8afe52a13 100644 --- a/src/engine/audioengine.cpp +++ b/src/engine/audioengine.cpp @@ -949,7 +949,7 @@ void AudioEngine::setRecording (const bool shouldBeRecording) transport.requestRecordState (shouldBeRecording); } -void AudioEngine::seekToAudioFrame (const int64 frame) +void AudioEngine::seekToAudioFrame (const int64_t frame) { auto& transport (priv->transport); transport.requestAudioFrame (frame); diff --git a/src/engine/clapprovider.cpp b/src/engine/clapprovider.cpp index 2b9d0fd7e..1c853094d 100644 --- a/src/engine/clapprovider.cpp +++ b/src/engine/clapprovider.cpp @@ -53,6 +53,8 @@ static void _fpreset() #define CLAP_LOG(a) #endif +using namespace juce; + namespace element { namespace detail { #if JUCE_MAC diff --git a/src/engine/clapprovider.hpp b/src/engine/clapprovider.hpp index 75b54b4c6..57257eb63 100644 --- a/src/engine/clapprovider.hpp +++ b/src/engine/clapprovider.hpp @@ -19,11 +19,11 @@ class CLAPProvider final : public NodeProvider juce::String format() const override; Processor* create (const juce::String&) override; juce::FileSearchPath defaultSearchPath() override; - juce::StringArray findTypes (const FileSearchPath& path, + juce::StringArray findTypes (const juce::FileSearchPath& path, bool recursive, bool allowAsync) override; - StringArray getHiddenTypes() override { return {}; } - void scan (const String& fileOrID, OwnedArray& out) override; + juce::StringArray getHiddenTypes() override { return {}; } + void scan (const juce::String& fileOrID, juce::OwnedArray& out) override; private: class Host; diff --git a/src/engine/internalformat.cpp b/src/engine/internalformat.cpp index 9947d9ddf..a24a02601 100644 --- a/src/engine/internalformat.cpp +++ b/src/engine/internalformat.cpp @@ -1,8 +1,6 @@ // Copyright 2023 Kushview, LLC // SPDX-License-Identifier: GPL-3.0-or-later -#include "ElementApp.h" - #include #include #include diff --git a/src/engine/ionode.hpp b/src/engine/ionode.hpp index d50336803..40d4442a3 100644 --- a/src/engine/ionode.hpp +++ b/src/engine/ionode.hpp @@ -3,6 +3,7 @@ #pragma once +#include #include namespace element { @@ -63,10 +64,10 @@ class IONode : public Processor /** True if this is an audio or midi output. */ bool isOutput() const; - void fillInPluginDescription (PluginDescription& d) const; + void fillInPluginDescription (juce::PluginDescription& d) const; - const String getInputChannelName (int channelIndex) const; - const String getOutputChannelName (int channelIndex) const; + const juce::String getInputChannelName (int channelIndex) const; + const juce::String getOutputChannelName (int channelIndex) const; //========================================================================== void refreshPorts() override; @@ -74,7 +75,7 @@ class IONode : public Processor void prepareToRender (double, int) override; void releaseResources() override; void render (RenderContext&) override; - void getState (MemoryBlock&) override {} + void getState (juce::MemoryBlock&) override {} void setState (const void*, int sizeInBytes) override {} //========================================================================== diff --git a/src/engine/jack.cpp b/src/engine/jack.cpp index 2ce5d48f5..e8301965d 100644 --- a/src/engine/jack.cpp +++ b/src/engine/jack.cpp @@ -27,7 +27,12 @@ #include #include "engine/jack.hpp" -#include "dynlib.h" + +#ifdef _WIN32 +// FIXME: +#else +#include +#endif using namespace juce; diff --git a/src/engine/midipipe.cpp b/src/engine/midipipe.cpp index 6f5266c41..b61a43faa 100644 --- a/src/engine/midipipe.cpp +++ b/src/engine/midipipe.cpp @@ -10,7 +10,6 @@ #include #include -#include "ElementApp.h" #include "el/midi_buffer.hpp" #include "el/factories.hpp" diff --git a/src/engine/processor.cpp b/src/engine/processor.cpp index 823f5cc2d..f562419cb 100644 --- a/src/engine/processor.cpp +++ b/src/engine/processor.cpp @@ -8,8 +8,6 @@ #include #include -#include "ElementApp.h" - #include "nodes/audioprocessor.hpp" #include "nodes/mididevice.hpp" #include "nodes/placeholder.hpp" diff --git a/src/feature_store.hpp b/src/feature_store.hpp deleted file mode 100644 index 6c46cae77..000000000 --- a/src/feature_store.hpp +++ /dev/null @@ -1,173 +0,0 @@ -// Copyright 2023 Kushview, LLC -// SPDX-License-Identifier: GPL-3.0-or-later - -#include -#include -#include - -/** Feature implementation template. - * The template parameter should be a -*/ -template -class FeatureData -{ -public: - using data_type = CType; - ~FeatureData() = default; - const data_type* get() const noexcept { return &data; } - -protected: - FeatureData() = default; - data_type& reference() { return data; } - -private: - data_type data; -}; - -class FeatureType -{ -public: - virtual ~FeatureType() = default; - const elFeature* c_type() const noexcept { return &f; } - const std::string& ID() const noexcept { return fid; } - const void* data() const noexcept { return f.data; } - -protected: - FeatureType() = default; - - void set_details (const char* ID, void* data) - { - fid = std::string (ID); - f.ID = fid.c_str(); - f.data = data; - } - -private: - std::string fid; - elFeature f; -}; - -/** List of referenced features. */ -class Features final -{ -public: - using VectorType = std::vector; - - Features() { features.push_back (nullptr); } - Features (const elFeature* const* cfeatures) - { - for (int i = 0; cfeatures[i] != nullptr; ++i) - { - features.push_back (cfeatures[i]); - } - features.push_back (nullptr); - } - - ~Features() { features.clear(); } - - void clear() noexcept { features.clear(); } - size_t size() const noexcept { return features.size() - 1; } - void reserve (size_t num) { features.reserve (num); } - auto begin() const noexcept { return features.cbegin(); } - auto end() const noexcept { return std::prev (features.cend()); } - - const void* find (const char* ID) const noexcept - { - for (const auto* f : *this) - if (strcmp (f->ID, ID) == 0) - return f->data; - return nullptr; - } - - bool contains (const char* ID) const noexcept { return nullptr != find (ID); } - elFeatures c_type() const noexcept { return features.data(); } - operator const elFeature* const*() const noexcept - { - return features.data(); - } - -private: - VectorType features; - Features (const Features& o) = delete; - Features (const Features&& o) = delete; - Features& operator= (const Features& o) = delete; -}; - -/** Collection of feature implementations. */ -class FeatureStore -{ -public: - FeatureStore() = default; - virtual ~FeatureStore() = default; - - operator elFeatures() const noexcept - { - build_cached (false); - return cached.data(); - } - - /** Add a new feature to the list. - - The passed object will be owned and deleted by the Features - class. - - @param ft The feature to add - */ - void add_type (FeatureType* ft) noexcept - { - auto sft = std::shared_ptr (ft); - types.push_back (sft); - ++dirty; - } - - const void* data (const std::string& feature) const noexcept - { - for (const auto& f : types) - if (f->ID() == feature) - return f->data(); - return nullptr; - } - - void clear() - { - while (types.size() > 0) - { - auto ptr = types.back(); - types.pop_back(); - ptr.reset(); - } - } - -private: - EL_DISABLE_COPY (FeatureStore) - EL_DISABLE_MOVE (FeatureStore) - - using TypeVec = std::vector>; - TypeVec types; - - Features::VectorType cached; - uint32_t dirty = 1; - - void clear_cached() - { - cached.clear(); - cached.reserve (types.size() + 1); - ++dirty; - } - - void build_cached (bool force) const - { - (const_cast (this))->build_cached_impl (force); - } - - void build_cached_impl (bool force) - { - if (dirty == 0 && ! force) - return; - clear_cached(); - for (const auto& t : types) - cached.push_back (t->c_type()); - cached.push_back (nullptr); - dirty = 0; - } -}; diff --git a/src/manifest.hpp b/src/manifest.hpp deleted file mode 100644 index d289f9a32..000000000 --- a/src/manifest.hpp +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright 2023 Kushview, LLC -// SPDX-License-Identifier: GPL-3.0-or-later - -#pragma once - -#include -#include - -#include -#include - -namespace element { - -static constexpr const char* MANIFEST_FILENAME = "manifest.lua"; - -struct Manifest -{ - Manifest() = default; - Manifest (const Manifest&& o) - { - this->name = std::move (o.name); - this->provides = std::move (o.provides); - } - - Manifest& operator= (const Manifest& o) - { - name = o.name; - provides = o.provides; - return *this; - } - - std::string name; - std::vector provides; -}; - -template -static Manifest read_module_manifest (Tx&& bundle_path) -{ - Manifest result; - std::filesystem::path f (bundle_path); - f /= MANIFEST_FILENAME; - f.make_preferred(); - - sol::state state; - state.open_libraries (sol::lib::base, sol::lib::string); - - try - { - state.safe_script_file (f.string()); - - result.name = state.get_or ("name", std::string ("")); - - auto provides = state.get_or ("provides", sol::table()); - if (provides.valid()) - for (const auto& item : provides) - if (item.first.is() && item.second.is()) - result.provides.push_back (item.second.as()); - - } catch (const std::exception& e) - { - std::clog << "config error: " << e.what() << std::endl; - } - - return result; -} - -} // namespace element diff --git a/src/messages.cpp b/src/messages.cpp index d31b27bb5..51fcce9d7 100644 --- a/src/messages.cpp +++ b/src/messages.cpp @@ -8,9 +8,11 @@ #include "messages.hpp" +using namespace juce; + namespace element { -class AddPluginAction : public UndoableAction +class AddPluginAction : public juce::UndoableAction { public: AddPluginAction (Services& _app, const AddPluginMessage& msg) @@ -58,7 +60,7 @@ class AddPluginAction : public UndoableAction } }; -class RemoveNodeAction : public UndoableAction +class RemoveNodeAction : public juce::UndoableAction { public: explicit RemoveNodeAction (Services& a, const Node& node) @@ -96,11 +98,11 @@ class RemoveNodeAction : public UndoableAction private: Services& app; - ValueTree nodeData; + juce::ValueTree nodeData; const Node targetGraph; - const Uuid nodeUuid; + const juce::Uuid nodeUuid; ConnectionBuilder builder; - OwnedArray arcs; + juce::OwnedArray arcs; double x = 0.5; double y = 0.5; bool isDataValid() const @@ -109,7 +111,7 @@ class RemoveNodeAction : public UndoableAction } }; -class AddConnectionAction : public UndoableAction +class AddConnectionAction : public juce::UndoableAction { public: AddConnectionAction (Services& a, const Node& targetGraph, const uint32 sn, const uint32 sp, const uint32 dn, const uint32 dp) @@ -143,7 +145,7 @@ class AddConnectionAction : public UndoableAction const Arc arc; }; -class RemoveConnectionAction : public UndoableAction +class RemoveConnectionAction : public juce::UndoableAction { public: RemoveConnectionAction (Services& a, const Node& targetGraph, const uint32 sn, const uint32 sp, const uint32 dn, const uint32 dp) diff --git a/src/messages.hpp b/src/messages.hpp index 113f6a897..448d8c3a0 100644 --- a/src/messages.hpp +++ b/src/messages.hpp @@ -3,7 +3,9 @@ #pragma once -#include "ElementApp.h" +#include +#include + #include #include @@ -13,7 +15,7 @@ class Services; class ContentView; class Context; -class Action : public UndoableAction +class Action : public juce::UndoableAction { public: virtual ~Action() {} @@ -22,32 +24,32 @@ class Action : public UndoableAction Action() {} }; -struct AppMessage : public Message +struct AppMessage : public juce::Message { enum ID { }; - inline virtual void createActions (Services&, OwnedArray&) const {} + inline virtual void createActions (Services&, juce::OwnedArray&) const {} }; struct AddMidiDeviceMessage : public AppMessage { - AddMidiDeviceMessage (const MidiDeviceInfo& dev, const bool isInput) + AddMidiDeviceMessage (const juce::MidiDeviceInfo& dev, const bool isInput) : device (dev), inputDevice (isInput) {} - const MidiDeviceInfo device; + const juce::MidiDeviceInfo device; const bool inputDevice; }; /** Send this to add a preset for a node */ struct AddPresetMessage : public AppMessage { - AddPresetMessage (const Node& n, const String& name_ = String()) + AddPresetMessage (const Node& n, const juce::String& name_ = String()) : node (n), name (name_) {} ~AddPresetMessage() noexcept {} const Node node; - const String name; + const juce::String name; }; /** Send this to add a preset for a node */ @@ -64,17 +66,17 @@ struct RemoveNodeMessage : public AppMessage RemoveNodeMessage (const Node& n) : nodeId (n.getNodeId()), node (n) {} RemoveNodeMessage (const NodeArray& n) : nodeId (EL_INVALID_NODE) { nodes.addArray (n); } RemoveNodeMessage (const uint32 _nodeId) : nodeId (_nodeId) {} - const uint32 nodeId; + const uint32_t nodeId; const Node node; NodeArray nodes; - virtual void createActions (Services& app, OwnedArray& actions) const; + virtual void createActions (Services& app, juce::OwnedArray& actions) const; }; /** Send this to add a new connection */ struct AddConnectionMessage : public AppMessage { - AddConnectionMessage (uint32 s, int sc, uint32 d, int dc, const Node& tgt = Node()) + AddConnectionMessage (uint32_t s, int sc, uint32_t d, int dc, const Node& tgt = Node()) : target (tgt) { sourceNode = s; @@ -85,7 +87,7 @@ struct AddConnectionMessage : public AppMessage jassert (useChannels()); } - AddConnectionMessage (uint32 s, uint32 sp, uint32 d, uint32 dp, const Node& tgt = Node()) + AddConnectionMessage (uint32_t s, uint32_t sp, uint32_t d, uint32_t dp, const Node& tgt = Node()) : target (tgt) { sourceNode = s; @@ -96,14 +98,14 @@ struct AddConnectionMessage : public AppMessage jassert (usePorts()); } - uint32 sourceNode, sourcePort, destNode, destPort; + uint32_t sourceNode, sourcePort, destNode, destPort; int sourceChannel, destChannel; const Node target; inline bool useChannels() const { return sourceChannel >= 0 && destChannel >= 0; } inline bool usePorts() const { return ! useChannels(); } - void createActions (Services& app, OwnedArray& actions) const override; + void createActions (Services& app, juce::OwnedArray& actions) const override; }; /** Send this to remove a connection from the graph */ @@ -132,16 +134,16 @@ class RemoveConnectionMessage : public AppMessage jassert (usePorts()); } - uint32 sourceNode, sourcePort, destNode, destPort; + uint32_t sourceNode, sourcePort, destNode, destPort; int sourceChannel, destChannel; const Node target; inline bool useChannels() const { return sourceChannel >= 0 && destChannel >= 0; } inline bool usePorts() const { return ! useChannels(); } - void createActions (Services& app, OwnedArray& actions) const override; + void createActions (Services& app, juce::OwnedArray& actions) const override; }; -class AddNodeMessage : public Message +class AddNodeMessage : public juce::Message { public: AddNodeMessage (const Node& n, const Node& t = Node(), const File& f = File()) @@ -158,17 +160,17 @@ class AddNodeMessage : public Message }; /** Send this when a plugin needs loaded into the graph */ -class LoadPluginMessage : public Message +class LoadPluginMessage : public juce::Message { public: - LoadPluginMessage (const PluginDescription& pluginDescription, const bool pluginVerified) + LoadPluginMessage (const juce::PluginDescription& pluginDescription, const bool pluginVerified) : Message(), description (pluginDescription), verified (pluginVerified) {} - LoadPluginMessage (const PluginDescription& d, const bool v, const float rx, const float ry) + LoadPluginMessage (const juce::PluginDescription& d, const bool v, const float rx, const float ry) : Message(), description (d), relativeX (rx), relativeY (ry), verified (v) {} ~LoadPluginMessage() {} /** Descriptoin of the plugin to load */ - const PluginDescription description; + const juce::PluginDescription description; /** Relative X of the node UI in a graph editor */ const float relativeX = 0.5f; @@ -182,30 +184,30 @@ class LoadPluginMessage : public Message struct AddPluginMessage : public AppMessage { - AddPluginMessage (const Node& g, const PluginDescription& d, const bool v = true) + AddPluginMessage (const Node& g, const juce::PluginDescription& d, const bool v = true) : graph (g), description (d), verified (v) { } const Node graph; - const PluginDescription description; + const juce::PluginDescription description; const bool verified; ConnectionBuilder builder; - void createActions (Services& app, OwnedArray& actions) const override; + void createActions (Services& app, juce::OwnedArray& actions) const override; }; struct ReplaceNodeMessage : public AppMessage { - ReplaceNodeMessage (const Node& n, const PluginDescription& d, const bool v = true) + ReplaceNodeMessage (const Node& n, const juce::PluginDescription& d, const bool v = true) : graph (n.getParentGraph()), node (n), description (d), verified (v) {} const Node graph; const Node node; - const PluginDescription description; + const juce::PluginDescription description; const bool verified; boost::signals2::signal success; }; -class DuplicateNodeMessage : public Message +class DuplicateNodeMessage : public juce::Message { public: DuplicateNodeMessage (const Node& n) @@ -214,7 +216,7 @@ class DuplicateNodeMessage : public Message const Node node; }; -class DisconnectNodeMessage : public Message +class DisconnectNodeMessage : public juce::Message { public: DisconnectNodeMessage (const Node& n, const bool i = true, const bool o = true, const bool a = true, const bool m = true) @@ -234,10 +236,10 @@ struct FinishedLaunchingMessage : public AppMessage struct ChangeBusesLayout : public AppMessage { - ChangeBusesLayout (const Node& n, const AudioProcessor::BusesLayout& l) + ChangeBusesLayout (const Node& n, const juce::AudioProcessor::BusesLayout& l) : node (n), layout (l) {} const Node node; - const AudioProcessor::BusesLayout layout; + const juce::AudioProcessor::BusesLayout layout; std::function onFinished; }; diff --git a/src/module.cpp b/src/module.cpp deleted file mode 100644 index 024bf3edb..000000000 --- a/src/module.cpp +++ /dev/null @@ -1,186 +0,0 @@ -// Copyright 2023 Kushview, LLC -// SPDX-License-Identifier: GPL-3.0-or-later - -#include -#include "scripting.hpp" - -#include "dynlib.h" -#include -#include "module.hpp" - -namespace fs = std::filesystem; - -namespace element { - -Module::Module (const std::string& bp, Context& b, ScriptingEngine& s) - : backend (b), - scripting (s), - m_bundle_path (bp) -{ - manifest = read_module_manifest (bundle_path()); -} - -Module::~Module() -{ - close(); -} - -bool Module::open() -{ - close(); - if (! is_open()) - { - fs::path libfile (m_bundle_path); - libfile /= libfile.filename() - .replace_extension (library_extension()); - if (! fs::exists (libfile)) - return false; - library = element_openlib (libfile.string().c_str()); - - if (library != nullptr) - { - f_descriptor = (elDescriptorFunction) - element_getsym (library, "element_descriptor"); - } - else - { - std::cout << "library couldn't open\n"; - if (auto str = dlerror()) - { - std::cout << "error: " << str << std::endl; - std::free (str); - } - } - - if (f_descriptor) - { - mod = f_descriptor(); - } - else - { - std::cout << "no descriptor function\n"; - } - - if (mod && mod->create) - { - handle = mod->create(); - } - - if (handle && mod->extension) - { - std::vector mids; - // mids.push_back (EL_EXTENSION__Main); - // mids.push_back (EL_EXTENSION__LuaPackages); - // mids.push_back ("el.GraphicsDevice"); - for (auto& s : mids) - { - if (auto data = mod->extension (handle, s.c_str())) - { - elFeature feature; - feature.ID = s.c_str(); - feature.data = (void*) data; - handle_module_extension (feature); - } - } - } - } - - return is_open(); -} - -void Module::handle_module_extension (const elFeature& f) -{ - bool handled = true; -#define use_extensions 0 -#if use_extensions - if (strcmp (f.ID, EL_EXTENSION__LuaPackages) == 0) - { - for (auto reg = (const luaL_Reg*) f.data; reg != nullptr && reg->name != nullptr && reg->func != nullptr; ++reg) - { - scripting.add_package (reg->name, reg->func); - } - } - else if (strcmp (f.ID, EL_EXTENSION__Main) == 0) - { - main = (const elMain*) f.data; - } - else if (strcmp (f.ID, "el.GraphicsDevice") == 0) - { - backend.video->load_device_descriptor ((const evgDescriptor*) f.data); - } - else - { -#endif - // clang-format off - handled = false; - for (const auto& ex : manifest.provides) { - if (ex == f.ID) { - handled = true; - break; - } - } -// clang-format on -#if use_extensions - } -#endif -#undef use_extensions - - if (! handled) - std::clog << "unhandled module feature: " << f.ID << std::endl; -} - -void Module::load (elFeatures features) -{ - if (has_loaded) - return; - - has_loaded = true; - if (handle && mod && mod->load) - { - mod->load (handle, features); - } -} - -void Module::unload() -{ - if (! has_loaded) - return; - - has_loaded = false; - if (handle && mod && mod->unload) - { - mod->unload (handle); - } -} - -FeatureMap Module::public_extensions() const -{ - FeatureMap e; - for (const auto& exp : manifest.provides) - if (auto data = mod->extension (handle, exp.c_str())) - e.insert ({ exp, data }); - return e; -} - -void Module::close() -{ - unload(); - - if (handle != nullptr) - { - if (mod != nullptr && mod->destroy != nullptr) - mod->destroy (handle); - handle = nullptr; - } - - mod = nullptr; - f_descriptor = nullptr; - - if (library != nullptr) - { - element_closelib (library); - library = nullptr; - } -} - -} // namespace element diff --git a/src/module.hpp b/src/module.hpp deleted file mode 100644 index 2d071f877..000000000 --- a/src/module.hpp +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright 2023 Kushview, LLC -// SPDX-License-Identifier: GPL-3.0-or-later - -#pragma once - -#include -#include -#include - -#include "element/element.hpp" -#include "scripting.hpp" -#include -#include "manifest.hpp" -#include "search_path.hpp" - -namespace element { - -using FeatureMap = std::map; - -class Module -{ -public: - Module (const std::string& bundle_path, Context& context, Scripting& s); - ~Module(); - - std::string name() const noexcept { return manifest.name; } - - static const std::string library_extension() - { -#if __APPLE__ - return ".dylib"; -#elif _WIN32 - return ".dll"; -#else - return ".so"; -#endif - } - - constexpr bool is_open() const noexcept - { - return library != nullptr && mod != nullptr && handle != nullptr; - } - - constexpr const void* extension (const std::string& ID) const noexcept - { - return mod && handle && mod->extension ? mod->extension (handle, ID.c_str()) - : nullptr; - } - - bool open(); - - bool loaded() const noexcept { return has_loaded; } - void load (elFeatures features); - void unload(); - - FeatureMap public_extensions() const; - - void close(); - - const std::string& bundle_path() const noexcept { return m_bundle_path; } - -private: - [[maybe_unused]] Context& backend; - [[maybe_unused]] Scripting& scripting; - Manifest manifest; - const std::string m_bundle_path; - void* library = nullptr; - const elDescriptor* mod = nullptr; - elHandle handle; - elDescriptorFunction f_descriptor = nullptr; - bool has_loaded = false; - void handle_module_extension (const elFeature& f); -}; - -class Modules -{ -public: - using ptr_type = std::unique_ptr; - using vector_type = std::vector; - Modules (Context& c) : backend (c) {} - - void add (ptr_type mod) - { - mods.push_back (std::move (mod)); - } - - void add (Module* mod) { add (ptr_type (mod)); } - - auto begin() const noexcept { return mods.begin(); } - auto end() const noexcept { return mods.end(); } - - bool contains (const std::string& bp) const noexcept - { - auto result = std::find_if (begin(), end(), [bp] (const ptr_type& ptr) { - return ptr->name() == bp; - }); - - return result != mods.end(); - } - - int discover() - { - if (discovered.size() > 0) - return (int) discovered.size(); - - for (auto const& entry : searchpath.find_folders (false, "*.element")) - { - Manifest manifest = read_module_manifest (entry.string()); - if (! manifest.name.empty()) - discovered.insert ({ manifest.name, entry.string() }); - } - - return (int) discovered.size(); - } - - void unload_all() - { - for (const auto& mod : mods) - { - mod->unload(); - mod->close(); - } - } - -private: - friend class Context; - [[maybe_unused]] Context& backend; - vector_type mods; - SearchPath searchpath; - std::map discovered; -}; - -} // namespace element diff --git a/src/native_unix.cpp b/src/native_unix.cpp deleted file mode 100644 index 1d4f116f5..000000000 --- a/src/native_unix.cpp +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2023 Kushview, LLC -// SPDX-License-Identifier: GPL-3.0-or-later - -#if ! defined(_WIN32) - -#include -#include - -uint64_t element_time_ns() -{ - struct timespec ts; - clock_gettime (CLOCK_MONOTONIC, &ts); - return ((uint64_t) ts.tv_sec * 1000000000ULL + (uint64_t) ts.tv_nsec); -} - -#endif diff --git a/src/nodes/audioprocessor.hpp b/src/nodes/audioprocessor.hpp index d40e47126..6826ca18b 100644 --- a/src/nodes/audioprocessor.hpp +++ b/src/nodes/audioprocessor.hpp @@ -13,44 +13,44 @@ class AudioProcessorNode : public Processor, public juce::AudioProcessorListener { public: - AudioProcessorNode (uint32 nodeId, AudioProcessor* processor); - AudioProcessorNode (AudioProcessor*); + AudioProcessorNode (uint32_t nodeId, juce::AudioProcessor* processor); + AudioProcessorNode (juce::AudioProcessor*); virtual ~AudioProcessorNode(); /** Returns the processor as an AudioProcessor */ - AudioProcessor* getAudioProcessor() const noexcept override { return proc.get(); } + juce::AudioProcessor* getAudioProcessor() const noexcept override { return proc.get(); } - void setPlayHead (AudioPlayHead* playhead) override + void setPlayHead (juce::AudioPlayHead* playhead) override { Processor::setPlayHead (playhead); if (auto* p = proc.get()) p->setPlayHead (playhead); } - void getState (MemoryBlock&) override; + void getState (juce::MemoryBlock&) override; void setState (const void*, int) override; void prepareToRender (double sampleRate, int maxBufferSize) override; void releaseResources() override; void refreshPorts() override; - void getPluginDescription (PluginDescription& desc) const override; + void getPluginDescription (juce::PluginDescription& desc) const override; bool wantsContext() const noexcept override { return false; } - void audioProcessorChanged (AudioProcessor*, const ChangeDetails&) override; + void audioProcessorChanged (juce::AudioProcessor*, const ChangeDetails&) override; void audioProcessorParameterChanged (juce::AudioProcessor*, int, float) override {} protected: ParameterPtr getParameter (const PortDescription& port) override; private: - std::unique_ptr proc; - Atomic enabled { 1 }; - MemoryBlock pluginState; + std::unique_ptr proc; + juce::Atomic enabled { 1 }; + juce::MemoryBlock pluginState; ParameterArray params; - struct EnablementUpdater : public AsyncUpdater + struct EnablementUpdater : public juce::AsyncUpdater { EnablementUpdater (AudioProcessorNode& n) : node (n) {} ~EnablementUpdater() {} diff --git a/src/nodes/audioprocessornode.cpp b/src/nodes/audioprocessornode.cpp index f2f361ef2..4e1c1df9a 100644 --- a/src/nodes/audioprocessornode.cpp +++ b/src/nodes/audioprocessornode.cpp @@ -8,6 +8,8 @@ #include "scopedflag.hpp" +using namespace juce; + namespace element { //============================================================================= @@ -95,7 +97,7 @@ void AudioProcessorNode::EnablementUpdater::handleAsyncUpdate() AudioProcessorNode::AudioProcessorNode (AudioProcessor* processor) : AudioProcessorNode (0, processor) {} -AudioProcessorNode::AudioProcessorNode (uint32 nodeId, AudioProcessor* processor) +AudioProcessorNode::AudioProcessorNode (uint32_t nodeId, AudioProcessor* processor) : Processor (nodeId), enablement (*this) { diff --git a/src/nodes/genericeditor.cpp b/src/nodes/genericeditor.cpp index 48cc89da9..ee9c62df0 100644 --- a/src/nodes/genericeditor.cpp +++ b/src/nodes/genericeditor.cpp @@ -4,6 +4,8 @@ #include "nodes/genericeditor.hpp" #include +using namespace juce; + namespace element { class BooleanParameterComponent final : public Component, diff --git a/src/nodes/genericeditor.hpp b/src/nodes/genericeditor.hpp index 86abee222..6dc6ea099 100644 --- a/src/nodes/genericeditor.hpp +++ b/src/nodes/genericeditor.hpp @@ -13,7 +13,7 @@ class GenericNodeEditor : public NodeEditor GenericNodeEditor (const Node&); ~GenericNodeEditor() override; void resized() override; - void paint (Graphics&) override; + void paint (juce::Graphics&) override; private: struct Pimpl; diff --git a/src/nodes/midiprogrammap.cpp b/src/nodes/midiprogrammap.cpp index 9b77bb427..196b92ef3 100644 --- a/src/nodes/midiprogrammap.cpp +++ b/src/nodes/midiprogrammap.cpp @@ -1,7 +1,6 @@ // Copyright 2023 Kushview, LLC // SPDX-License-Identifier: GPL-3.0-or-later -#include "ElementApp.h" #include "nodes/midiprogrammap.hpp" #include "engine/trace.hpp" diff --git a/src/nodes/midisetlist.cpp b/src/nodes/midisetlist.cpp index d1af73dd0..b2d8fd3c4 100644 --- a/src/nodes/midisetlist.cpp +++ b/src/nodes/midisetlist.cpp @@ -1,11 +1,12 @@ // Copyright 2024 Kushview, LLC // SPDX-License-Identifier: GPL-3.0-or-later -#include "ElementApp.h" +#include + #include "nodes/midisetlist.hpp" #include "engine/trace.hpp" -#include +using namespace juce; namespace element { diff --git a/src/nodes/midisetlist.hpp b/src/nodes/midisetlist.hpp index cf9337056..4d336f6ae 100644 --- a/src/nodes/midisetlist.hpp +++ b/src/nodes/midisetlist.hpp @@ -3,23 +3,24 @@ #pragma once -#include "nodes/midifilter.hpp" #include #include #include +#include "nodes/midifilter.hpp" + namespace element { class Context; class MidiSetListProcessor : public MidiFilterNode, - public AsyncUpdater, - public ChangeBroadcaster + public juce::AsyncUpdater, + public juce::ChangeBroadcaster { public: struct ProgramEntry { - String name; + juce::String name; int in; int out; double tempo { 0.0 }; @@ -28,7 +29,7 @@ class MidiSetListProcessor : public MidiFilterNode, MidiSetListProcessor (Context&); virtual ~MidiSetListProcessor(); - void getPluginDescription (PluginDescription& desc) const override + void getPluginDescription (juce::PluginDescription& desc) const override { desc.fileOrIdentifier = EL_NODE_ID_MIDI_SET_LIST; desc.name = getName(); @@ -52,10 +53,10 @@ class MidiSetListProcessor : public MidiFilterNode, void sendProgramChange (int program, int channel); int getNumProgramEntries() const; - void addProgramEntry (const String& name, int programIn, int programOut = -1); + void addProgramEntry (const juce::String& name, int programIn, int programOut = -1); void removeProgramEntry (int index); void editProgramEntry (int index, - const String& name, + const juce::String& name, int inProgram, int outProgram, double tempo); @@ -66,33 +67,33 @@ class MidiSetListProcessor : public MidiFilterNode, inline void setSize (int w, int h) { - width = jmax (w, (int) 1); - height = jmax (h, (int) 1); + width = juce::jmax (w, (int) 1); + height = juce::jmax (h, (int) 1); } inline float getFontSize() const { return fontSize; } inline void setFontSize (float newSize) { - fontSize = jlimit (9.f, 72.f, newSize); + fontSize = juce::jlimit (9.f, 72.f, newSize); } inline int getLastProgram() const { - ScopedLock sl (lock); + juce::ScopedLock sl (lock); return lastProgram; } void setState (const void* data, int size) override { - const auto tree = ValueTree::readFromGZIPData (data, (size_t) size); + const auto tree = juce::ValueTree::readFromGZIPData (data, (size_t) size); if (! tree.isValid()) return; clear(); - fontSize = jlimit (9.f, 72.f, (float) tree.getProperty ("fontSize", 15.f)); - width = jmax (10, (int) tree.getProperty ("width", 360)); - height = jmax (10, (int) tree.getProperty ("height", 540)); + fontSize = juce::jlimit (9.f, 72.f, (float) tree.getProperty ("fontSize", 15.f)); + width = juce::jmax (10, (int) tree.getProperty ("width", 360)); + height = juce::jmax (10, (int) tree.getProperty ("height", 540)); for (int i = 0; i < tree.getNumChildren(); ++i) { @@ -105,7 +106,7 @@ class MidiSetListProcessor : public MidiFilterNode, } { - ScopedLock sl (lock); + juce::ScopedLock sl (lock); for (const auto* const entry : entries) programMap[entry->in] = entry->out; } @@ -113,16 +114,16 @@ class MidiSetListProcessor : public MidiFilterNode, sendChangeMessage(); } - void getState (MemoryBlock& block) override + void getState (juce::MemoryBlock& block) override { - ValueTree tree ("state"); + juce::ValueTree tree ("state"); tree.setProperty ("fontSize", fontSize, nullptr) .setProperty ("width", width, nullptr) .setProperty ("height", height, nullptr); for (const auto* const entry : entries) { - ValueTree e ("entry"); + juce::ValueTree e ("entry"); e.setProperty ("name", entry->name, nullptr) .setProperty ("in", entry->in, nullptr) .setProperty ("out", entry->out, nullptr) @@ -130,10 +131,10 @@ class MidiSetListProcessor : public MidiFilterNode, tree.appendChild (e, nullptr); } - MemoryOutputStream stream (block, false); + juce::MemoryOutputStream stream (block, false); { - GZIPCompressorOutputStream gzip (stream); + juce::GZIPCompressorOutputStream gzip (stream); tree.writeToStream (gzip); } } @@ -143,15 +144,15 @@ class MidiSetListProcessor : public MidiFilterNode, protected: Context& _context; - CriticalSection lock; - OwnedArray entries; + juce::CriticalSection lock; + juce::OwnedArray entries; int programMap[128]; bool assertedLowChannels = false; bool createdPorts = false; - MidiBuffer* buffers[16]; - MidiBuffer tempMidi; - MidiBuffer toSendMidi; + juce::MidiBuffer* buffers[16]; + juce::MidiBuffer tempMidi; + juce::MidiBuffer toSendMidi; int width = 360; int height = 540; diff --git a/src/nodes/scriptnode.cpp b/src/nodes/scriptnode.cpp index a1f63c7b5..42bdae5d7 100644 --- a/src/nodes/scriptnode.cpp +++ b/src/nodes/scriptnode.cpp @@ -6,8 +6,6 @@ #include #include -#include "ElementApp.h" - #include "luascripts.hpp" #include "sol/sol.hpp" diff --git a/src/plugineditor.cpp b/src/plugineditor.cpp index e69ea2634..bf8735f32 100644 --- a/src/plugineditor.cpp +++ b/src/plugineditor.cpp @@ -11,7 +11,6 @@ #include "plugineditor.hpp" #include "pluginprocessor.hpp" -#include "ElementApp.h" #define EL_PLUGIN_MIN_WIDTH 546 #define EL_PLUGIN_MIN_HEIGHT 266 diff --git a/src/pluginprocessor.hpp b/src/pluginprocessor.hpp index 05f51e016..1528f6a69 100644 --- a/src/pluginprocessor.hpp +++ b/src/pluginprocessor.hpp @@ -12,17 +12,15 @@ namespace element { -using namespace juce; - //============================================================================= -class PerformanceParameter : public HostedAudioProcessorParameter, +class PerformanceParameter : public juce::HostedAudioProcessorParameter, public element::Parameter::Listener { public: std::function onCleared; explicit PerformanceParameter (int paramIdx) - : HostedAudioProcessorParameter (1), + : juce::HostedAudioProcessorParameter (1), index (paramIdx) { clearNode(); @@ -35,9 +33,9 @@ class PerformanceParameter : public HostedAudioProcessorParameter, bool haveNode() const { return node != nullptr; } - String getBoundParameterName() const + juce::String getBoundParameterName() const { - SpinLock::ScopedLockType sl (lock); + juce::SpinLock::ScopedLockType sl (lock); return parameter != nullptr ? parameter->getName (100) : String(); } @@ -78,7 +76,7 @@ class PerformanceParameter : public HostedAudioProcessorParameter, ProcessorPtr newNodeObj = model.getObject(); { - SpinLock::ScopedLockType sl (lock); + juce::SpinLock::ScopedLockType sl (lock); parameterIdx = newParam; node = newNodeObj; processor = (node != nullptr) ? node->getAudioProcessor() : nullptr; @@ -126,14 +124,14 @@ class PerformanceParameter : public HostedAudioProcessorParameter, float getValue() const override { - SpinLock::ScopedLockType sl (lock); + juce::SpinLock::ScopedLockType sl (lock); return (parameter != nullptr) ? parameter->getValue() : value.get(); } void setValue (float newValue) override { value.set (newValue); - SpinLock::ScopedLockType sl (lock); + juce::SpinLock::ScopedLockType sl (lock); if (parameter != nullptr) { @@ -146,7 +144,7 @@ class PerformanceParameter : public HostedAudioProcessorParameter, float getDefaultValue() const override { - SpinLock::ScopedLockType sl (lock); + juce::SpinLock::ScopedLockType sl (lock); if (parameter != nullptr) return parameter->getDefaultValue(); @@ -166,25 +164,25 @@ class PerformanceParameter : public HostedAudioProcessorParameter, return 0.f; } - String getParameterID() const override + juce::String getParameterID() const override { return getName (32).toLowerCase().replace (" ", "-"); } - String getName (int maximumStringLength) const override + juce::String getName (int maximumStringLength) const override { String name ("Parameter "); name << int (index + 1); return name.substring (0, maximumStringLength); } - String getLabel() const override + juce::String getLabel() const override { return parameter != nullptr ? parameter->getLabel() : String(); } /** Should parse a string and return the appropriate value for it. */ - float getValueForText (const String& text) const override + float getValueForText (const juce::String& text) const override { return parameter != nullptr ? parameter->getValueForText (text) : jlimit (0.f, 1.f, text.getFloatValue()); @@ -204,7 +202,7 @@ class PerformanceParameter : public HostedAudioProcessorParameter, break; } - return AudioProcessorParameter::getNumSteps(); + return juce::AudioProcessorParameter::getNumSteps(); } bool isDiscrete() const override @@ -236,24 +234,24 @@ class PerformanceParameter : public HostedAudioProcessorParameter, : AudioProcessorParameter::isMetaParameter(); } - AudioProcessorParameter::Category getCategory() const override + juce::AudioProcessorParameter::Category getCategory() const override { return (parameter != nullptr) - ? static_cast (parameter->getCategory()) - : AudioProcessorParameter::getCategory(); + ? static_cast (parameter->getCategory()) + : juce::AudioProcessorParameter::getCategory(); } - String getText (float value, int length) const override + juce::String getText (float value, int length) const override { return (parameter != nullptr) ? parameter->getText (value, length) - : AudioProcessorParameter::getText (value, length); + : juce::AudioProcessorParameter::getText (value, length); } bool isOrientationInverted() const override { return (parameter != nullptr) ? parameter->isOrientationInverted() - : AudioProcessorParameter::isOrientationInverted(); + : juce::AudioProcessorParameter::isOrientationInverted(); } //========================================================================= @@ -318,17 +316,17 @@ class PerformanceParameter : public HostedAudioProcessorParameter, Node getNode() const { return model; } int getBoundParameter() const { - SpinLock::ScopedLockType sl (lock); + juce::SpinLock::ScopedLockType sl (lock); return parameterIdx; } private: - SpinLock lock; + juce::SpinLock lock; const int index; - Atomic value { 0.f }; + juce::Atomic value { 0.f }; Node model; ProcessorPtr node; - AudioProcessor* processor = nullptr; + juce::AudioProcessor* processor = nullptr; element::ParameterPtr parameter = nullptr; int parameterIdx = -1; bool special = false; @@ -336,8 +334,8 @@ class PerformanceParameter : public HostedAudioProcessorParameter, SignalConnection removedConnection; }; -class PluginProcessor : public AudioProcessor, - private AsyncUpdater +class PluginProcessor : public juce::AudioProcessor, + private juce::AsyncUpdater { public: enum Variant diff --git a/src/search_path.hpp b/src/search_path.hpp deleted file mode 100644 index 4e7345fda..000000000 --- a/src/search_path.hpp +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright 2023 Kushview, LLC -// SPDX-License-Identifier: GPL-3.0-or-later - -#pragma once - -#include -#include - -#include - -namespace element { - -extern std::string wildcard_to_regex (const std::string& wildcard); - -class SearchPath -{ -public: - SearchPath() = default; - ~SearchPath() = default; - - SearchPath (const SearchPath& o) { operator= (o); } - SearchPath (SearchPath&& o) { operator= (o); } - - SearchPath& operator= (const SearchPath& o) - { - std::copy (o.paths.begin(), o.paths.end(), this->paths.begin()); - return *this; - } - - SearchPath& operator= (SearchPath&& o) - { - this->paths = std::move (o.paths); - return *this; - } - - template - void add (Tx&& path) - { - paths.push_back (path); - paths.back().make_preferred(); - } - - void clear() noexcept - { - paths.clear(); - } - - std::vector find_folders (bool recursive, const std::string& wildcard = "*") const - { - auto regex = wildcard.size() > 0 && wildcard != "*" - ? wildcard_to_regex (wildcard) - : ""; - return recursive ? std::move (find_folders_regex (regex)) - : std::move (find_folders_regex (regex)); - } - - auto begin() const noexcept { return paths.begin(); } - auto end() const noexcept { return paths.end(); } - -private: - std::vector paths; - - template - std::vector find_folders_regex (const std::string& pattern) const - { - namespace fs = std::filesystem; - std::vector results; - std::function match; - - try - { - std::regex reg (pattern); - if (pattern == "*" || pattern.empty()) - match = [] (const std::filesystem::directory_entry&) -> bool { return true; }; - else - match = [=, ®] (const std::filesystem::directory_entry& entry) -> bool { - return std::regex_match (entry.path().filename().string(), reg); - }; - - for (const auto& dir : paths) - { - std::filesystem::path path (dir); - if (std::filesystem::exists (path) && std::filesystem::is_directory (path)) - { - for (auto const& entry : Iter (path)) - { - if (std::filesystem::is_directory (entry) && match (entry)) - results.push_back (entry.path()); - } - } - } - } catch (const std::regex_error& e) - { - // noop - } - - return results; - } -}; - -} // namespace element diff --git a/src/services/engineservice.cpp b/src/services/engineservice.cpp index a7991c709..f1af3ffd3 100644 --- a/src/services/engineservice.cpp +++ b/src/services/engineservice.cpp @@ -1,8 +1,6 @@ // Copyright 2023 Kushview, LLC // SPDX-License-Identifier: GPL-3.0-or-later -#include "ElementApp.h" - #include #include #include @@ -17,6 +15,8 @@ #include #include +using namespace juce; + namespace element { namespace detail { diff --git a/src/strings.cpp b/src/strings.cpp deleted file mode 100644 index 21504e368..000000000 --- a/src/strings.cpp +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2023 Kushview, LLC -// SPDX-License-Identifier: GPL-3.0-or-later - -#include - -namespace element { -static void escape_regex (std::string& input) -{ - boost::replace_all (input, "\\", "\\\\"); - boost::replace_all (input, "^", "\\^"); - boost::replace_all (input, ".", "\\."); - boost::replace_all (input, "$", "\\$"); - boost::replace_all (input, "|", "\\|"); - boost::replace_all (input, "(", "\\("); - boost::replace_all (input, ")", "\\)"); - boost::replace_all (input, "{", "\\{"); - boost::replace_all (input, "{", "\\}"); - boost::replace_all (input, "[", "\\["); - boost::replace_all (input, "]", "\\]"); - boost::replace_all (input, "*", "\\*"); - boost::replace_all (input, "+", "\\+"); - boost::replace_all (input, "?", "\\?"); - boost::replace_all (input, "/", "\\/"); -} - -static void transform_wildcard (std::string& input) -{ - boost::replace_all (input, "\\?", "."); - boost::replace_all (input, "\\*", ".*"); -} - -std::string wildcard_to_regex (const std::string& wildcard) -{ - auto input = wildcard; - escape_regex (input); - transform_wildcard (input); - return input; -} - -} // namespace element \ No newline at end of file diff --git a/src/ui/grapheditorcomponent.cpp b/src/ui/grapheditorcomponent.cpp index c0480fb1b..38755b872 100644 --- a/src/ui/grapheditorcomponent.cpp +++ b/src/ui/grapheditorcomponent.cpp @@ -7,8 +7,6 @@ #include #include -#include "ElementApp.h" - #include "engine/graphmanager.hpp" #include "nodes/baseprocessor.hpp" #include "nodes/audioprocessor.hpp" diff --git a/src/ui/horizontallistbox.cpp b/src/ui/horizontallistbox.cpp index 023e70bec..357614716 100644 --- a/src/ui/horizontallistbox.cpp +++ b/src/ui/horizontallistbox.cpp @@ -3,6 +3,8 @@ #include "ui/horizontallistbox.hpp" +using namespace juce; + namespace element { class HorizontalListBox::RowComponent : public Component, diff --git a/src/ui/horizontallistbox.hpp b/src/ui/horizontallistbox.hpp index bcdf47bdd..1eec9ec5e 100644 --- a/src/ui/horizontallistbox.hpp +++ b/src/ui/horizontallistbox.hpp @@ -3,8 +3,7 @@ #pragma once -#include -#include "ElementApp.h" // FIXME +#include namespace element { /** @@ -17,8 +16,8 @@ namespace element { @see juce::ComboBox, juce::TableListBox */ -class HorizontalListBox : public Component, - public SettableTooltipClient +class HorizontalListBox : public juce::Component, + public juce::SettableTooltipClient { public: /** Creates a ListBox. @@ -26,17 +25,17 @@ class HorizontalListBox : public Component, The model pointer passed-in can be null, in which case you can set it later with setModel(). */ - HorizontalListBox (const String& componentName = String(), - ListBoxModel* model = nullptr); + HorizontalListBox (const juce::String& componentName = juce::String(), + juce::ListBoxModel* model = nullptr); /** Destructor. */ ~HorizontalListBox(); /** Changes the current data model to display. */ - void setModel (ListBoxModel* newModel); + void setModel (juce::ListBoxModel* newModel); /** Returns the current list model. */ - ListBoxModel* getModel() const noexcept { return model; } + juce::ListBoxModel* getModel() const noexcept { return model; } /** Causes the list to refresh its content. @@ -121,7 +120,7 @@ class HorizontalListBox : public Component, /** Returns a sparse set indicating the rows that are currently selected. @see setSelectedRows */ - SparseSet getSelectedRows() const; + juce::SparseSet getSelectedRows() const; /** Sets the rows that should be selected, based on an explicit set of ranges. @@ -130,8 +129,8 @@ class HorizontalListBox : public Component, @see getSelectedRows */ - void setSelectedRows (const SparseSet& setOfRowsToBeSelected, - NotificationType sendNotificationEventToModel = sendNotification); + void setSelectedRows (const juce::SparseSet& setOfRowsToBeSelected, + juce::NotificationType sendNotificationEventToModel = juce::sendNotification); /** Checks whether a row is selected. */ @@ -177,7 +176,7 @@ class HorizontalListBox : public Component, @see selectRow */ void selectRowsBasedOnModifierKeys (int rowThatWasClickedOn, - ModifierKeys modifiers, + juce::ModifierKeys modifiers, bool isMouseUpEvent); /** Scrolls the list to a particular position. @@ -208,10 +207,10 @@ class HorizontalListBox : public Component, void setScrollBarsShown (bool vertical, bool horizontal); /** Returns a pointer to the vertical scrollbar. */ - ScrollBar* getVerticalScrollBar() const noexcept; + juce::ScrollBar* getVerticalScrollBar() const noexcept; /** Returns a pointer to the horizontal scrollbar. */ - ScrollBar* getHorizontalScrollBar() const noexcept; + juce::ScrollBar* getHorizontalScrollBar() const noexcept; /** Finds the row index that contains a given x,y position. The position is relative to the ListBox's top-left. @@ -241,8 +240,8 @@ class HorizontalListBox : public Component, This may be off-screen, and the range of the row number that is passed-in is not checked to see if it's a valid row. */ - Rectangle getRowPosition (int rowNumber, - bool relativeToComponentTopLeft) const noexcept; + juce::Rectangle getRowPosition (int rowNumber, + bool relativeToComponentTopLeft) const noexcept; /** Finds the row component for a given row in the list. @@ -361,52 +360,52 @@ class HorizontalListBox : public Component, @see Component::createComponentSnapshot */ - virtual Image createSnapshotOfSelectedRows (int& x, int& y); + virtual juce::Image createSnapshotOfSelectedRows (int& x, int& y); /** Returns the viewport that this ListBox uses. You may need to use this to change parameters such as whether scrollbars are shown, etc. */ - Viewport* getViewport() const noexcept; + juce::Viewport* getViewport() const noexcept; /** @internal */ - bool keyPressed (const KeyPress&) override; + bool keyPressed (const juce::KeyPress&) override; /** @internal */ bool keyStateChanged (bool isKeyDown) override; /** @internal */ - void paint (Graphics&) override; + void paint (juce::Graphics&) override; /** @internal */ - void paintOverChildren (Graphics&) override; + void paintOverChildren (juce::Graphics&) override; /** @internal */ void resized() override; /** @internal */ void visibilityChanged() override; /** @internal */ - void mouseWheelMove (const MouseEvent&, const MouseWheelDetails&) override; + void mouseWheelMove (const juce::MouseEvent&, const juce::MouseWheelDetails&) override; /** @internal */ - void mouseUp (const MouseEvent&) override; + void mouseUp (const juce::MouseEvent&) override; /** @internal */ void colourChanged() override; /** @internal */ void parentHierarchyChanged() override; /** @internal */ - void startDragAndDrop (const MouseEvent&, const var& dragDescription, bool allowDraggingToOtherWindows); + void startDragAndDrop (const juce::MouseEvent&, const juce::var& dragDescription, bool allowDraggingToOtherWindows); private: JUCE_PUBLIC_IN_DLL_BUILD (class ListViewport) JUCE_PUBLIC_IN_DLL_BUILD (class RowComponent) friend class ListViewport; friend class TableListBox; - ListBoxModel* model; + juce::ListBoxModel* model; std::unique_ptr viewport; - std::unique_ptr headerComponent; + std::unique_ptr headerComponent; std::unique_ptr mouseMoveSelector; int totalItems, rowHeight, minimumRowWidth; int outlineThickness; int lastRowSelected; bool multipleSelection, alwaysFlipSelection, hasDoneInitialUpdate; - SparseSet selected; + juce::SparseSet selected; void selectRowInternal (int rowNumber, bool dontScrollToShowThisRow, bool deselectOthersFirst, bool isMouseClick); diff --git a/src/ui/midiblinker.cpp b/src/ui/midiblinker.cpp index 3243cdc6e..6defc72b1 100644 --- a/src/ui/midiblinker.cpp +++ b/src/ui/midiblinker.cpp @@ -4,6 +4,8 @@ #include "ui/midiblinker.hpp" #include +using namespace juce; + namespace element { MidiBlinker::MidiBlinker() diff --git a/src/ui/midiblinker.hpp b/src/ui/midiblinker.hpp index 79b98b0b1..8b9f6012a 100644 --- a/src/ui/midiblinker.hpp +++ b/src/ui/midiblinker.hpp @@ -4,13 +4,12 @@ #pragma once #include -using namespace juce; // FIXME; namespace element { -class MidiBlinker : public Component, - public SettableTooltipClient, - private Timer +class MidiBlinker : public juce::Component, + public juce::SettableTooltipClient, + private juce::Timer { public: enum ColourIds @@ -27,7 +26,7 @@ class MidiBlinker : public Component, void setInputOutputVisibility (bool in, bool out); - void paint (Graphics&) override; + void paint (juce::Graphics&) override; void resized() override; private: @@ -36,7 +35,7 @@ class MidiBlinker : public Component, bool haveOutput = false; bool showInput = true; bool showOutput = true; - friend class Timer; + friend class juce::Timer; void timerCallback() override; }; diff --git a/src/ui/nodeeditorview.cpp b/src/ui/nodeeditorview.cpp index 1203ac4b8..2c7110192 100644 --- a/src/ui/nodeeditorview.cpp +++ b/src/ui/nodeeditorview.cpp @@ -7,8 +7,6 @@ #include #include -#include "ElementApp.h" - #include "engine/graphnode.hpp" #include "nodes/ionodeeditor.hpp" #include "nodes/audioroutereditor.hpp" diff --git a/src/ui/resizelistener.hpp b/src/ui/resizelistener.hpp index 2f037c5a6..d6acfb0bd 100644 --- a/src/ui/resizelistener.hpp +++ b/src/ui/resizelistener.hpp @@ -29,7 +29,7 @@ struct ViewSizeListener : private juce::ComponentMovementWatcher { if (wasResized) { - const auto physicalSize = Desktop::getInstance().getDisplays().logicalToPhysical (getComponent()->localAreaToGlobal (getComponent()->getLocalBounds())); + const auto physicalSize = juce::Desktop::getInstance().getDisplays().logicalToPhysical (getComponent()->localAreaToGlobal (getComponent()->getLocalBounds())); const auto width = physicalSize.getWidth(); const auto height = physicalSize.getHeight(); diff --git a/src/ui/windowmanager.hpp b/src/ui/windowmanager.hpp index 0c9bf4b31..7b5a8ccfd 100644 --- a/src/ui/windowmanager.hpp +++ b/src/ui/windowmanager.hpp @@ -6,7 +6,6 @@ #include #include -#include "ElementApp.h" #include "ui/window.hpp" #include "ui/pluginwindow.hpp"