id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
754,240
KiwiModel_LessEqualTilde.cpp
Musicoll_Kiwi/Modules/KiwiModel/KiwiModel_Objects/KiwiModel_LessEqualTilde.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiModel/KiwiModel_Objects/KiwiModel_LessEqualTilde.h> #include <KiwiModel/KiwiModel_Factory.h> namespace kiwi { namespace model { // ================================================================================ // // OBJECT <=~ // // ================================================================================ // void LessEqualTilde::declare() { if (!DataModel::has<model::OperatorTilde>()) { OperatorTilde::declare(); } std::unique_ptr<ObjectClass> lessequaltilde_class(new ObjectClass("<=~", &LessEqualTilde::create)); flip::Class<LessEqualTilde> & lessequaltilde_model = DataModel::declare<LessEqualTilde>() .name(lessequaltilde_class->getModelName().c_str()) .inherit<OperatorTilde>(); Factory::add<LessEqualTilde>(std::move(lessequaltilde_class), lessequaltilde_model); } std::unique_ptr<Object> LessEqualTilde::create(std::vector<tool::Atom> const& args) { return std::make_unique<LessEqualTilde>(args); } LessEqualTilde::LessEqualTilde(std::vector<tool::Atom> const& args): OperatorTilde(args) { } }}
2,262
C++
.cpp
41
46.195122
115
0.516473
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,241
KiwiModel_Pow.cpp
Musicoll_Kiwi/Modules/KiwiModel/KiwiModel_Objects/KiwiModel_Pow.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiModel/KiwiModel_Objects/KiwiModel_Pow.h> #include <KiwiModel/KiwiModel_Factory.h> namespace kiwi { namespace model { // ================================================================================ // // OBJECT POW // // ================================================================================ // void Pow::declare() { if (!DataModel::has<model::Operator>()) { Operator::declare(); } std::unique_ptr<ObjectClass> pow_class(new ObjectClass("pow", &Pow::create)); flip::Class<Pow> & pow_model = DataModel::declare<Pow>() .name(pow_class->getModelName().c_str()) .inherit<Operator>(); Factory::add<Pow>(std::move(pow_class), pow_model); } std::unique_ptr<Object> Pow::create(std::vector<tool::Atom> const& args) { return std::make_unique<Pow>(args); } Pow::Pow(std::vector<tool::Atom> const& args): Operator(args) { } }}
2,111
C++
.cpp
42
40.642857
90
0.466301
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,242
KiwiModel_Minus.cpp
Musicoll_Kiwi/Modules/KiwiModel/KiwiModel_Objects/KiwiModel_Minus.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiModel/KiwiModel_Objects/KiwiModel_Minus.h> #include <KiwiModel/KiwiModel_Factory.h> namespace kiwi { namespace model { // ================================================================================ // // OBJECT MINUS // // ================================================================================ // void Minus::declare() { if (!DataModel::has<model::Operator>()) { Operator::declare(); } std::unique_ptr<ObjectClass> minus_class(new ObjectClass("-", &Minus::create)); flip::Class<Minus> & minus_model = DataModel::declare<Minus>() .name(minus_class->getModelName().c_str()) .inherit<Operator>(); Factory::add<Minus>(std::move(minus_class), minus_model); } std::unique_ptr<Object> Minus::create(std::vector<tool::Atom> const& args) { return std::make_unique<Minus>(args); } Minus::Minus(std::vector<tool::Atom> const& args): Operator(args) { } }}
2,127
C++
.cpp
42
41.309524
90
0.476969
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,243
KiwiModel_NumberTilde.cpp
Musicoll_Kiwi/Modules/KiwiModel/KiwiModel_Objects/KiwiModel_NumberTilde.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiModel/KiwiModel_Factory.h> #include <KiwiModel/KiwiModel_ObjectClass.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_NumberTilde.h> namespace kiwi { namespace model { // ================================================================================ // // OBJECT NUMBER TILDE // // ================================================================================ // void NumberTilde::declare() { std::unique_ptr<ObjectClass> numbertilde_class(new ObjectClass("number~", &NumberTilde::create)); // parameters std::unique_ptr<ParameterClass> param_value(new ParameterClass(tool::Parameter::Type::Float)); numbertilde_class->addParameter("value", std::move(param_value)); // flags numbertilde_class->setFlag(ObjectClass::Flag::DefinedSize); // data model flip::Class<NumberTilde> & numbertilde_model = DataModel::declare<NumberTilde>() .name(numbertilde_class->getModelName().c_str()) .inherit<Object>(); Factory::add<NumberTilde>(std::move(numbertilde_class), numbertilde_model); } std::unique_ptr<Object> NumberTilde::create(std::vector<tool::Atom> const& args) { return std::make_unique<NumberTilde>(args); } NumberTilde::NumberTilde(std::vector<tool::Atom> const& args): Object() { if (!args.empty()) { throw Error("number tilde doesn't take any arguments"); } setWidth(50.); setHeight(20.); pushInlet({PinType::IType::Signal}); pushOutlet(PinType::IType::Control); } NumberTilde::NumberTilde(flip::Default& d): Object(d) { } std::string NumberTilde::getIODescription(bool is_inlet, size_t index) const { if (is_inlet && index == 0) { return "Input signal"; } else if(!is_inlet && index == 0) { return "Ouputs input signal value every interval"; } else { return ""; } } }}
3,225
C++
.cpp
72
34.958333
103
0.520854
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,244
KiwiModel_DifferentTilde.cpp
Musicoll_Kiwi/Modules/KiwiModel/KiwiModel_Objects/KiwiModel_DifferentTilde.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiModel/KiwiModel_Objects/KiwiModel_DifferentTilde.h> #include <KiwiModel/KiwiModel_Factory.h> namespace kiwi { namespace model { // ================================================================================ // // OBJECT !=~ // // ================================================================================ // void DifferentTilde::declare() { if (!DataModel::has<model::OperatorTilde>()) { OperatorTilde::declare(); } std::unique_ptr<ObjectClass> differenttilde_class(new ObjectClass("!=~", &DifferentTilde::create)); flip::Class<DifferentTilde> & differenttilde_model = DataModel::declare<DifferentTilde>() .name(differenttilde_class->getModelName().c_str()) .inherit<OperatorTilde>(); Factory::add<DifferentTilde>(std::move(differenttilde_class), differenttilde_model); } std::unique_ptr<Object> DifferentTilde::create(std::vector<tool::Atom> const& args) { return std::make_unique<DifferentTilde>(args); } DifferentTilde::DifferentTilde(std::vector<tool::Atom> const& args): OperatorTilde(args) { } }}
2,261
C++
.cpp
41
46.170732
115
0.516713
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,245
KiwiModel_Swith.cpp
Musicoll_Kiwi/Modules/KiwiModel/KiwiModel_Objects/KiwiModel_Swith.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <string> #include <KiwiModel/KiwiModel_Factory.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Switch.h> namespace kiwi { namespace model { // ================================================================================ // // SWITCH // // ================================================================================ // void Switch::declare() { std::unique_ptr<ObjectClass> switch_class(new ObjectClass("switch", &Switch::create)); flip::Class<Switch> & switch_model = DataModel::declare<Switch>() .name(switch_class->getModelName().c_str()) .inherit<Object>(); Factory::add<Switch>(std::move(switch_class), switch_model); } std::unique_ptr<Object> Switch::create(std::vector<tool::Atom> const& args) { return std::make_unique<Switch>(args); } Switch::Switch(std::vector<tool::Atom> const& args) { if (args.size() <= 0) throw Error("switch number of inputs must be specified"); if (args.size() > 2) throw Error("switch takes at most 2 arguments"); if (args.size() > 1 && !args[1].isNumber()) throw Error("switch 2nd argument must be a number"); if (args.size() > 0) { if (!args[0].isInt()) { throw Error("switch 1rst argument must be an integer"); } else if(args[0].getInt() < 0) { throw Error("switch 1rst argument must be greater than 0"); } } pushInlet({PinType::IType::Control}); pushOutlet(PinType::IType::Control); if (args.empty()) { pushInlet({PinType::IType::Control}); } else { for(int inlet = 0; inlet < args[0].getInt(); ++inlet) { pushInlet({PinType::IType::Control}); } } } std::string Switch::getIODescription(bool is_inlet, size_t index) const { std::string description = ""; if (is_inlet) { if (index == 0) { description = "Integer opens inlet. 0 closes all inlets"; } else if(index < getNumberOfInlets()) { description = "Input " + std::to_string(index) + " sends message when inlet is opened"; } } else { description = "Sends message received in opened inlet"; } return description; } }}
3,667
C++
.cpp
87
31.597701
103
0.490407
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,246
KiwiModel_SwitchTilde.cpp
Musicoll_Kiwi/Modules/KiwiModel/KiwiModel_Objects/KiwiModel_SwitchTilde.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <string> #include <KiwiModel/KiwiModel_Factory.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_SwitchTilde.h> namespace kiwi { namespace model { // ================================================================================ // // SWITCH~ // // ================================================================================ // void SwitchTilde::declare() { std::unique_ptr<ObjectClass> switchtilde_class(new ObjectClass("switch~", &SwitchTilde::create)); flip::Class<SwitchTilde> & switchtilde_model = DataModel::declare<SwitchTilde>() .name(switchtilde_class->getModelName().c_str()) .inherit<Object>(); Factory::add<SwitchTilde>(std::move(switchtilde_class), switchtilde_model); } std::unique_ptr<Object> SwitchTilde::create(std::vector<tool::Atom> const& args) { return std::make_unique<SwitchTilde>(args); } SwitchTilde::SwitchTilde(std::vector<tool::Atom> const& args) { if (args.size() <= 0) throw Error("switch~ number of inputs must be specified"); if (args.size() > 2) throw Error("switch~ takes at most 2 arguments"); if (args.size() > 1 && !args[1].isNumber()) throw Error("switch~ 2nd argument must be a number"); if (args.size() > 0) { if (!args[0].isInt()) { throw Error("switch~ 1rst argument must be an integer"); } else if(args[0].getInt() < 0) { throw Error("switch~ 1rst argument must be greater than 0"); } } pushInlet({PinType::IType::Control, PinType::IType::Signal}); pushOutlet(PinType::IType::Signal); for(int inlet = 0; inlet < args[0].getInt(); ++inlet) { pushInlet({PinType::IType::Signal}); } } std::string SwitchTilde::getIODescription(bool is_inlet, size_t index) const { std::string description = ""; if (is_inlet) { if (index == 0) { description = "Int Open/Close input"; } else { description = "Input " + std::to_string(index) + " sends signal if opened"; } } else { if (index == 0) { description = "Output sends signal from opened input"; } } return description; } }}
3,634
C++
.cpp
83
33.096386
105
0.496199
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,247
KiwiEngine_Link.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Link.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include "KiwiEngine_Link.h" namespace kiwi { namespace engine { // ================================================================================ // // LINK // // ================================================================================ // Link::Link(Object & receiver, size_t index) : m_receiver(receiver), m_index(index) { ; } Object & Link::getReceiver() const { return m_receiver; } size_t Link::getReceiverIndex() const { return m_index; } size_t& Link::useStackCount() { return m_stack_count; } } }
1,733
C++
.cpp
42
32.97619
95
0.429095
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,248
KiwiEngine_Console.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Console.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include "KiwiEngine_Console.h" namespace kiwi { namespace engine { // ================================================================================ // // CONSOLE // // ================================================================================ // void Console::post(Message const& mess) const { m_listeners.call(&Listener::newConsoleMessage, mess); } void Console::addListener(Listener& listener) { m_listeners.add(listener); } void Console::removeListener(Listener& listener) { m_listeners.remove(listener); } } }
1,631
C++
.cpp
36
38.805556
94
0.469112
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,249
KiwiEngine_Object.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Object.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include "KiwiEngine_Object.h" #include "KiwiEngine_Link.h" #include "KiwiEngine_Patcher.h" #include <KiwiModel/KiwiModel_DocumentManager.h> #include <KiwiModel/KiwiModel_Object.h> namespace kiwi { namespace engine { // ================================================================================ // // OBJECT // // ================================================================================ // Object::Object(model::Object const& model, Patcher& patcher) noexcept : m_patcher(patcher) , m_ref(model.ref()) , m_inlets(model.getNumberOfInlets()) , m_outlets(model.getNumberOfOutlets()) , m_master(this, [](engine::Object*){}) { getObjectModel().addListener(*this); } Object::~Object() noexcept { getObjectModel().removeListener(*this); } void Object::addOutputLink(flip::Ref link_ref, size_t outlet_index, Object & receiver, size_t inlet_index) { m_outlets[outlet_index].emplace(std::make_pair(link_ref, Link {receiver, inlet_index})); } void Object::removeOutputLink(flip::Ref link_ref, size_t outlet_index) { m_outlets[outlet_index].erase(link_ref); } // ================================================================================ // // PARMETERS // // ================================================================================ // void Object::modelParameterChanged(std::string const& name, tool::Parameter const& parameter) { defer([this, name, parameter]() { parameterChanged(name, parameter); }); } void Object::modelAttributeChanged(std::string const& name, tool::Parameter const& parameter) { defer([this, name, parameter]() { attributeChanged(name, parameter); }); } model::Object& Object::getObjectModel() { return m_patcher.getPatcherModel().document().object<model::Object>(m_ref); } void Object::parameterChanged(std::string const& param_name, tool::Parameter const& param) {} void Object::attributeChanged(std::string const& name, tool::Parameter const& attribute) {} void Object::setAttribute(std::string const& name, tool::Parameter && param) { deferMain([this, name, param = std::move(param)]() { auto& object_model = getObjectModel(); object_model.setAttribute(name, param); model::DocumentManager::commit(object_model); }); } void Object::setParameter(std::string const& name, tool::Parameter && param) { deferMain([this, name, param = std::move(param)]() { getObjectModel().setParameter(name, param); }); } // ================================================================================ // // CONSOLE // // ================================================================================ // void Object::log(std::string const& text) const { m_patcher.log(text); } void Object::post(std::string const& text) const { m_patcher.post(text); } void Object::warning(std::string const& text) const { m_patcher.warning(text); } void Object::error(std::string const& text) const { m_patcher.error(text); } // ================================================================================ // // SCHEDULER // // ================================================================================ // tool::Scheduler<> & Object::getScheduler() const { return m_patcher.getScheduler(); } tool::Scheduler<> & Object::getMainScheduler() const { return m_patcher.getMainScheduler(); } void Object::defer(std::function<void()> call_back) { std::weak_ptr<engine::Object> object(m_master); getScheduler().defer([object, cb = std::move(call_back)]() { if (!object.expired()) { cb(); } }); } void Object::deferMain(std::function<void()> call_back) { std::weak_ptr<engine::Object> object(m_master); getMainScheduler().defer([object, cb = std::move(call_back)]() { if (!object.expired()) { cb(); } }); } void Object::schedule(std::function<void()> call_back, tool::Scheduler<>::duration_t delay) { std::weak_ptr<engine::Object> object(m_master); getScheduler().schedule([object, cb = std::move(call_back)]() { if (!object.expired()) { cb(); } }, delay); } void Object::scheduleMain(std::function<void()> call_back, tool::Scheduler<>::duration_t delay) { std::weak_ptr<engine::Object> object(m_master); getMainScheduler().schedule([object, cb = std::move(call_back)]() { if (!object.expired()) { cb(); } }, delay); } // ================================================================================ // // BEACON // // ================================================================================ // tool::Beacon& Object::getBeacon(std::string const& name) const { return m_patcher.getBeacon(name); } void Object::send(const size_t index, std::vector<tool::Atom> const& args) { assert(getScheduler().isThisConsumerThread()); // all message are disabled when the patcher has a stack overflow if(m_patcher.stackOverflowDetected()) return; if(index >= m_outlets.size()) return; for(auto& link_it : m_outlets[index]) { auto& link = link_it.second; ++link.useStackCount(); if(link.useStackCount() >= m_stack_overflow_max) { auto link_ref = link_it.first; m_patcher.signalStackOverflow(link_ref); error("infinite message loop detected, messages are disabled until you fix it..."); return; } Object& receiver = link.getReceiver(); receiver.receive(link.getReceiverIndex(), args); --link.useStackCount(); } } void Object::clearStackOverflow() { for(auto& outlet : m_outlets) { for(auto& link_it : outlet) { auto& link = link_it.second; link.useStackCount() = 0; } } } // ================================================================================ // // AUDIOOBJECT // // ================================================================================ // AudioObject::AudioObject(model::Object const& model, Patcher& patcher) noexcept : Object(model, patcher) , dsp::Processor(model.getNumberOfInlets(), model.getNumberOfOutlets()) {} } }
9,460
C++
.cpp
205
32.77561
114
0.431548
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,250
KiwiEngine_Patcher.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Patcher.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include "KiwiEngine_Patcher.h" #include "KiwiEngine_Object.h" #include "KiwiEngine_Link.h" #include "KiwiEngine_Factory.h" #include "KiwiEngine_Instance.h" #include <KiwiTool/KiwiTool_Scheduler.h> #include <KiwiModel/KiwiModel_PatcherUser.h> namespace kiwi { namespace engine { // ================================================================================ // // PATCHER // // ================================================================================ // Patcher::Patcher(Instance& instance, model::Patcher& patcher_model) noexcept : m_instance(instance) , m_objects() , m_chain() , m_patcher_model(patcher_model) , m_stack_overflow_cleared_signal_cnx(patcher_model.signal_stack_overflow_clear.connect([this]() { onStackOverflowCleared(); })) { m_instance.getAudioControler().add(m_chain); } Patcher::~Patcher() { m_stack_overflow_cleared_signal_cnx.disconnect(); m_instance.getAudioControler().remove(m_chain); } model::Patcher& Patcher::getPatcherModel() { return m_patcher_model; } void Patcher::updateChain() { try { m_chain.update(); } catch (dsp::LoopError & e) { error(e.what()); } } AudioControler& Patcher::getAudioControler() const { return m_instance.getAudioControler(); } void Patcher::signalStackOverflow(flip::Ref ref) { m_instance.getMainScheduler().defer([this, ref = std::move(ref)](){ m_patcher_model.signal_stack_overflow({ref}); }); m_has_stack_overflow = true; } bool Patcher::stackOverflowDetected() const { return m_has_stack_overflow; } void Patcher::clearStackOverflow() { for(auto& object_it : m_objects) { auto& object = object_it.second; object->clearStackOverflow(); } m_has_stack_overflow = false; } void Patcher::onStackOverflowCleared() { clearStackOverflow(); } void Patcher::sendLoadbang() { for(auto& object : m_objects) { object.second->loadbang(); } } // ================================================================================ // // CONSOLE // // ================================================================================ // void Patcher::log(std::string const& text) const { m_instance.log(text); } void Patcher::post(std::string const& text) const { m_instance.post(text); } void Patcher::warning(std::string const& text) const { m_instance.warning(text); } void Patcher::error(std::string const& text) const { m_instance.error(text); } // ================================================================================ // // SCHEDULER // // ================================================================================ // tool::Scheduler<> & Patcher::getScheduler() const { return m_instance.getScheduler(); } tool::Scheduler<> & Patcher::getMainScheduler() const { return m_instance.getMainScheduler(); } // ================================================================================ // // BEACON // // ================================================================================ // tool::Beacon& Patcher::getBeacon(std::string const& name) const { return m_instance.getBeacon(name); } // ================================================================================ // // MODEL CHANGED // // ================================================================================ // void Patcher::modelChanged(model::Patcher const& model) { if(model.changed()) { updateGraph(model); updateAttributes(model); if(m_dsp_chain_need_update) { updateChain(); m_dsp_chain_need_update = false; } } } void Patcher::updateGraph(model::Patcher const& patcher_model) { std::vector<model::Link const*> added_links; std::vector<model::Link const*> removed_links; std::vector<model::Object const*> added_objects; std::vector<model::Object const*> removed_objects; if (patcher_model.linksChanged()) { for (auto const& link : patcher_model.getLinks()) { if (link.added()) { added_links.emplace_back(&link); } if (link.removed()) { removed_links.emplace_back(&link); } } } if (patcher_model.objectsChanged()) { for(auto const & object : patcher_model.getObjects()) { if(object.added()) { added_objects.emplace_back(&object); } else if(object.removed()) { removed_objects.emplace_back(&object); } } } const bool has_changed = (!added_links.empty() || !removed_links.empty() || !added_objects.empty() || !removed_objects.empty()); if (has_changed) { std::unique_lock<std::mutex> lock(getScheduler().lock()); for (auto link : removed_links) { linkRemoved(*link); } for (auto object : removed_objects) { objectRemoved(*object); } for (auto object : added_objects) { objectAdded(*object); } for (auto link : added_links) { linkAdded(*link); } } } void Patcher::updateAttributes(model::Patcher const& patcher_model) { if (patcher_model.objectsChanged()) { for(auto const& object : patcher_model.getObjects()) { if (!object.removed() && !object.added()) { std::set<std::string> changed_params = object.getChangedAttributes(); for (std::string const& param_name : changed_params) { m_objects.at(object.ref())->modelAttributeChanged(param_name, object.getAttribute(param_name)); } } } } } void Patcher::objectAdded(model::Object const& object_m) { auto it = m_objects.emplace(std::make_pair(object_m.ref(), Factory::create(*this, object_m))); if(it.second) { auto object = it.first->second; if(auto processor = std::dynamic_pointer_cast<AudioObject>(object)) { m_chain.addProcessor(std::move(processor)); m_dsp_chain_need_update = true; } } } void Patcher::objectRemoved(model::Object const& object_m) { auto it = m_objects.find(object_m.ref()); // (for now) all model object must be reflected in the engine graph assert(it != m_objects.end()); if(it == m_objects.end()) return; // abort if (auto processor = std::dynamic_pointer_cast<AudioObject>(it->second)) { m_chain.removeProcessor(*processor); m_dsp_chain_need_update = true; } m_objects.erase(it); } void Patcher::linkAdded(model::Link const& link_m) { auto from = m_objects[link_m.getSenderObject().ref()]; auto to = m_objects[link_m.getReceiverObject().ref()]; assert(from && to); if(!from || !to) return; // abort const auto outlet = link_m.getSenderIndex(); const auto inlet = link_m.getReceiverIndex(); if (!link_m.isSignal()) { from->addOutputLink(link_m.ref(), outlet, *to, inlet); } else { auto proc_from = std::dynamic_pointer_cast<AudioObject>(from); auto proc_to = std::dynamic_pointer_cast<AudioObject>(to); m_chain.connect(*proc_from, outlet, *proc_to, inlet); m_dsp_chain_need_update = true; } } void Patcher::linkRemoved(model::Link const& link_m) { auto from = m_objects[link_m.getSenderObject().ref()]; auto to = m_objects[link_m.getReceiverObject().ref()]; assert(from && to); if(!from || !to) return; // abort const auto outlet = link_m.getSenderIndex(); const auto inlet = link_m.getReceiverIndex(); if (!link_m.isSignal()) { from->removeOutputLink(link_m.ref(), outlet); } else { auto proc_from = std::dynamic_pointer_cast<AudioObject>(from); auto proc_to = std::dynamic_pointer_cast<AudioObject>(to); assert(proc_from && proc_to); m_chain.disconnect(*proc_from, outlet, *proc_to, inlet); m_dsp_chain_need_update = true; } } }}
11,062
C++
.cpp
291
27.013746
107
0.469433
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,251
KiwiEngine_Factory.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Factory.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiModel/KiwiModel_Factory.h> #include "KiwiEngine_Factory.h" namespace kiwi { namespace engine { // ================================================================================ // // FACTORY // // ================================================================================ // std::map<std::string, Factory::ctor_fn_t> Factory::m_creators; std::unique_ptr<Object> Factory::create(Patcher& patcher, model::Object const& model) { assert(m_creators.count(model.getName()) != 0 && "The object has not been registered."); return m_creators[model.getName()](model, patcher); } bool Factory::has(std::string const& name) { return static_cast<bool>(m_creators.count(name)); } bool Factory::modelHasObject(std::string const& name) { return model::Factory::has(name); } } }
1,975
C++
.cpp
39
42.410256
101
0.486096
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,252
KiwiEngine_Instance.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Instance.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include "KiwiEngine_Factory.h" #include "KiwiEngine_Instance.h" namespace kiwi { namespace engine { // ================================================================================ // // INSTANCE // // ================================================================================ // Instance::Instance(std::unique_ptr<AudioControler> audio_controler, tool::Scheduler<> & main_scheduler): m_audio_controler(std::move(audio_controler)), m_scheduler(), m_main_scheduler(main_scheduler), m_quit(false), m_engine_thread(std::bind(&Instance::processScheduler, this)) { } Instance::~Instance() { m_quit.store(true); m_engine_thread.join(); } // ================================================================================ // // CONSOLE // // ================================================================================ // void Instance::log(std::string const& text) const { m_console.post({text, Console::Message::Type::Log}); } void Instance::post(std::string const& text) const { m_console.post({text, Console::Message::Type::Normal}); } void Instance::warning(std::string const& text) const { m_console.post({text, Console::Message::Type::Warning}); } void Instance::error(std::string const& text) const { m_console.post({text, Console::Message::Type::Error}); } void Instance::addConsoleListener(Console::Listener& listener) { m_console.addListener(listener); } void Instance::removeConsoleListener(Console::Listener& listener) { m_console.removeListener(listener); } // ================================================================================ // // AUDIO CONTROLER // // ================================================================================ // AudioControler& Instance::getAudioControler() const { return *m_audio_controler.get(); } // ================================================================================ // // SCHEDULER // // ================================================================================ // tool::Scheduler<> & Instance::getScheduler() { return m_scheduler; } tool::Scheduler<> & Instance::getMainScheduler() { return m_main_scheduler; } void Instance::processScheduler() { m_scheduler.setThreadAsConsumer(); while(!m_quit.load()) { m_scheduler.process(); std::this_thread::sleep_for(std::chrono::milliseconds(1)); } } } }
4,212
C++
.cpp
92
36
112
0.410269
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,253
KiwiEngine_GreaterTilde.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_GreaterTilde.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_GreaterTilde.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // >~ // // ================================================================================ // void GreaterTilde::declare() { Factory::add<GreaterTilde>(">~", &GreaterTilde::create); } std::unique_ptr<Object> GreaterTilde::create(model::Object const& model, Patcher & patcher) { return std::make_unique<GreaterTilde>(model, patcher); } GreaterTilde::GreaterTilde(model::Object const& model, Patcher& patcher): OperatorTilde(model, patcher) { } void GreaterTilde::compute(dsp::sample_t & result, dsp::sample_t const& lhs, dsp::sample_t const& rhs) { result = lhs > rhs ? 1 : 0; } }}
1,875
C++
.cpp
37
45.756757
106
0.521739
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,254
KiwiEngine_DacTilde.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_DacTilde.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_DacTilde.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // DAC~ // // ================================================================================ // void DacTilde::declare() { Factory::add<DacTilde>("dac~", &DacTilde::create); } std::unique_ptr<Object> DacTilde::create(model::Object const& model, Patcher & patcher) { return std::make_unique<DacTilde>(model, patcher); } DacTilde::DacTilde(model::Object const& model, Patcher& patcher): AudioInterfaceObject(model, patcher) { } void DacTilde::perform(dsp::Buffer const& input, dsp::Buffer& output) noexcept { for (size_t inlet = 0; inlet < m_routes.size(); ++inlet) { m_audio_controler.addToChannel(m_routes[inlet], input[inlet]); } } void DacTilde::prepare(dsp::Processor::PrepareInfo const& infos) { setPerformCallBack(this, &DacTilde::perform); } }}
2,092
C++
.cpp
44
42.045455
91
0.531266
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,255
KiwiEngine_ErrorBox.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_ErrorBox.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Factory.h> #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_ErrorBox.h> namespace kiwi { namespace engine { // ================================================================================ // // ERRORBOX // // ================================================================================ // void ErrorBox::declare() { Factory::add<ErrorBox>("errorbox", &ErrorBox::create); } std::unique_ptr<Object> ErrorBox::create(model::Object const& object, Patcher& patcher) { return std::make_unique<ErrorBox>(object, patcher); } ErrorBox::ErrorBox(model::Object const& model, Patcher& patcher) : AudioObject(model, patcher) { ; } void ErrorBox::receive(size_t index, std::vector<tool::Atom> const& args) { ; } void ErrorBox::prepare(dsp::Processor::PrepareInfo const& infos) { ; } }}
1,901
C++
.cpp
42
40
91
0.518519
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,256
KiwiEngine_Loadmess.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_Loadmess.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_Loadmess.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // OBJECT LOADMESS // // ================================================================================ // void Loadmess::declare() { Factory::add<Loadmess>("loadmess", &Loadmess::create); } std::unique_ptr<Object> Loadmess::create(model::Object const& model, Patcher & patcher) { return std::make_unique<Loadmess>(model, patcher); } Loadmess::Loadmess(model::Object const& model, Patcher& patcher): Object(model, patcher), m_args(model.getArguments()) { } void Loadmess::receive(size_t index, std::vector<tool::Atom> const& args) { if (!args.empty() && args[0].isBang()) { send(0ul, m_args); } else { warning("loadmess inlet 1 doesn't understane [" + args[0].getString() + "]"); } } void Loadmess::loadbang() { defer([this]() { send(0, m_args); }); } }}
2,154
C++
.cpp
52
35.288462
91
0.504386
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,257
KiwiEngine_OperatorTilde.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_OperatorTilde.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_OperatorTilde.h> namespace kiwi { namespace engine { // ================================================================================ // // OPERATOR TILDE // // ================================================================================ // OperatorTilde::OperatorTilde(model::Object const& model, Patcher& patcher): AudioObject(model, patcher), m_rhs() { std::vector<tool::Atom> const& args = model.getArguments(); if (!args.empty() && args[0].isNumber()) { m_rhs = args[0].getFloat(); } } void OperatorTilde::receive(size_t index, std::vector<tool::Atom> const& args) { if(!args.empty()) { if(args[0].isNumber() && index == 1) { m_rhs = args[0].getFloat(); } } } void OperatorTilde::performVec(dsp::Buffer const& input, dsp::Buffer& output) noexcept { dsp::Signal const& in = input[0]; const size_t size = in.size(); dsp::sample_t const* in1 = in.data(); dsp::sample_t const* in2 = input[1].data(); dsp::sample_t* out = output[0].data(); for(size_t i = size>>3; i; --i, in1 += 8, in2 += 8, out += 8) { compute(out[0], in1[0], in2[0]); compute(out[1], in1[1], in2[1]); compute(out[2], in1[2], in2[2]); compute(out[3], in1[3], in2[3]); compute(out[4], in1[4], in2[4]); compute(out[5], in1[5], in2[5]); compute(out[6], in1[6], in2[6]); compute(out[7], in1[7], in2[7]); } for(size_t i = size&7; i; --i, in1++, in2++, out++) { compute(out[0], in1[0], in2[0]); } } void OperatorTilde::performValue(dsp::Buffer const& input, dsp::Buffer& output) noexcept { dsp::Signal const& in = input[0]; const size_t size = in.size(); dsp::sample_t const* in1 = in.data(); dsp::sample_t* out = output[0].data(); dsp::sample_t const value = m_rhs; for(size_t i = size>>3; i; --i, in1 += 8, out += 8) { compute(out[0], in1[0], value); compute(out[1], in1[1], value); compute(out[2], in1[2], value); compute(out[3], in1[3], value); compute(out[4], in1[4], value); compute(out[5], in1[5], value); compute(out[6], in1[6], value); compute(out[7], in1[7], value); } for(size_t i = size&7; i; --i, in1++, out++) { compute(out[0], in1[0], value); } } void OperatorTilde::prepare(dsp::Processor::PrepareInfo const& infos) { if (infos.inputs.size() > 1 && infos.inputs[1]) { setPerformCallBack(this, &OperatorTilde::performVec); } else { setPerformCallBack(this, &OperatorTilde::performValue); } } }}
4,003
C++
.cpp
97
32.319588
92
0.485572
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,258
KiwiEngine_MeterTilde.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_MeterTilde.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiModel/KiwiModel_Objects/KiwiModel_MeterTilde.h> #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_MeterTilde.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // METER~ // // ================================================================================ // void MeterTilde::declare() { Factory::add<MeterTilde>("meter~", &MeterTilde::create); } std::unique_ptr<Object> MeterTilde::create(model::Object const& model, Patcher & patcher) { return std::make_unique<MeterTilde>(model, patcher); } MeterTilde::MeterTilde(model::Object const& model, Patcher& patcher): engine::AudioObject(model, patcher), tool::Scheduler<>::Timer(patcher.getScheduler()), m_interval(50), m_current_peak(0), m_sample_index(0), m_target_sample_index(0), m_last_peak(0), m_uptodate(true), m_signal(model.getSignal<float>(model::MeterTilde::Signal::PeakChanged)) { } void MeterTilde::receive(size_t index, std::vector<tool::Atom> const& args) { } void MeterTilde::perform(dsp::Buffer const& input, dsp::Buffer& output) { dsp::sample_t const* const input_data = input[0ul].data(); size_t sample_index = input[0].size(); while(sample_index--) { m_current_peak = std::max(m_current_peak, std::abs(input_data[sample_index])); if (m_sample_index++ == m_target_sample_index) { m_last_peak.store(m_current_peak); m_uptodate.store(false); m_sample_index = 0; m_current_peak = 0; } } } void MeterTilde::timerCallBack() { bool expected = false; if (m_uptodate.compare_exchange_strong(expected, true)) { float last_peak = m_last_peak.load(); send(0, {last_peak}); m_signal(last_peak); } } void MeterTilde::release() { stopTimer(); } void MeterTilde::prepare(dsp::Processor::PrepareInfo const& infos) { m_target_sample_index = static_cast<size_t>(infos.sample_rate * (m_interval / 1000.)); m_sample_index = 0; m_current_peak = 0; setPerformCallBack(this, &MeterTilde::perform); startTimer(std::chrono::milliseconds(m_interval)); } } }
3,492
C++
.cpp
84
34.02381
94
0.550773
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,259
KiwiEngine_DivideTilde.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_DivideTilde.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_DivideTilde.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // /~ // // ================================================================================ // void DivideTilde::declare() { Factory::add<DivideTilde>("/~", &DivideTilde::create); } std::unique_ptr<Object> DivideTilde::create(model::Object const& model, Patcher & patcher) { return std::make_unique<DivideTilde>(model, patcher); } DivideTilde::DivideTilde(model::Object const& model, Patcher& patcher): OperatorTilde(model, patcher) { if (model.getArguments().empty()) { m_rhs = 1; } } void DivideTilde::compute(dsp::sample_t & result, dsp::sample_t const& lhs, dsp::sample_t const& rhs) { result = rhs != 0 ? lhs / rhs : 0.; } }}
1,959
C++
.cpp
41
42.365854
105
0.51174
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,261
KiwiEngine_Modulo.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_Modulo.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <cmath> #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_Modulo.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // OBJECT MODULO // // ================================================================================ // void Modulo::declare() { Factory::add<Modulo>("%", &Modulo::create); } std::unique_ptr<Object> Modulo::create(model::Object const& model, Patcher & patcher) { return std::make_unique<Modulo>(model, patcher); } Modulo::Modulo(model::Object const& model, Patcher& patcher): Operator(model, patcher) { std::vector<tool::Atom> const& args = model.getArguments(); if (args.empty()) { m_rhs = 1; } } double Modulo::compute(double lhs, double rhs) const { return fmodf(lhs, rhs); } }}
1,931
C++
.cpp
43
39.27907
90
0.51036
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,262
KiwiEngine_Equal.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_Equal.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_Equal.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // OBJECT EQUAL // // ================================================================================ // void Equal::declare() { Factory::add<Equal>("==", &Equal::create); } std::unique_ptr<Object> Equal::create(model::Object const& model, Patcher & patcher) { return std::make_unique<Equal>(model, patcher); } Equal::Equal(model::Object const& model, Patcher& patcher): Operator(model, patcher) { } double Equal::compute(double lhs, double rhs) const { return lhs == rhs ? 1 : 0; } }}
1,762
C++
.cpp
37
42.702703
90
0.506841
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,263
KiwiEngine_Select.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_Select.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_Select.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // SELECT // // ================================================================================ // void Select::declare() { Factory::add<Select>("select", &Select::create); } std::unique_ptr<Object> Select::create(model::Object const& model, Patcher & patcher) { return std::make_unique<Select>(model, patcher); } Select::Select(model::Object const& model, Patcher& patcher) : Object(model, patcher) , m_list(model.getArguments()) {} void Select::receive(size_t index, std::vector<tool::Atom> const& args) { if(args.empty()) return; // abort static const std::vector<tool::Atom> bang_msg = {"bang"}; tool::Atom const& input = args[0]; if (index == 0) { for(size_t i = 0; i != m_list.size(); ++i) { tool::Atom const& selector = m_list[i]; if ((input.isNumber() && (input.getFloat() == selector.getFloat())) || (input.isString() && (input.getString() == selector.getString()))) { send(i, bang_msg); return; } } send(m_list.size(), args); } else if(index > 0 && m_list.size() <= index) { m_list[index - 1] = input; } } }}
2,664
C++
.cpp
60
34.95
90
0.473032
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,264
KiwiEngine_Plus.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_Plus.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_Plus.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // OBJECT PLUS // // ================================================================================ // void Plus::declare() { Factory::add<Plus>("+", &Plus::create); } std::unique_ptr<Object> Plus::create(model::Object const& model, Patcher & patcher) { return std::make_unique<Plus>(model, patcher); } Plus::Plus(model::Object const& model, Patcher& patcher): Operator(model, patcher) { } double Plus::compute(double lhs, double rhs) const { return lhs + rhs; } }}
1,744
C++
.cpp
37
42.189189
90
0.505415
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,265
KiwiEngine_SahTilde.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_SahTilde.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_SahTilde.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi{ namespace engine { // ================================================================================ // // SAH~ // // ================================================================================ // void SahTilde::declare() { Factory::add<SahTilde>("sah~", &SahTilde::create); } std::unique_ptr<Object> SahTilde::create(model::Object const& model, Patcher & patcher) { return std::make_unique<SahTilde>(model, patcher); } SahTilde::SahTilde(model::Object const& model, Patcher& patcher) : AudioObject(model, patcher) { std::vector<tool::Atom> const& args = model.getArguments(); if (!args.empty() && args[0].isNumber()) { setThreshold(args[0].getFloat()); } } void SahTilde::setThreshold(dsp::sample_t const& value) noexcept { m_threshold.store(value); } void SahTilde::receive(size_t index, std::vector<tool::Atom> const& args) { if (index == 1 && !args.empty()) { if (args[0].isNumber()) { setThreshold(args[0].getFloat()); } else { warning("sah~ inlet 1 only takes numbers"); } } } void SahTilde::prepare(PrepareInfo const& infos) { setPerformCallBack(this, &SahTilde::perform); } void SahTilde::perform(dsp::Buffer const& input, dsp::Buffer& output) noexcept { size_t sampleframes = output[0ul].size(); dsp::sample_t const* in1 = input[0ul].data(); dsp::sample_t const* in2 = input[1ul].data(); dsp::sample_t* out = output[0ul].data(); const dsp::sample_t threshold = m_threshold.load(); while(sampleframes--) { dsp::sample_t sample = *in1++; dsp::sample_t ctrl_sample = *in2++; if(m_last_ctrl_sample <= threshold && ctrl_sample > threshold) { m_hold_value = sample; } *out++ = m_hold_value; m_last_ctrl_sample = ctrl_sample; } } }}
3,284
C++
.cpp
80
32.45
91
0.51132
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,266
KiwiEngine_Hub.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_Hub.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiTool/KiwiTool_Atom.h> #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_Hub.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // OBJECT HUB // // ================================================================================ // void Hub::declare() { Factory::add<Hub>("hub", &Hub::create); } std::unique_ptr<Object> Hub::create(model::Object const& model, Patcher& patcher) { return std::make_unique<Hub>(model, patcher); } Hub::Hub(model::Object const& object_model, Patcher& patcher): Object(object_model, patcher) { } Hub::~Hub() { } void Hub::attributeChanged(std::string const& name, tool::Parameter const& parameter) { if (name == "message") { send(0, tool::AtomHelper::parse(parameter[0].getString())); } } void Hub::receive(size_t index, std::vector<tool::Atom> const& args) { if (index == 0 && !args.empty()) { setAttribute("message", { tool::Parameter::Type::String, {tool::AtomHelper::toString(args)}}); } } }}
2,213
C++
.cpp
51
37.509804
106
0.516175
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,267
KiwiEngine_Comment.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_Comment.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_Comment.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // OBJECT COMMENT // // ================================================================================ // void Comment::declare() { Factory::add<Comment>("comment", &Comment::create); } std::unique_ptr<Object> Comment::create(model::Object const& model, Patcher& patcher) { return std::make_unique<Comment>(model, patcher); } Comment::Comment(model::Object const& object_model, Patcher& patcher): Object(object_model, patcher) { } Comment::~Comment() { } void Comment::receive(size_t index, std::vector<tool::Atom> const& args) { } }}
1,827
C++
.cpp
39
41.74359
90
0.519331
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,268
KiwiEngine_NoiseTilde.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_NoiseTilde.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <functional> #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_NoiseTilde.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // NOISE~ // // ================================================================================ // void NoiseTilde::declare() { Factory::add<NoiseTilde>("noise~", &NoiseTilde::create); } std::unique_ptr<Object> NoiseTilde::create(model::Object const& model, Patcher & patcher) { return std::make_unique<NoiseTilde>(model, patcher); } NoiseTilde::NoiseTilde(model::Object const& model, Patcher& patcher) : AudioObject(model, patcher) , m_random_devive() , m_random_generator(m_random_devive()) , m_random_distribution(-1., 1.) { ; } void NoiseTilde::receive(size_t index, std::vector<tool::Atom> const& args) { ; } void NoiseTilde::perform(dsp::Buffer const& input, dsp::Buffer& output) noexcept { size_t frames = output[0].size(); dsp::sample_t* out = output[0].data(); while(frames--) { *out++ = m_random_distribution(m_random_generator); } } void NoiseTilde::prepare(dsp::Processor::PrepareInfo const& infos) { setPerformCallBack(this, &NoiseTilde::perform); } }}
2,426
C++
.cpp
56
37.035714
93
0.53209
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,269
KiwiEngine_OSCSend.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_OSCSend.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Factory.h> #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_OSCSend.h> namespace kiwi { namespace engine { // ================================================================================ // // OSC.receive // // ================================================================================ // void OSCSend::declare() { Factory::add<OSCSend>("OSC.send", &OSCSend::create); } std::unique_ptr<Object> OSCSend::create(model::Object const& model, Patcher& patcher) { return std::make_unique<OSCSend>(model, patcher); } OSCSend::OSCSend(model::Object const& model, Patcher& patcher) : Object(model, patcher) { const auto& args = model.getArguments(); if(args.size() >= 2) { if(args[0].isString()) { m_host = args[0].getString(); } if(args[1].isInt()) { m_port = args[1].getInt(); } } connectToHostAndPort(m_host, m_port); } void OSCSend::receive(size_t index, std::vector<tool::Atom> const& args) { if(args.size() >= 1 && args[0].isString() && args[0].getString() == "connect") { if(args.size() >= 3 && args[1].isString() && args[2].isInt()) { m_host = args[1].getString(); m_port = args[2].getInt(); connectToHostAndPort(m_host, m_port); } } else if(!args.empty()) { // send message auto arg = args.begin(); if(arg->isString() && arg->getString().front() == '/') { juce::OSCAddressPattern ap(arg->getString()); juce::OSCMessage message(ap); for(arg++; arg != args.end(); arg++) { if(arg->isInt()) {message.addInt32(arg->getInt());} else if(arg->isFloat()) {message.addFloat32(arg->getFloat());} else if(arg->isString()) {message.addString(arg->getString());} } if(!m_sender.sendToIPAddress(m_host, m_port, message)) { error("OSC.send: can't bind to host " + m_host + " on port " + std::to_string(m_port)); } } else { error("bad OSC message format"); } } } bool OSCSend::connectToHostAndPort(std::string host, int new_port) { m_sender.disconnect(); if(m_sender.connect(host, new_port)) { return true; } error("OSC.send: can't connect to host " + host + " on port " + std::to_string(new_port)); return false; } }}
3,845
C++
.cpp
92
31.086957
107
0.474455
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,270
KiwiEngine_Scale.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_Scale.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_Scale.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // SCALE // // ================================================================================ // void Scale::declare() { Factory::add<Scale>("scale", &Scale::create); } std::unique_ptr<Object> Scale::create(model::Object const& model, Patcher & patcher) { return std::make_unique<Scale>(model, patcher); } Scale::Scale(model::Object const& model, Patcher& patcher): Object(model, patcher) { std::vector<tool::Atom> const& args = model.getArguments(); if (args.size() > 3) { m_output_high = args[3].getFloat(); } if (args.size() > 2) { m_output_low = args[2].getFloat(); } if (args.size() > 1) { m_input_high = args[1].getFloat(); } if (args.size() > 0) { m_input_low = args[0].getFloat(); } } void Scale::receive(size_t index, std::vector<tool::Atom> const& args) { if (index == 0) { if (args[0].isNumber()) { m_value = args[0].getFloat(); send(0, {scaleValue()}); } else if (args[0].isBang()) { send(0, {scaleValue()}); } else { warning("scale inlet 1 only understands numbers and bang"); } } else if (index == 1) { if (args[0].isNumber()) { m_input_low = args[0].getFloat(); } else { warning("scale inlet 2 only understands numbers"); } } else if(index == 2) { if (args[0].isNumber()) { m_input_high = args[0].getFloat(); } else { warning("scale inlet 3 only understands numbers"); } } else if(index == 3) { if (args[0].isNumber()) { m_output_low = args[0].getFloat(); } else { warning("scale inlet 4 only understands numbers"); } } else if(index == 4) { if (args[0].isNumber()) { m_output_high = args[0].getFloat(); } else { warning("scale inlet 5 only understands numbers"); } } } float Scale::scaleValue() { return m_output_low + ((m_output_high - m_output_low) / (m_input_high - m_input_low)) * (m_value - m_input_low); } }}
3,931
C++
.cpp
118
23.322034
100
0.437182
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,271
KiwiEngine_LessEqual.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_LessEqual.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_LessEqual.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // OBJECT LESSEQUAL // // ================================================================================ // void LessEqual::declare() { Factory::add<LessEqual>("<=", &LessEqual::create); } std::unique_ptr<Object> LessEqual::create(model::Object const& model, Patcher & patcher) { return std::make_unique<LessEqual>(model, patcher); } LessEqual::LessEqual(model::Object const& model, Patcher& patcher): Operator(model, patcher) { } double LessEqual::compute(double lhs, double rhs) const { return lhs <= rhs ? 1 : 0; } }}
1,798
C++
.cpp
37
43.675676
92
0.519511
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,272
KiwiEngine_Unpack.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_Unpack.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_Unpack.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // UNPACK // // ================================================================================ // void Unpack::declare() { Factory::add<Unpack>("unpack", &Unpack::create); } std::unique_ptr<Object> Unpack::create(model::Object const& model, Patcher & patcher) { return std::make_unique<Unpack>(model, patcher); } Unpack::Unpack(model::Object const& model, Patcher& patcher) : Object(model, patcher), m_list(model.getArguments()) { } void Unpack::output_list() { for (int i = m_list.size() - 1; i >= 0; --i) { send(i, {m_list[i]}); } } void Unpack::receive(size_t index, std::vector<tool::Atom> const& args) { if (args[0].isBang()) { output_list(); } else { for (int i = std::max(m_list.size() - 1, args.size() - 1); i >= 0; --i) { if (!args[i].isBang()) { switch (m_list[i].getType()) { case tool::Atom::Type::Float: { m_list[i] = args[i].getFloat(); send(i, {m_list[i]}); break; } case tool::Atom::Type::Int: { m_list[i] = args[i].getInt(); send(i, {m_list[i]}); break; } case tool::Atom::Type::String: { if (args[i].isString()) { m_list[i] = args[i].getString(); send(i, {m_list[i]}); } break; } default: break; } } else if (i > 0) { warning("unpack list element " + std::to_string(i) + " bang not taken into account"); } } } } }}
3,422
C++
.cpp
86
26.581395
105
0.39063
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,273
KiwiEngine_Route.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_Route.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Factory.h> #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_Route.h> namespace kiwi { namespace engine { // ================================================================================ // // ROUTE // // ================================================================================ // void Route::declare() { Factory::add<Route>("route", &Route::create); } std::unique_ptr<Object> Route::create(model::Object const& model, Patcher& patcher) { return std::make_unique<Route>(model, patcher); } Route::Route(model::Object const& model, Patcher& patcher) : Object(model, patcher) , m_args(model.getArguments()) { if(m_args.empty()) { // Initialize default custom selector m_args.emplace_back(0); } } void Route::receive(size_t index, std::vector<tool::Atom> const& args) { // handle custom selector special case if(index == 1 && !args.empty()) { assert(m_args.size() == 1); m_args.front() = args.front(); } if(index == 0 && !args.empty()) { const auto& first_arg = args.front(); const bool is_list = args.size() > 1; const std::vector<tool::Atom> bang_msg = {"bang"}; auto send_if = [&](const size_t out, bool remove_first_elem = true) { if(!remove_first_elem) { send(out, args); } else if (is_list) { send(out, {args.begin()+1, args.end()}); } else { send(out, bang_msg); } }; bool input_matched = false; for (int i = 0; i < m_args.size(); i++) { auto const& arg = m_args[i]; if(arg.isString()) { const auto& str = arg.getString(); if(first_arg.isString() && (first_arg.getString() == str)) { send_if(i); input_matched = true; continue; } if ((!is_list && str == "int" && first_arg.isInt()) || (!is_list && str == "float" && first_arg.isFloat()) || (is_list && str == "list")) { send_if(i, false); input_matched = true; } } else { if((first_arg.isInt() && arg.isInt() && (first_arg.getInt() == arg.getInt())) || ((first_arg.isFloat() && arg.isFloat()) && (first_arg.getFloat() == arg.getFloat()))) { send_if(i); input_matched = true; } } } if(!input_matched) { // pass all input to last outlet if doesn't match send(m_args.size(), args); } } } }}
4,394
C++
.cpp
106
27.264151
90
0.413128
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,274
KiwiEngine_GreaterEqual.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_GreaterEqual.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_GreaterEqual.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // OBJECT GREATEREQUAL // // ================================================================================ // void GreaterEqual::declare() { Factory::add<GreaterEqual>(">=", &GreaterEqual::create); } std::unique_ptr<Object> GreaterEqual::create(model::Object const& model, Patcher & patcher) { return std::make_unique<GreaterEqual>(model, patcher); } GreaterEqual::GreaterEqual(model::Object const& model, Patcher& patcher): Operator(model, patcher) { } double GreaterEqual::compute(double lhs, double rhs) const { return lhs >= rhs ? 1 : 0; } }}
1,825
C++
.cpp
37
44.405405
95
0.52867
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,275
KiwiEngine_Switch.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_Switch.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_Switch.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // SWITCH // // ================================================================================ // void Switch::declare() { Factory::add<Switch>("switch", &Switch::create); } std::unique_ptr<Object> Switch::create(model::Object const& model, Patcher & patcher) { return std::make_unique<Switch>(model, patcher); } Switch::Switch(model::Object const& model, Patcher& patcher) : Object(model, patcher), m_opened_input(), m_num_inputs(model.getArguments()[0].getInt()) { std::vector<tool::Atom> const& args = model.getArguments(); if (args.size() > 1) { openInput(args[1].getInt()); } } void Switch::openInput(int input) { m_opened_input = std::max(0, std::min(input, static_cast<int>(m_num_inputs))); } void Switch::receive(size_t index, std::vector<tool::Atom> const& args) { if (args.size() > 0) { if (index == 0) { if (args[0].isBang()) { send(0, {static_cast<int>(m_opened_input)}); } else if(args[0].isNumber()) { openInput(args[0].getInt()); } else { warning("switch inlet 1 receives only numbers"); } } else if(index == m_opened_input) { send(0, args); } } } }}
2,745
C++
.cpp
69
30.956522
90
0.470768
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,276
KiwiEngine_Divide.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_Divide.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_Divide.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // OBJECT DIVIDE // // ================================================================================ // void Divide::declare() { Factory::add<Divide>("/", &Divide::create); } std::unique_ptr<Object> Divide::create(model::Object const& model, Patcher & patcher) { return std::make_unique<Divide>(model, patcher); } Divide::Divide(model::Object const& model, Patcher& patcher): Operator(model, patcher) { std::vector<tool::Atom> const& args = model.getArguments(); if (args.empty()) { m_rhs = 1; } } double Divide::compute(double lhs, double rhs) const { return lhs / rhs; } }}
1,907
C++
.cpp
42
39.690476
90
0.507174
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,277
KiwiEngine_Greater.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_Greater.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_Greater.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // OBJECT GREATER // // ================================================================================ // void Greater::declare() { Factory::add<Greater>(">", &Greater::create); } std::unique_ptr<Object> Greater::create(model::Object const& model, Patcher & patcher) { return std::make_unique<Greater>(model, patcher); } Greater::Greater(model::Object const& model, Patcher& patcher): Operator(model, patcher) { } double Greater::compute(double lhs, double rhs) const { return lhs > rhs ? 1 : 0; } }}
1,778
C++
.cpp
37
43.135135
90
0.513848
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,278
KiwiEngine_Pow.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_Pow.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <cmath> #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_Pow.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // OBJECT POW // // ================================================================================ // void Pow::declare() { Factory::add<Pow>("pow", &Pow::create); } std::unique_ptr<Object> Pow::create(model::Object const& model, Patcher & patcher) { return std::make_unique<Pow>(model, patcher); } Pow::Pow(model::Object const& model, Patcher& patcher): Operator(model, patcher) { } double Pow::compute(double lhs, double rhs) const { return std::pow(lhs, rhs); } }}
1,763
C++
.cpp
38
41.552632
90
0.506548
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,279
KiwiEngine_NewBox.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_NewBox.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Factory.h> #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_NewBox.h> namespace kiwi { namespace engine { // ================================================================================ // // NEWBOX // // ================================================================================ // void NewBox::declare() { Factory::add<NewBox>("newbox", &NewBox::create); } std::unique_ptr<Object> NewBox::create(model::Object const& model, Patcher& patcher) { return std::make_unique<NewBox>(model, patcher); } NewBox::NewBox(model::Object const& model, Patcher& patcher) : Object(model, patcher) { ; } void NewBox::receive(size_t index, std::vector<tool::Atom> const& args) { ; } }}
1,775
C++
.cpp
38
41.736842
90
0.505009
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,280
KiwiEngine_NumberTilde.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_NumberTilde.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiModel/KiwiModel_Objects/KiwiModel_Number.h> #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_NumberTilde.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // OBJECT NUMBER TILDE // // ================================================================================ // void NumberTilde::declare() { Factory::add<NumberTilde>("number~", &NumberTilde::create); } std::unique_ptr<Object> NumberTilde::create(model::Object const& model, Patcher& patcher) { return std::make_unique<NumberTilde>(model, patcher); } NumberTilde::NumberTilde(model::Object const& object_model, Patcher& patcher): AudioObject(object_model, patcher), tool::Scheduler<>::Timer(patcher.getScheduler()), m_value(object_model.getParameter("value")[0].getFloat()), m_interval(100) { } void NumberTilde::perform(dsp::Buffer const& input, dsp::Buffer& output) { m_value.store(input[0][input[0].size() - 1]); } void NumberTilde::prepare(dsp::Processor::PrepareInfo const& infos) { if(infos.inputs[0]) { setPerformCallBack(this, &NumberTilde::perform); } startTimer(std::chrono::milliseconds(m_interval)); } void NumberTilde::release() { stopTimer(); } void NumberTilde::timerCallBack() { double current_value = m_value.load(); setParameter("value", tool::Parameter(tool::Parameter::Type::Float, {current_value})); send(0,{current_value}); } void NumberTilde::receive(size_t index, std::vector<tool::Atom> const& args) { } }}
2,746
C++
.cpp
62
38.048387
94
0.566641
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,281
KiwiEngine_Delay.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_Delay.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_Delay.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // OBJECT DELAY // // ================================================================================ // void Delay::declare() { Factory::add<Delay>("delay", &Delay::create); } std::unique_ptr<Object> Delay::create(model::Object const& object, Patcher & patcher) { return std::make_unique<Delay>(object, patcher); } Delay::Delay(model::Object const& model, Patcher& patcher): Object(model, patcher), m_task(new tool::Scheduler<>::CallBack(std::bind(&Delay::bang, this))), m_delay(std::chrono::milliseconds(0)) { std::vector<tool::Atom> const& args = model.getArguments(); if (!args.empty()) { m_delay = std::chrono::milliseconds(args[0].getInt()); } } Delay::~Delay() { getScheduler().unschedule(m_task); } void Delay::bang() { send(0, {"bang"}); } void Delay::receive(size_t index, std::vector<tool::Atom> const& args) { if (!args.empty()) { if (index == 0) { if(args[0].isBang()) { getScheduler().schedule(m_task, m_delay); } else if(args[0].isString() && args[0].getString() == "stop") { getScheduler().unschedule(m_task); } else { warning("delay inlet 1 only receives bang and stop"); } } else if(index == 1) { if (args[0].isNumber()) { m_delay = std::chrono::milliseconds(args[0].getInt()); } else { warning("delay inlet 2 doesn't understand [" + args[0].getString() + "]"); } } } } } }
3,386
C++
.cpp
84
27.845238
98
0.425776
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,282
KiwiEngine_Trigger.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_Trigger.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_Trigger.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // TRIGGER // // ================================================================================ // void Trigger::declare() { Factory::add<Trigger>("trigger", &Trigger::create); } std::unique_ptr<Object> Trigger::create(model::Object const& model, Patcher & patcher) { return std::make_unique<Trigger>(model, patcher); } Trigger::Trigger(model::Object const& model, Patcher& patcher) : Object(model, patcher) , m_triggers(initializeTriggers(model.getArguments())) { ; } auto Trigger::initializeTriggers(std::vector<tool::Atom> const& _args) -> std::vector<trigger_fn_t> { const auto trigger_fn_factory = [](tool::Atom const& atom) -> trigger_fn_t { if(atom.isNumber()) { const auto value = atom.isInt() ? atom.getInt() : atom.getFloat(); return [value](std::vector<tool::Atom> const&){ return std::vector<tool::Atom>{{value}}; }; } const auto str = atom.getString(); if(str == "b") { return [](std::vector<tool::Atom> const&) { return std::vector<tool::Atom>{{"bang"}}; }; } if(str == "i") { return [](std::vector<tool::Atom> const& args) { return std::vector<tool::Atom> {{args[0].getInt()}}; }; } if(str == "f") { return [](std::vector<tool::Atom> const& args) { return std::vector<tool::Atom> {{args[0].getFloat()}}; }; } if(str == "s") { return [](std::vector<tool::Atom> const& args) { return std::vector<tool::Atom> {{args[0].getString()}}; }; } if(str == "l") { return [](std::vector<tool::Atom> const& args) { return args; }; } return [str](std::vector<tool::Atom> const&) { return std::vector<tool::Atom>{{str}}; }; }; std::vector<trigger_fn_t> triggers; triggers.reserve(_args.size()); for(auto& atom : _args) { triggers.emplace_back(trigger_fn_factory(atom)); } return triggers; } void Trigger::receive(size_t, std::vector<tool::Atom> const& args) { if(m_triggers.empty()) return; const auto size = m_triggers.size(); size_t idx = size - 1; for (auto rit = m_triggers.rbegin(); rit != m_triggers.rend(); ++rit) { send(idx--, (*rit)(args)); } } }}
4,063
C++
.cpp
93
32.290323
104
0.478746
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,283
KiwiEngine_Random.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_Random.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <functional> #include <cmath> #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_Random.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // RANDOM // // ================================================================================ // void Random::declare() { Factory::add<Random>("random", &Random::create); } std::unique_ptr<Object> Random::create(model::Object const& model, Patcher & patcher) { return std::make_unique<Random>(model, patcher); } Random::Random(model::Object const& model, Patcher& patcher) : Object(model, patcher) { auto const& args = model.getArguments(); setRange((args.size() > 0 && args[0].isNumber()) ? args[0].getInt() : 0ll); setSeed((args.size() > 1 && args[1].isNumber()) ? args[1].getInt() : 0ll); } void Random::receive(size_t index, std::vector<tool::Atom> const& args) { if(args.empty()) return; // abort if (index == 0) { if (args[0].isBang()) { send(0, {getNextRandomValue()}); } else if (args[0].getString() == "seed") { if(args.size() > 1 && args[1].isNumber()) { setSeed(args[1].getInt()); } else { warning("random: seed message must be followed by an integer"); } } else { warning("random: inlet 1 only understands bang or seed message"); } } else if (index == 1) { if (args[0].isNumber()) { setRange(args[0].getInt()); } else { warning("random: inlet 2 only understands numbers"); } } } void Random::setRange(int64_t range) { m_random_distribution.param(rnd_distribution_t::param_type(0, std::max<int64_t>(0, range - 1))); } void Random::setSeed(int64_t seed) { if(seed == 0) { // obtain a seed from the timer seed = (clock_t::now() - m_start_time).count(); } m_random_generator.seed(seed); } int64_t Random::getNextRandomValue() { return m_random_distribution(m_random_generator); } }}
3,525
C++
.cpp
93
28.784946
104
0.481194
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,284
KiwiEngine_Mtof.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_Mtof.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <cmath> #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_Mtof.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // MTOF // // ================================================================================ // void Mtof::declare() { Factory::add<Mtof>("mtof", &Mtof::create); } std::unique_ptr<Object> Mtof::create(model::Object const& model, Patcher & patcher) { return std::make_unique<Mtof>(model, patcher); } Mtof::Mtof(model::Object const& model, Patcher& patcher) : Object(model, patcher) { } void Mtof::receive(size_t index, std::vector<tool::Atom> const& args) { if (index == 0 && !args.empty()) { if (args[0].isNumber()) { send(0, {440. * std::pow(2., (args[0].getFloat() - 69) / 12.)}); } else { warning("mtof inlet 1 doesn't understand " + args[0].getString()); } } } }}
2,103
C++
.cpp
48
37
90
0.481723
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,285
KiwiEngine_Gate.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_Gate.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_Gate.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // GATE // // ================================================================================ // void Gate::declare() { Factory::add<Gate>("gate", &Gate::create); } std::unique_ptr<Object> Gate::create(model::Object const& model, Patcher & patcher) { return std::make_unique<Gate>(model, patcher); } Gate::Gate(model::Object const& model, Patcher& patcher) : Object(model, patcher), m_opened_output(), m_num_outputs(model.getArguments()[0].getInt()) { std::vector<tool::Atom> const& args = model.getArguments(); if (args.size() > 1) { openOutput(args[1].getInt()); } } void Gate::openOutput(int output) { m_opened_output = std::max(0, std::min(output, static_cast<int>(m_num_outputs))); } void Gate::receive(size_t index, std::vector<tool::Atom> const& args) { if (args.size() > 0) { if (index == 0) { if (args[0].isBang()) { send(0, {static_cast<int>(m_opened_output)}); } else if (args[0].isNumber()) { openOutput(args[0].getInt()); } else { warning("gate inlet 1 receives only numbers"); } } else if(index == 1) { if (m_opened_output > 0) { send(m_opened_output - 1, args); } } } } }}
2,820
C++
.cpp
72
29.916667
90
0.458736
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,286
KiwiEngine_LineTilde.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_LineTilde.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_LineTilde.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi{ namespace engine { // ================================================================================ // // RAMP // // ================================================================================ // Ramp::Ramp(dsp::sample_t start) noexcept : m_current_value(start) , m_destination_value(start) { } void Ramp::setSampleRate(double sample_rate) noexcept { //! Note: this will only affect next value-time pairs. m_sr = sample_rate; } void Ramp::setEndOfRampCallback(std::function<void()> callback) { m_ramp_ended_callback = callback; } void Ramp::setValueDirect(dsp::sample_t new_value) noexcept { auto lock = std::unique_lock<std::mutex>(m_lock); reset(); m_current_value = m_destination_value = new_value; m_countdown = m_steps_to_destination = 0; m_step = 0.; } void Ramp::setValueTimePairs(std::vector<ValueTimePair> value_time_pairs) { auto lock = std::unique_lock<std::mutex>(m_lock); reset(); m_value_time_pairs.swap(value_time_pairs); m_valuetime_pairs_countdown = m_value_time_pairs.size(); } dsp::sample_t Ramp::getNextValue() noexcept { auto lock = std::unique_lock<std::mutex>(m_lock); if (m_countdown <= 0) { const auto value = m_destination_value; triggerNextRamp(); return value; } --m_countdown; m_current_value += m_step; return m_current_value; } dsp::sample_t Ramp::getValue() noexcept { return m_current_value; } void Ramp::triggerNextRamp() { if(m_valuetime_pairs_countdown > 0) { assert(m_valuetime_pairs_countdown <= m_value_time_pairs.size()); const size_t index = m_value_time_pairs.size() - m_valuetime_pairs_countdown; setNextValueTime(m_value_time_pairs[index]); --m_valuetime_pairs_countdown; m_should_notify_end = (m_valuetime_pairs_countdown == 0); } else if(m_should_notify_end && m_ramp_ended_callback) { m_ramp_ended_callback(); m_should_notify_end = false; } } void Ramp::setNextValueTime(ValueTimePair const& value_time) noexcept { m_countdown = m_steps_to_destination = std::floor(value_time.time_ms * 0.001 * m_sr); m_destination_value = value_time.value; if (m_countdown <= 0) { m_current_value = m_destination_value; m_step = 0.; } else { m_step = (m_destination_value - m_current_value) / (dsp::sample_t) m_countdown; } } void Ramp::reset() { m_value_time_pairs.clear(); m_valuetime_pairs_countdown = 0; m_destination_value = m_current_value; m_countdown = 0; m_should_notify_end = false; } // ================================================================================ // // LINE~ TASK // // ================================================================================ // class LineTilde::BangTask : public tool::Scheduler<>::Task { public: // methods BangTask(LineTilde& owner) : m_owner(owner) {} ~BangTask() = default; void execute() override { m_owner.send(1ul, {"bang"}); } private: // members LineTilde& m_owner; }; // ================================================================================ // // LINE~ // // ================================================================================ // void LineTilde::declare() { Factory::add<LineTilde>("line~", &LineTilde::create); } std::unique_ptr<Object> LineTilde::create(model::Object const& model, Patcher & patcher) { return std::make_unique<LineTilde>(model, patcher); } LineTilde::LineTilde(model::Object const& model, Patcher& patcher) : AudioObject(model, patcher) , m_bang_task(std::make_shared<BangTask>(*this)) , m_ramp(0.) { std::vector<tool::Atom> const& args = model.getArguments(); if (!args.empty() && args[0].isNumber()) { m_ramp.setValueDirect(args[0].getFloat()); } m_ramp.setEndOfRampCallback([this]{ getScheduler().defer(m_bang_task); }); } LineTilde::~LineTilde() { getScheduler().unschedule(m_bang_task); } std::vector<Ramp::ValueTimePair> LineTilde::parseAtomsAsValueTimePairs(std::vector<tool::Atom> const& atoms) const { std::vector<Ramp::ValueTimePair> value_time_pairs; for(size_t i = 0; i < atoms.size(); i += 2) { auto const& time_atom = atoms[i+1]; if(!time_atom.isNumber() || !atoms[i].isNumber()) { error("line~ only accepts value-time numbers"); return value_time_pairs; } if(time_atom.getFloat() < 0.) { error("line~ do not accepts negative ramp time"); return value_time_pairs; } Ramp::ValueTimePair pair { (dsp::sample_t) atoms[i].getFloat(), (dsp::sample_t) time_atom.getFloat() }; value_time_pairs.emplace_back(std::move(pair)); } return value_time_pairs; } void LineTilde::receive(size_t index, std::vector<tool::Atom> const& args) { if (!args.empty()) { if(args[0].isNumber()) { if(index == 0) { if(args.size() >= 2) { auto value_time_pairs = parseAtomsAsValueTimePairs(args); if(!value_time_pairs.empty()) { m_ramp.setValueTimePairs(value_time_pairs); } } else { if(!m_next_ramp_time_consumed) { Ramp::ValueTimePair pair { (dsp::sample_t) args[0].getFloat(), (dsp::sample_t) m_next_ramp_time_ms }; m_ramp.setValueTimePairs({std::move(pair)}); m_next_ramp_time_consumed = true; } else { m_ramp.setValueDirect(args[0].getFloat()); } } } else if(index == 1) { if (args[0].isNumber()) { m_next_ramp_time_ms = args[0].getFloat(); m_next_ramp_time_consumed = false; } } } else { warning("line~ inlet " + std::to_string(index + 1) + " parameter must be a number"); } /* //! @todo else if(args[0].isString()) { const auto str = args[0].getString(); if(str == "stop") { ; } else if(str == "pause") { ; } else if(str == "resume") { ; } } */ } } void LineTilde::prepare(PrepareInfo const& infos) { m_ramp.setSampleRate((double) infos.sample_rate); setPerformCallBack(this, &LineTilde::perform); } void LineTilde::perform(dsp::Buffer const&, dsp::Buffer& output) noexcept { size_t sampleframes = output[0ul].size(); dsp::sample_t* out = output[0ul].data(); while(sampleframes--) { *out++ = m_ramp.getNextValue(); } } }}
9,586
C++
.cpp
251
26.266932
100
0.460266
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,287
KiwiEngine_Less.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_Less.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_Less.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // OBJECT LESS // // ================================================================================ // void Less::declare() { Factory::add<Less>("<", &Less::create); } std::unique_ptr<Object> Less::create(model::Object const& model, Patcher & patcher) { return std::make_unique<Less>(model, patcher); } Less::Less(model::Object const& model, Patcher& patcher): Operator(model, patcher) { } double Less::compute(double lhs, double rhs) const { return lhs < rhs ? 1 : 0; } }}
1,751
C++
.cpp
37
42.405405
90
0.504192
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,288
KiwiEngine_Minus.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_Minus.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_Minus.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // OBJECT MINUS // // ================================================================================ // void Minus::declare() { Factory::add<Minus>("-", &Minus::create); } std::unique_ptr<Object> Minus::create(model::Object const& model, Patcher & patcher) { return std::make_unique<Minus>(model, patcher); } Minus::Minus(model::Object const& model, Patcher& patcher): Operator(model, patcher) { } double Minus::compute(double lhs, double rhs) const { return lhs - rhs; } }}
1,752
C++
.cpp
37
42.432432
90
0.508677
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,289
KiwiEngine_LessTilde.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_LessTilde.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_LessTilde.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // <~ // // ================================================================================ // void LessTilde::declare() { Factory::add<LessTilde>("<~", &LessTilde::create); } std::unique_ptr<Object> LessTilde::create(model::Object const& model, Patcher & patcher) { return std::make_unique<LessTilde>(model, patcher); } LessTilde::LessTilde(model::Object const& model, Patcher& patcher): OperatorTilde(model, patcher) { } void LessTilde::compute(dsp::sample_t & result, dsp::sample_t const& lhs, dsp::sample_t const& rhs) { result = lhs < rhs ? 1 : 0; } }}
1,848
C++
.cpp
37
45.027027
103
0.514431
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,290
KiwiEngine_MinusTilde.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_MinusTilde.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_MinusTilde.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // -~ // // ================================================================================ // void MinusTilde::declare() { Factory::add<MinusTilde>("-~", &MinusTilde::create); } std::unique_ptr<Object> MinusTilde::create(model::Object const& model, Patcher & patcher) { return std::make_unique<MinusTilde>(model, patcher); } MinusTilde::MinusTilde(model::Object const& model, Patcher& patcher): OperatorTilde(model, patcher) { } void MinusTilde::compute(dsp::sample_t & result, dsp::sample_t const& lhs, dsp::sample_t const& rhs) { result = lhs - rhs; } }}
1,849
C++
.cpp
37
45.054054
104
0.5181
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,291
KiwiEngine_TimesTilde.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_TimesTilde.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Factory.h> #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_TimesTilde.h> namespace kiwi { namespace engine { // ================================================================================ // // TIMES~ // // ================================================================================ // void TimesTilde::declare() { Factory::add<TimesTilde>("*~", &TimesTilde::create); } std::unique_ptr<Object> TimesTilde::create(model::Object const& model, Patcher & patcher) { return std::make_unique<TimesTilde>(model, patcher); } TimesTilde::TimesTilde(model::Object const& model, Patcher& patcher): OperatorTilde(model, patcher) { } void TimesTilde::compute(dsp::sample_t & result, dsp::sample_t const& lhs, dsp::sample_t const& rhs) { result = lhs * rhs; } }}
1,850
C++
.cpp
37
45.081081
104
0.520633
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,292
KiwiEngine_Bang.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_Bang.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiModel/KiwiModel_Objects/KiwiModel_Bang.h> #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_Bang.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // OBJECT BANG // // ================================================================================ // void Bang::declare() { Factory::add<Bang>("bang", &Bang::create); } std::unique_ptr<Object> Bang::create(model::Object const& model, Patcher & patcher) { return std::make_unique<Bang>(model, patcher); } Bang::Bang(model::Object const& model, Patcher & patcher) : Object(model, patcher) , m_trigger_signal(model.getSignal<>(model::Bang::Signal::TriggerBang)) , m_flash_signal(model.getSignal<>(model::Bang::Signal::FlashBang)) , m_connection(m_trigger_signal.connect(std::bind(&Bang::signalTriggered, this))) { } Bang::~Bang() { } void Bang::signalTriggered() { defer([this]() { send(0, {"bang"}); }); } void Bang::receive(size_t index, std::vector<tool::Atom> const& args) { if (index == 0 && !args.empty()) { if(args[0].getString() == "set") { m_flash_signal(); } else { m_trigger_signal(); } } } }}
2,441
C++
.cpp
61
33.295082
90
0.502582
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,293
KiwiEngine_OscTilde.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_OscTilde.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_OscTilde.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // OSC~ // // ================================================================================ // void OscTilde::declare() { Factory::add<OscTilde>("osc~", &OscTilde::create); } std::unique_ptr<Object> OscTilde::create(model::Object const& model, Patcher & patcher) { return std::make_unique<OscTilde>(model, patcher); } OscTilde::OscTilde(model::Object const& model, Patcher& patcher): AudioObject(model, patcher) { std::vector<tool::Atom> const& args = model.getArguments(); if (!args.empty() && args[0].isNumber()) { setFrequency(args[0].getFloat()); } } void OscTilde::setFrequency(dsp::sample_t const& freq) noexcept { m_freq = freq; } void OscTilde::setSampleRate(dsp::sample_t const& sample_rate) { m_sr = sample_rate; } void OscTilde::setOffset(dsp::sample_t const& offset) noexcept { m_offset = fmodf(offset, 1.f); } void OscTilde::receive(size_t index, std::vector<tool::Atom> const& args) { if (index == 0) { if (args[0].isNumber()) { setFrequency(args[0].getFloat()); } else { warning("osc~ inlet 1 doesn't understanc [" + args[0].getString() + "]"); } } else if(index == 1) { if (args[0].isNumber()) { setOffset(args[0].getFloat()); } else { warning("osc~ inlet 2 doesn't understand [" + args[0].getString() + "]"); } } } void OscTilde::prepare(PrepareInfo const& infos) { setSampleRate(static_cast<dsp::sample_t>(infos.sample_rate)); if (infos.inputs[0] && infos.inputs[1]) { setPerformCallBack(this, &OscTilde::performPhaseAndFreq); } else if(infos.inputs[0]) { setPerformCallBack(this, &OscTilde::performFreq); } else if(infos.inputs[1]) { setPerformCallBack(this, &OscTilde::performPhase); } else { setPerformCallBack(this, &OscTilde::performValue); } } void OscTilde::performValue(dsp::Buffer const& input, dsp::Buffer& output) noexcept { dsp::sample_t *sig_data = output[0ul].data(); size_t sample_index = output[0ul].size(); dsp::sample_t const time_inc = m_freq/m_sr; dsp::sample_t const offset = m_offset; while(sample_index--) { *sig_data++ = std::cos(2.f * dsp::pi * (m_time + offset)); m_time += time_inc; } m_time = fmodf(m_time, 1.f); } void OscTilde::performFreq(dsp::Buffer const& input, dsp::Buffer& output) noexcept { size_t sample_index = output[0ul].size(); dsp::sample_t* output_sig = output[0ul].data(); dsp::sample_t const* freq = input[0ul].data(); dsp::sample_t const offset = m_offset; while(sample_index--) { *output_sig++ = std::cos(2.f *dsp::pi * (m_time + offset)); m_time += (*freq++ / m_sr); } m_time = fmodf(m_time, 1.f); } void OscTilde::performPhase(dsp::Buffer const& input, dsp::Buffer& output) noexcept { dsp::sample_t* output_sig = output[0ul].data(); size_t sample_index = output[0ul].size(); dsp::sample_t const* phase = input[1ul].data(); dsp::sample_t const time_inc = m_freq/m_sr; while(sample_index--) { *output_sig++ = std::cos(2.f * dsp::pi * (m_time + fmodf(*phase++, 1.f))); m_time += time_inc; } m_time = fmodf(m_time, 1.f); } void OscTilde::performPhaseAndFreq(dsp::Buffer const& input, dsp::Buffer& output) noexcept { size_t sample_index = output[0].size(); dsp::sample_t* output_sig = output[0].data(); dsp::sample_t const* freq = input[0].data(); dsp::sample_t const* phase = input[1].data(); while(sample_index--) { *output_sig++ = std::cos(2.f * dsp::pi * (m_time + fmodf(*phase++, 1.f))); m_time += (*freq++ / m_sr); } m_time = fmodf(m_time, 1.f); } }}
5,657
C++
.cpp
147
29.380952
94
0.515742
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,294
KiwiEngine_Operator.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_Operator.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_Operator.h> namespace kiwi { namespace engine { // ================================================================================ // // OBJECT OPERATOR // // ================================================================================ // Operator::Operator(model::Object const& model, Patcher& patcher): Object(model, patcher), m_lhs(), m_rhs() { std::vector<tool::Atom> const& args = model.getArguments(); m_lhs = 0.; if(!args.empty() && args[0].isNumber()) { m_rhs = args[0].getFloat(); } } void Operator::receive(size_t index, std::vector<tool::Atom> const& args) { if(!args.empty()) { if(index == 0) { if (args[0].isNumber()) { m_lhs = args[0].getFloat(); bang(); } else if(args[0].isBang()) { bang(); } else { warning("operator inlet 1 parameter must be a number or bang"); } } else if(index == 1) { if (args[0].isNumber()) { m_rhs = args[0].getFloat(); } else { warning("operator inlet 2 parameter must be a number"); } } } } void Operator::bang() { send(0, {compute(m_lhs, m_rhs)}); } }}
2,608
C++
.cpp
69
27.304348
90
0.419733
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,295
KiwiEngine_Metro.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_Metro.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_Metro.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // OBJECT METRO // // ================================================================================ // void Metro::declare() { Factory::add<Metro>("metro", &Metro::create); } std::unique_ptr<Object> Metro::create(model::Object const& model, Patcher & patcher) { return std::make_unique<Metro>(model, patcher); } Metro::Metro(model::Object const& model, Patcher& patcher): engine::Object(model, patcher), m_period(std::chrono::milliseconds(1000)), m_task(new tool::Scheduler<>::CallBack(std::bind(&Metro::timerCallBack, this))) { std::vector<tool::Atom> const& args = model.getArguments(); if(!args.empty()) { m_period = std::chrono::milliseconds(args[0].getInt()); } } Metro::~Metro() { getScheduler().unschedule(m_task); } void Metro::receive(size_t index, std::vector<tool::Atom> const& args) { if (!args.empty()) { if (index == 0) { if (args[0].isNumber()) { if (static_cast<bool>(args[0].getFloat())) { getScheduler().unschedule(m_task); timerCallBack(); } else { getScheduler().unschedule(m_task); } } else { warning("metro inlet 1 only take numbers"); } } else if(index == 1) { if (args[0].isNumber()) { m_period = std::chrono::milliseconds(args[0].getInt()); } else { warning("metro inlet 2 doesn't understand [" + args[0].getString() + "]"); } } } } void Metro::timerCallBack() { send(0, {"bang"}); getScheduler().schedule(m_task, m_period); } }}
3,279
C++
.cpp
85
28.270588
94
0.455995
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,296
KiwiEngine_GateTilde.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_GateTilde.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_GateTilde.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // GATE~ // // ================================================================================ // void GateTilde::declare() { Factory::add<GateTilde>("gate~", &GateTilde::create); } std::unique_ptr<Object> GateTilde::create(model::Object const& model, Patcher & patcher) { return std::make_unique<GateTilde>(model, patcher); } GateTilde::GateTilde(model::Object const& model, Patcher& patcher) : AudioObject(model, patcher), m_opened_output(), m_num_outputs(model.getArguments()[0].getInt()) { std::vector<tool::Atom> const& args = model.getArguments(); if (args.size() > 1) { openOutput(args[1].getInt()); } } void GateTilde::openOutput(int output) { m_opened_output = std::max(0, std::min(output, static_cast<int>(m_num_outputs))); } void GateTilde::receive(size_t index, std::vector<tool::Atom> const& args) { if (args.size() > 0) { if (index == 0) { if (args[0].isNumber()) { openOutput(args[0].getInt()); } else { warning("gate~ inlet 1 receives only numbers"); } } } } void GateTilde::prepare(PrepareInfo const& infos) { if (infos.inputs[0]) { setPerformCallBack(this, &GateTilde::performSig); } else { setPerformCallBack(this, &GateTilde::performValue); } } void GateTilde::performValue(dsp::Buffer const& input, dsp::Buffer& output) noexcept { size_t output_number = output.getNumberOfChannels(); for(size_t outlet = 0; outlet < output_number; ++outlet) { output[outlet].fill(0); } if (m_opened_output != 0) { output[m_opened_output - 1].copy(input[1]); } } void GateTilde::performSig(dsp::Buffer const& input, dsp::Buffer& output) noexcept { dsp::sample_t const * route_signal = input[0].data(); dsp::sample_t const * input_signal = input[1].data(); size_t sample_index = input[0ul].size(); size_t output_number = output.getNumberOfChannels(); size_t opened_output = 0; for(size_t outlet = 0; outlet < output_number; ++outlet) { output[outlet].fill(0); } while(sample_index--) { opened_output = std::max((size_t) 0, std::min(m_num_outputs, (size_t) route_signal[sample_index])); if (opened_output) { output[opened_output - 1][sample_index] = input_signal[sample_index]; } } } }}
4,066
C++
.cpp
104
30.057692
111
0.514717
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,297
KiwiEngine_Slider.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_Slider.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <functional> #include <algorithm> #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_Slider.h> #include <KiwiEngine/KiwiEngine_Factory.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Slider.h> namespace kiwi { namespace engine { // ================================================================================ // // OBJECT SLIDER // // ================================================================================ // void Slider::declare() { Factory::add<Slider>("slider", &Slider::create); } std::unique_ptr<Object> Slider::create(model::Object const& model, Patcher& patcher) { return std::make_unique<Slider>(model, patcher); } Slider::Slider(model::Object const& object_model, Patcher& patcher): Object(object_model, patcher), m_value(object_model.getParameter("value")[0].getFloat()), m_connection(object_model.getSignal<>(model::Slider::Signal::OutputValue) .connect(std::bind(&Slider::outputValue, this))) { } Slider::~Slider() { } void Slider::parameterChanged(std::string const& name, tool::Parameter const& parameter) { if (name == "value") { m_value = parameter[0].getFloat(); } } void Slider::outputValue() { defer([this]() { send(0, {m_value}); }); } void Slider::receive(size_t index, std::vector<tool::Atom> const& args) { if (index == 0 && !args.empty()) { if (args[0].isNumber()) { send(0, {args[0].getFloat()}); setParameter("value", tool::Parameter(tool::Parameter::Type::Float, {args[0].getFloat()})); } else if(args[0].isString() && args[0].getString() == "set") { if (args.size() >= 1 && args[1].isNumber()) { setParameter("value", tool::Parameter(tool::Parameter::Type::Float, {args[1].getFloat()})); } } else if (args[0].isBang()) { send(0, {m_value}); } else { warning("slider inlet 1 doesn't understand [" + args[0].getString() + "]"); } } } }}
3,285
C++
.cpp
82
31.829268
111
0.501594
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,298
KiwiEngine_Toggle.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_Toggle.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiModel/KiwiModel_Objects/KiwiModel_Toggle.h> #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_Toggle.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // OBJECT TOGGLE // // ================================================================================ // void Toggle::declare() { Factory::add<Toggle>("toggle", &Toggle::create); } std::unique_ptr<Object> Toggle::create(model::Object const& model, Patcher & patcher) { return std::make_unique<Toggle>(model, patcher); } Toggle::Toggle(model::Object const& model, Patcher& patcher): Object(model, patcher), m_connection(model.getSignal<>(model::Toggle::Signal::OutputValue) .connect(std::bind(&Toggle::outputValue, this))), m_is_on(false) { } Toggle::~Toggle() { } void Toggle::parameterChanged(std::string const& name, tool::Parameter const& param) { if (name == "value") { m_is_on = static_cast<bool>(param[0].getInt()); } } void Toggle::outputValue() { defer([this]() { send(0, {m_is_on}); }); } void Toggle::receive(size_t index, std::vector<tool::Atom> const& args) { if (!args.empty()) { if (index == 0) { if(args[0].isString()) { if (args[0].isBang()) { send(0, {!m_is_on}); setParameter("value", tool::Parameter(tool::Parameter::Type::Int, {!m_is_on})); } else if(args.size() == 2 && args[0].getString() == "set") { if (args[1].isNumber()) { if (args[1].getFloat() != 0) { setParameter("value", tool::Parameter(tool::Parameter::Type::Int, {1})); } else { setParameter("value", tool::Parameter(tool::Parameter::Type::Int, {0})); } } else { warning("toggle set requires number value"); } } else { warning("toggle doesn't understand message [" + args[0].getString() + "]"); } } else if(args[0].isNumber()) { if (args[0].getFloat() != 0) { send(0, {true}); setParameter("value", tool::Parameter(tool::Parameter::Type::Int, {1})); } else { send(0, {false}); setParameter("value", tool::Parameter(tool::Parameter::Type::Int, {0})); } } } } } }}
4,268
C++
.cpp
106
26.698113
104
0.415508
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,299
KiwiEngine_Float.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_Float.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_Float.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // FLOAT // // ================================================================================ // void Float::declare() { Factory::add<Float>("float", &Float::create); } std::unique_ptr<Object> Float::create(model::Object const& model, Patcher & patcher) { return std::make_unique<Float>(model, patcher); } Float::Float(model::Object const& model, Patcher& patcher): Object(model, patcher), m_stored_value() { std::vector<tool::Atom> const& args = model.getArguments(); if (args.size() > 0 && args[0].isNumber()) { m_stored_value = args[0].getFloat(); } } void Float::receive(size_t index, std::vector<tool::Atom> const& args) { if (!args.empty()) { if (index == 0) { if (args[0].isNumber()) { m_stored_value = args[0].getFloat(); send(0, {m_stored_value}); } else if(args[0].isBang()) { send(0, {m_stored_value}); } else { warning("float inlet 1 only understand numbers"); } } else if(index == 1) { if (args[0].isNumber()) { m_stored_value = args[0].getFloat(); } else { warning("float inlet 2 only understand numbers"); } } } } }}
2,822
C++
.cpp
72
29.152778
90
0.444362
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,300
KiwiEngine_PlusTilde.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_PlusTilde.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_PlusTilde.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // PLUS~ // // ================================================================================ // void PlusTilde::declare() { Factory::add<PlusTilde>("+~", &PlusTilde::create); } std::unique_ptr<Object> PlusTilde::create(model::Object const& model, Patcher & patcher) { return std::make_unique<PlusTilde>(model, patcher); } PlusTilde::PlusTilde(model::Object const& model, Patcher& patcher): OperatorTilde(model, patcher) { } void PlusTilde::compute(dsp::sample_t & result, dsp::sample_t const& lhs, dsp::sample_t const& rhs) { result = lhs + rhs; } }}
1,840
C++
.cpp
37
44.810811
103
0.517908
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,301
KiwiEngine_Pack.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_Pack.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_Pack.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // PACK // // ================================================================================ // void Pack::declare() { Factory::add<Pack>("pack", &Pack::create); } std::unique_ptr<Object> Pack::create(model::Object const& model, Patcher & patcher) { return std::make_unique<Pack>(model, patcher); } Pack::Pack(model::Object const& model, Patcher& patcher) : Object(model, patcher), m_list(model.getArguments()) { } void Pack::output_list() { send(0, m_list); } void Pack::setElement(size_t index, tool::Atom const& atom) { switch (m_list[index].getType()) { case tool::Atom::Type::Float: { m_list[index] = atom.getFloat(); break; } case tool::Atom::Type::Int: { m_list[index] = atom.getInt(); break; } case tool::Atom::Type::String: { m_list[index] = atom.getString(); break; } default: break; } } void Pack::receive(size_t index, std::vector<tool::Atom> const& args) { if (!args.empty()) { if (index == 0) { if (args[0].isBang()) { output_list(); } else if (args[0].isString() && args[0].getString() == "set" && args.size() > 1) { setElement(index, args[1]); } else { setElement(index, args[0]); output_list(); } } else { if (args[0].isString() && args[0].getString() == "set" && args.size() > 1) { setElement(index, args[1]); } else { setElement(index, args[0]); } } } } }}
3,385
C++
.cpp
97
23.896907
90
0.413548
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,302
KiwiEngine_Times.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_Times.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_Times.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine{ // ================================================================================ // // OBJECT TIMES // // ================================================================================ // void Times::declare() { Factory::add<Times>("*", &Times::create); } std::unique_ptr<Object> Times::create(model::Object const& model, Patcher & patcher) { return std::make_unique<Times>(model, patcher); } Times::Times(model::Object const& model, Patcher& patcher): Operator(model, patcher) { } double Times::compute(double lhs, double rhs) const { return lhs * rhs; } }}
1,751
C++
.cpp
37
42.405405
90
0.508982
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,303
KiwiEngine_DifferentTilde.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_DifferentTilde.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_DifferentTilde.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // !=~ // // ================================================================================ // void DifferentTilde::declare() { Factory::add<DifferentTilde>("!=~", &DifferentTilde::create); } std::unique_ptr<Object> DifferentTilde::create(model::Object const& model, Patcher & patcher) { return std::make_unique<DifferentTilde>(model, patcher); } DifferentTilde::DifferentTilde(model::Object const& model, Patcher& patcher): OperatorTilde(model, patcher) { } void DifferentTilde::compute(dsp::sample_t & result, dsp::sample_t const& lhs, dsp::sample_t const& rhs) { result = lhs != rhs ? 1. : 0.; } }}
1,897
C++
.cpp
37
46.351351
108
0.52533
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,304
KiwiEngine_EqualTilde.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_EqualTilde.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_EqualTilde.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // ==~ // // ================================================================================ // void EqualTilde::declare() { Factory::add<EqualTilde>("==~", &EqualTilde::create); } std::unique_ptr<Object> EqualTilde::create(model::Object const& model, Patcher & patcher) { return std::make_unique<EqualTilde>(model, patcher); } EqualTilde::EqualTilde(model::Object const& model, Patcher& patcher): OperatorTilde(model, patcher) { } void EqualTilde::compute(dsp::sample_t & result, dsp::sample_t const& lhs, dsp::sample_t const& rhs) { result = lhs == rhs ? 1 : 0; } }}
1,860
C++
.cpp
37
45.351351
104
0.51602
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,305
KiwiEngine_Different.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_Different.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_Different.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // OBJECT DIFFERENT // // ================================================================================ // void Different::declare() { Factory::add<Different>("!=", &Different::create); } std::unique_ptr<Object> Different::create(model::Object const& model, Patcher & patcher) { return std::make_unique<Different>(model, patcher); } Different::Different(model::Object const& model, Patcher& patcher): Operator(model, patcher) { } double Different::compute(double lhs, double rhs) const { return lhs != rhs ? 1 : 0; } }}
1,799
C++
.cpp
37
43.702703
92
0.519208
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,306
KiwiEngine_OSCReceive.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_OSCReceive.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Factory.h> #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_OSCReceive.h> namespace kiwi { namespace engine { // ================================================================================ // // OSC.receive // // ================================================================================ // void OSCReceive::declare() { Factory::add<OSCReceive>("OSC.receive", &OSCReceive::create); } std::unique_ptr<Object> OSCReceive::create(model::Object const& model, Patcher& patcher) { return std::make_unique<OSCReceive>(model, patcher); } OSCReceive::OSCReceive(model::Object const& model, Patcher& patcher) : Object(model, patcher) { const auto& args = model.getArguments(); if(args.size() >= 1 && args[0].isInt()) { setPort(args[0].getInt()); } } void OSCReceive::receive(size_t index, std::vector<tool::Atom> const& args) { if(index == 0 && args.size() >= 2 && args[0].getString() == "port" && args[1].isInt()) { setPort(args[1].getInt()); } } bool OSCReceive::setPort(int new_port) { removeListener(this); disconnect(); if (connect(new_port)) { addListener(this); return true; } error("OSC.receive: can't connect to port " + std::to_string(new_port)); return false; } tool::Atom OSCReceive::OSCArgToAtom(juce::OSCArgument const& arg) { if (arg.isFloat32()) return arg.getFloat32(); if (arg.isInt32()) return arg.getInt32(); if (arg.isString()) return arg.getString().toStdString(); return {"error"}; } void OSCReceive::oscMessageReceived(juce::OSCMessage const& msg) { std::vector<tool::Atom> msg_out {msg.getAddressPattern().toString().toStdString()}; for(auto const& arg : msg) { msg_out.emplace_back(OSCArgToAtom(arg)); } defer([this, msg_out = std::move(msg_out)]() { send(0, msg_out); }); } void OSCReceive::oscBundleReceived(juce::OSCBundle const& bundle) { for (auto& element : bundle) { if(element.isMessage()) { oscMessageReceived(element.getMessage()); } else if (element.isBundle()) { oscBundleReceived(element.getBundle()); } } } }}
3,499
C++
.cpp
87
32.218391
94
0.527443
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,307
KiwiEngine_Send.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_Send.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_Send.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // SEND // // ================================================================================ // void Send::declare() { Factory::add<Send>("send", &Send::create); } std::unique_ptr<Object> Send::create(model::Object const& model, Patcher & patcher) { return std::make_unique<Send>(model, patcher); } Send::Send(model::Object const& model, Patcher& patcher) : Object(model, patcher), m_beacon(patcher.getBeacon(model.getArguments()[0].getString())) { } void Send::receive(size_t index, std::vector<tool::Atom> const& args) { if (index == 0 && !args.empty()) { m_beacon.dispatch(args); } } }}
1,906
C++
.cpp
41
41.170732
90
0.505766
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,308
KiwiEngine_SfRecordTilde.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_SfRecordTilde.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_SfRecordTilde.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // SOUNDFILE RECORDER // // ================================================================================ // //! @note the SoundFileRecorder class is based on the juce Demo App SoundFileRecorder::SoundFileRecorder() : m_background_thread("SoundFile Recorder Thread") { m_background_thread.startThread(); } SoundFileRecorder::~SoundFileRecorder() { stop(); } bool SoundFileRecorder::start(const juce::File& file) { stop(); if (m_sample_rate <= 0) return false; // abort // Create an OutputStream to write to our destination file... file.deleteFile(); std::unique_ptr<juce::FileOutputStream> file_stream (file.createOutputStream()); if (file_stream == nullptr) return false; // abort // Now create a WAV writer object that writes to our output stream... juce::WavAudioFormat wav_format; const int bit_per_sample = 16; const int quality_option = 0; const juce::StringPairArray metadata {}; const int nchan = getNumberOfChannels(); auto channel_set = juce::AudioChannelSet::canonicalChannelSet(nchan); if(!wav_format.isChannelLayoutSupported(channel_set)) { std::cerr << "channel layout not supported\n"; return false; } auto* writer = wav_format.createWriterFor(file_stream.get(), m_sample_rate, channel_set, bit_per_sample, metadata, quality_option); if (writer == nullptr) return false; // abort // (passes responsibility for deleting the stream to the writer object that is now using it) file_stream.release(); // Now we'll create one of these helper objects which will act as a FIFO buffer, and will // write the data to disk on our background thread. m_threaded_writer.reset(new juce::AudioFormatWriter::ThreadedWriter(writer, m_background_thread, 32768)); // And now, swap over our active writer pointer so that the audio callback will start using it.. const std::lock_guard<std::mutex> lock (m_writer_lock); m_active_writer = m_threaded_writer.get(); return true; } void SoundFileRecorder::stop() { // First, clear this pointer to stop the audio callback from using our writer object.. { const std::lock_guard<std::mutex> lock (m_writer_lock); m_active_writer = nullptr; } // Now we can delete the writer object. It's done in this order because the deletion could // take a little time while remaining data gets flushed to disk, so it's best to avoid blocking // the audio callback while this happens. m_threaded_writer.reset(); } bool SoundFileRecorder::isRecording() const { return m_active_writer != nullptr; } void SoundFileRecorder::setNumberOfChannels(size_t channels) { m_channels = channels > 0 ? channels : m_channels; m_buffer_ref.resize(m_channels); } size_t SoundFileRecorder::getNumberOfChannels() const { return m_channels; } void SoundFileRecorder::prepare(double sample_rate, size_t vector_size) { m_sample_rate = sample_rate; m_vector_size = vector_size; } bool SoundFileRecorder::write(dsp::Buffer const& input) { const std::lock_guard<std::mutex> lock (m_writer_lock); if (m_active_writer != nullptr) { const auto channels = input.getNumberOfChannels(); for(auto channel = 0; channel < channels; ++channel) { m_buffer_ref[channel] = input[channel].data(); } return m_active_writer->write(m_buffer_ref.data(), m_vector_size); } return false; } // ================================================================================ // // SFRECORD~ // // ================================================================================ // void SfRecordTilde::declare() { Factory::add<SfRecordTilde>("sf.record~", &SfRecordTilde::create); } std::unique_ptr<Object> SfRecordTilde::create(model::Object const& model, Patcher & patcher) { return std::make_unique<SfRecordTilde>(model, patcher); } SfRecordTilde::SfRecordTilde(model::Object const& model, Patcher& patcher) : AudioObject(model, patcher) { m_recorder.setNumberOfChannels(getNumberOfInputs()); } SfRecordTilde::~SfRecordTilde() { closeFileDialog(); } void SfRecordTilde::receive(size_t index, std::vector<tool::Atom> const& args) { if (!args.empty() && index == 0) { if (args[0].isString() && args[0].getString() == "open") { if(args.size() > 1) { if(args[1].isString()) { openFile(juce::File(args[1].getString())); } else { error("sf.record~: bad argument for open"); } } else { openFileDialog(); } } else if (args[0].isNumber()) { auto num = args[0].getInt(); if(num == 1) record(); else if(num == 0) stop(); else warning("sf.record~: use 1 to start recording, 0 to stop"); } else if (args[0].getString() == "record") { double duration_ms = -1; if(args.size() > 1 && args[1].isNumber()) { duration_ms = args[1].getFloat(); } record(duration_ms); } } } bool SfRecordTilde::openFile(juce::File file) { const auto path = file.getFullPathName(); if(!juce::File::isAbsolutePath(path)) { warning("sf.record~: is not an absolute path"); return false; } if(file.isDirectory()) { warning("sf.record~: invalid file path"); return false; } // is a file if(!file.hasWriteAccess()) { warning("sf.record~: no write access to file \"" + path.toStdString() + "\""); return false; } // that has write access if(!file.hasFileExtension(m_extension)) { file = file.withFileExtension(m_extension); } // and valid extension if(!file.exists()) { if(!file.create()) { warning("sf.record~: can't create file \"" + path.toStdString() + "\""); return false; } } else { warning("sf.record~: file will be overwritten \"" + path.toStdString() + "\""); } // that really exist. m_file_to_write = path; return true; } void SfRecordTilde::openFileDialog() { const auto default_dir = juce::File::getSpecialLocation(juce::File::userMusicDirectory); auto dir = (!m_file_to_write.getFullPathName().isEmpty() ? m_file_to_write.getParentDirectory() : default_dir); if (dir.createDirectory().wasOk()) { dir = dir.getChildFile("Untitled.wav"); } m_file_chooser = std::make_unique<juce::FileChooser>("Choose a file to save...", dir, "*.wav;", true); deferMain([this, fc = m_file_chooser.get()]() { const int fc_flags = (juce::FileBrowserComponent::saveMode | juce::FileBrowserComponent::canSelectFiles); fc->launchAsync(fc_flags, [this](juce::FileChooser const& chooser) { auto file = chooser.getResult(); if(file.getFullPathName().isNotEmpty()) { openFile(file); } }); }); } void SfRecordTilde::closeFileDialog() { deferMain([this]() { m_file_chooser.reset(); }); } void SfRecordTilde::stop() { defer([this]{ m_writer_count = 0; m_recorder.stop(); }); } void SfRecordTilde::record(double duration_ms) { m_writer_count = 0; m_time_to_stop_ms = duration_ms > 0 ? duration_ms : -1; m_recorder.start(m_file_to_write); m_file_to_write = juce::File(); // consumed } void SfRecordTilde::perform(dsp::Buffer const& input, dsp::Buffer& output) noexcept { if(m_recorder.write(input)) { size_t sampleframe = output[0].size(); dsp::sample_t* output_sig = output[0].data(); while(sampleframe--) { *output_sig++ = (m_writer_count++ / m_sample_rate * 1000.); } if((m_time_to_stop_ms > 0) && m_time_to_stop_ms < output_sig[sampleframe-1]) { // defered stop stop(); m_time_to_stop_ms = 0; } } else { output[0].fill(m_writer_count / m_sample_rate * 1000.); } } void SfRecordTilde::prepare(dsp::Processor::PrepareInfo const& infos) { m_sample_rate = infos.sample_rate; m_recorder.prepare(infos.sample_rate, infos.vector_size); setPerformCallBack(this, &SfRecordTilde::perform); } void SfRecordTilde::release() { m_sample_rate = 0.; } }}
11,982
C++
.cpp
299
27.294314
104
0.500045
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,309
KiwiEngine_Clip.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_Clip.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_Clip.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // CLIP~ // // ================================================================================ // void Clip::declare() { Factory::add<Clip>("clip", &Clip::create); } std::unique_ptr<Object> Clip::create(model::Object const& model, Patcher & patcher) { return std::make_unique<Clip>(model, patcher); } Clip::Clip(model::Object const& model, Patcher& patcher): Object(model, patcher), m_minimum(0.), m_maximum(0.) { std::vector<tool::Atom> const& args = model.getArguments(); if (args.size() > 0) { m_minimum = args[0].getFloat(); if (args.size() > 1) { m_maximum = args[1].getFloat(); } } } void Clip::receive(size_t index, std::vector<tool::Atom> const& args) { if (!args.empty()) { if (index == 0) { if (args[0].isNumber()) { send(0, {std::max(m_minimum, std::min(args[0].getFloat(), m_maximum))}); } else { warning("clip inlet 1 only takes numbers"); } } else if (index == 1) { if (args[0].isNumber()) { m_minimum = args[0].getFloat(); if (m_minimum > m_maximum) { warning("clip minimum is higher than maximum"); } } else { warning("clip inlet 2 only takes numbers"); } } else if(index == 2) { if (args[0].isNumber()) { m_maximum = args[0].getFloat(); if (m_minimum > m_maximum) { warning("clip maximum is lower than minimum"); } } else { warning("clip inlet 3 only takes numbers"); } } } } }}
3,441
C++
.cpp
91
25.736264
92
0.417616
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,310
KiwiEngine_DelaySimpleTilde.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_DelaySimpleTilde.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <cmath> #include <atomic> #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_DelaySimpleTilde.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // DELAYSIMPLETILDE // // ================================================================================ // void DelaySimpleTilde::declare() { Factory::add<DelaySimpleTilde>("delaysimple~", &DelaySimpleTilde::create); } std::unique_ptr<Object> DelaySimpleTilde::create(model::Object const& model, Patcher & patcher) { return std::make_unique<DelaySimpleTilde>(model, patcher); } DelaySimpleTilde::DelaySimpleTilde(model::Object const& model, Patcher& patcher): AudioObject(model, patcher), tool::Scheduler<>::Timer(patcher.getScheduler()), m_circular_buffer(), m_reinject_signal(), m_max_delay(60.), m_delay(1.), m_reinject_level(0.), m_sr(0.), m_pool() { std::vector<tool::Atom> const& args = model.getArguments(); if (args.size() > 0) { m_delay = (args[0].getFloat() / 1000.); } if (args.size() > 1) { m_reinject_level = std::max(0., std::min(args[1].getFloat(), 1.)); } std::shared_ptr<CircularBuffer> buffer(new CircularBuffer(0., 0., 0.)); m_pool.add(buffer); store(buffer); startTimer(std::chrono::milliseconds(1000)); } DelaySimpleTilde::~DelaySimpleTilde() { stopTimer(); timerCallBack(); } void DelaySimpleTilde::timerCallBack() { m_pool.clear(); } std::shared_ptr<DelaySimpleTilde::CircularBuffer> DelaySimpleTilde::load() { std::shared_ptr<CircularBuffer> load_buffer; { std::lock_guard<std::mutex> lock(m_mutex); load_buffer = m_circular_buffer; } return load_buffer; } void DelaySimpleTilde::store(std::shared_ptr<CircularBuffer> new_buffer) { std::lock_guard<std::mutex> lock(m_mutex); m_circular_buffer = new_buffer; } void DelaySimpleTilde::receive(size_t index, std::vector<tool::Atom> const& args) { if (index == 0 && args[0].isString()) { if (args[0].isString() && args[0].getString() == "clear") { std::shared_ptr<CircularBuffer> new_buffer(new CircularBuffer(m_circular_buffer->size(), m_circular_buffer->size(), 0.)); m_pool.add(new_buffer); store(new_buffer); } else { warning("delaysimple~ inlet 1 doesn't understand + [" + args[0].getString() + "]"); } } if (index == 1) { if (args[0].isNumber()) { m_delay.store(args[0].getFloat() / 1000.); } else { warning("delaysimple~ inlet 2 requires a number"); } } else if(index == 2) { if (args[0].isNumber()) { m_reinject_level.store(std::max(0., std::min(1., args[0].getFloat()))); } else { warning("delaysimple~ inlet 3 requires a number"); } } } dsp::sample_t DelaySimpleTilde::cubicInterpolate(float const& x, float const& y0, float const& y1, float const& y2, float const& y3) { return y1 + 0.5 * x * (y2 - y0 + x * (2.0 * y0 - 5.0 * y1 + 4.0 * y2 - y3 + x * (3.0 * (y1 - y2) + y3 - y0))); } void DelaySimpleTilde::perform(dsp::Buffer const& input, dsp::Buffer& output) noexcept { std::shared_ptr<CircularBuffer> buffer = load(); size_t buffer_size = input[0].size(); for (int i = 0; i < buffer_size; ++i) { buffer->push_back(input[0][i] + m_reinject_signal->operator[](i)); } float delay = std::max<float>(1. / m_sr, std::min<float>(m_delay.load(), m_max_delay)); float offset = buffer->size() - (delay * m_sr) - (buffer_size - 1); size_t offset_floor = std::floor(offset); float decimal_part = offset - offset_floor; for(int i = 0; i < buffer_size; ++i) { output[0][i] = cubicInterpolate(decimal_part, m_circular_buffer->operator[](offset_floor - 1), m_circular_buffer->operator[](offset_floor), m_circular_buffer->operator[](offset_floor + 1), m_circular_buffer->operator[](offset_floor + 2)); m_reinject_signal->operator[](i) = m_reinject_level.load() * output[0][i]; ++offset_floor; } } void DelaySimpleTilde::performDelay(dsp::Buffer const& input, dsp::Buffer& output) noexcept { std::shared_ptr<CircularBuffer> buffer = load(); size_t buffer_size = input[0].size(); for (int i = 0; i < buffer_size; ++i) { buffer->push_back(input[0][i] + m_reinject_signal->operator[](i)); } for(int i = 0; i < buffer_size; ++i) { float delay = std::max<float>(1. / m_sr, std::min<float>(input[1][i] / 1000., m_max_delay)); float offset = buffer->size() - (delay * m_sr) - (buffer_size - 1) + i; size_t offset_floor = std::floor(offset); output[0][i] = cubicInterpolate(offset - offset_floor, buffer->operator[](offset_floor - 1), buffer->operator[](offset_floor), buffer->operator[](offset_floor + 1), buffer->operator[](offset_floor + 2)); m_reinject_signal->operator[](i) = m_reinject_level.load() * output[0][i]; } } void DelaySimpleTilde::prepare(dsp::Processor::PrepareInfo const& infos) { m_sr = infos.sample_rate; size_t vector_size = infos.vector_size; size_t buffer_size = std::ceil(m_max_delay * m_sr) + 1 + vector_size; std::shared_ptr<CircularBuffer> new_buffer(new CircularBuffer(buffer_size, buffer_size, 0.)); m_pool.add(new_buffer); store(new_buffer); m_reinject_signal.reset(new dsp::Signal(vector_size)); if (infos.inputs.size() > 1 && infos.inputs[1]) { setPerformCallBack(this, &DelaySimpleTilde::performDelay); } else { setPerformCallBack(this, &DelaySimpleTilde::perform); } } // ================================================================================ // // RELEASEPOOL // // ================================================================================ // DelaySimpleTilde::ReleasePool::ReleasePool(): m_pool(), m_mutex() { } DelaySimpleTilde::ReleasePool::~ReleasePool() { } void DelaySimpleTilde::ReleasePool::add(std::shared_ptr<DelaySimpleTilde::CircularBuffer> & buffer) { if (buffer != nullptr) { std::lock_guard<std::mutex> lock(m_mutex); m_pool.emplace_back(buffer); } } void DelaySimpleTilde::ReleasePool::clear() { std::lock_guard<std::mutex> lock(m_mutex); for (auto it = m_pool.begin(); it != m_pool.end();) { if (it->use_count() <= 1) { it = m_pool.erase(it); } else { ++it; } } } }}
9,438
C++
.cpp
224
29.53125
104
0.479087
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,311
KiwiEngine_SnapshotTilde.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_SnapshotTilde.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_SnapshotTilde.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // SNAPSHOT~ // // ================================================================================ // void SnapshotTilde::declare() { Factory::add<SnapshotTilde>("snapshot~", &SnapshotTilde::create); } std::unique_ptr<Object> SnapshotTilde::create(model::Object const& model, Patcher & patcher) { return std::make_unique<SnapshotTilde>(model, patcher); } SnapshotTilde::SnapshotTilde(model::Object const& model, Patcher& patcher) : AudioObject(model, patcher) { ; } void SnapshotTilde::receive(size_t index, std::vector<tool::Atom> const& args) { if (index == 0 && !args.empty()) { if(args[0].isBang()) { send(0, {m_value.load()}); } else { warning("snapshot~ inlet 1 doesn't understand args"); } } } void SnapshotTilde::perform(dsp::Buffer const& input, dsp::Buffer& output) noexcept { size_t sample_index = input[0].size(); dsp::sample_t const* in = input[0].data(); while(sample_index--) { m_value.store(*in++); } } void SnapshotTilde::prepare(dsp::Processor::PrepareInfo const& infos) { if(infos.inputs[0]) { setPerformCallBack(this, &SnapshotTilde::perform); } } }}
2,617
C++
.cpp
64
33.578125
96
0.514056
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,312
KiwiEngine_AudioInterface.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_AudioInterface.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_AudioInterface.h> namespace kiwi { namespace engine { // ================================================================================ // // AUDIOINTERFACE // // ================================================================================ // AudioInterfaceObject::AudioInterfaceObject(model::Object const& model, Patcher& patcher): AudioObject(model, patcher), m_audio_controler(patcher.getAudioControler()), m_routes(parseArgs(model.getArguments())) { } std::vector<size_t> AudioInterfaceObject::parseArgs(std::vector<tool::Atom> const& args) const { std::vector<size_t> routes; for(tool::Atom const& arg : args) { if (arg.isNumber()) { routes.push_back(arg.getInt() - 1); } else if(arg.isString()) { std::string inputs(arg.getString()); int left_input = std::stoi(inputs.substr(0, inputs.find(":"))) - 1; int right_input = std::stoi(inputs.substr(inputs.find(":") + 1)) - 1; bool rev = left_input > right_input; for (int channel = left_input; rev ? channel >= right_input : channel <= right_input; rev ? --channel : ++channel) { routes.push_back(channel); } } } if (routes.empty()) { routes = {0, 1}; } return routes; } void AudioInterfaceObject::receive(size_t index, std::vector<tool::Atom> const & args) { if(!args.empty()) { if(args[0].isString()) { const std::string sym = args[0].getString(); if(sym == "start") { m_audio_controler.startAudio(); } else if(sym == "stop") { m_audio_controler.stopAudio(); } else { warning("audio interface inlet 1 only understand start and stop"); } } else { warning("audio interface inlet 1 only understand start and stop"); } } } }}
3,417
C++
.cpp
80
30.6875
130
0.464564
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,313
KiwiEngine_SfPlayTilde.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_SfPlayTilde.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_SfPlayTilde.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // SOUNDFILE PLAYER // // ================================================================================ // //! @note the SoundFilePlayer class is based on the juce tutorial : // https://docs.juce.com/master/tutorial_playing_sound_files.html SoundFilePlayer::SoundFilePlayer() : m_buffer() , m_audio_source_channel_info(m_buffer) { m_format_manager.registerBasicFormats(); m_transport_source.addChangeListener(this); } SoundFilePlayer::~SoundFilePlayer() { stop(); } bool SoundFilePlayer::start(const juce::File& file, double start_ms, double end_ms) { stop(); std::unique_ptr<juce::AudioFormatReader> reader (m_format_manager.createReaderFor(file)); if (reader) { const auto sf_frames = reader->lengthInSamples; const auto sf_samplerate = reader->sampleRate; const int64_t start_sample = (start_ms * 0.001 * sf_samplerate); if(start_sample >= 0 && start_sample < sf_frames) { int64_t end_sample = sf_frames; if(start_ms < end_ms) { end_sample = std::min<int64_t>(end_ms * 0.001 * sf_samplerate, sf_frames); } int64_t length = end_sample - start_sample; auto subsection_reader = new juce::AudioSubsectionReader(reader.release(), start_sample, length, true); auto new_source = std::make_unique<juce::AudioFormatReaderSource>(subsection_reader, true); int read_ahead = 0; m_transport_source.setSource(new_source.get(), read_ahead, nullptr, subsection_reader->sampleRate, getNumberOfChannels()); m_reader_source.reset(new_source.release()); setLoop(is_looping); changeState(Starting); } } return false; } void SoundFilePlayer::stop() { changeState(Stopping); } bool SoundFilePlayer::isPlaying() const { return m_transport_source.isPlaying(); } void SoundFilePlayer::setLoop(bool should_loop) { is_looping = should_loop; if (m_reader_source != nullptr) { m_reader_source->setLooping(should_loop); } } void SoundFilePlayer::setNumberOfChannels(size_t channels) { m_channels = channels > 0 ? channels : 0; } size_t SoundFilePlayer::getNumberOfChannels() const { return m_channels; } juce::String SoundFilePlayer::getSupportedFormats() const { return m_format_manager.getWildcardForAllFormats(); } void SoundFilePlayer::printInfos(juce::File file, std::function<void(juce::String const&)> post) { std::unique_ptr<juce::AudioFormatReader> reader (m_format_manager.createReaderFor(file)); if (reader) { post("- file: " + file.getFullPathName()); post("- format: " + reader->getFormatName()); post("- sampling rate: " + juce::String(reader->sampleRate)); post("- channels: " + juce::String(reader->numChannels)); post("- duration: " + juce::RelativeTime::seconds(reader->lengthInSamples / reader->sampleRate).getDescription()); post("- bits per sample: " + juce::String(reader->bitsPerSample)); // other infos; const auto speaker_arr = reader->getChannelLayout().getSpeakerArrangementAsString(); if(!speaker_arr.isEmpty()) { post("- speaker arrangement: " + speaker_arr + "\n"); } const auto metadata = reader->metadataValues.getDescription(); if(!metadata.isEmpty()) { post("- metadata: " + metadata + "\n"); } } } void SoundFilePlayer::setPlayingStoppedCallback(playingStoppedCallback && fn) { m_playing_stopped_callback = std::move(fn); } void SoundFilePlayer::prepare(double sample_rate, size_t vector_size) { m_buffer.setSize(getNumberOfChannels(), vector_size); m_audio_source_channel_info.startSample = 0.; m_audio_source_channel_info.numSamples = vector_size; m_transport_source.prepareToPlay(vector_size, sample_rate); } bool SoundFilePlayer::read(dsp::Buffer& outputs) { if (m_reader_source == nullptr) { const auto channels = outputs.getNumberOfChannels(); for(auto channel = 0; channel < channels; ++channel) { outputs[channel].fill(0.); } return false; } m_transport_source.getNextAudioBlock(m_audio_source_channel_info); // recopy samples const auto channels = outputs.getNumberOfChannels(); for(auto channel = 0; channel < channels; ++channel) { auto& output = outputs[channel]; if(channel < m_buffer.getNumChannels() && output.size() <= m_buffer.getNumSamples()) { for(auto i = 0; i < output.size(); ++i) { output[i] = m_buffer.getReadPointer(channel)[i]; } } } return true; } void SoundFilePlayer::release() { m_transport_source.releaseResources(); } void SoundFilePlayer::changeState (TransportState new_state) { if (m_state != new_state) { m_state = new_state; switch (m_state) { case Stopped: if(m_playing_stopped_callback) { m_playing_stopped_callback(); } break; case Starting: m_transport_source.start(); break; case Playing: break; case Stopping: m_transport_source.stop(); break; } } } void SoundFilePlayer::changeListenerCallback(juce::ChangeBroadcaster* source) { if (source == &m_transport_source) { if (m_transport_source.isPlaying()) changeState (Playing); else changeState (Stopped); } } // ================================================================================ // // SFPLAY~ // // ================================================================================ // void SfPlayTilde::declare() { Factory::add<SfPlayTilde>("sf.play~", &SfPlayTilde::create); } std::unique_ptr<Object> SfPlayTilde::create(model::Object const& model, Patcher & patcher) { return std::make_unique<SfPlayTilde>(model, patcher); } SfPlayTilde::SfPlayTilde(model::Object const& model, Patcher& patcher) : AudioObject(model, patcher) { const auto& args = model.getArguments(); const auto channels = !args.empty() && args[0].getInt() > 0 ? args[0].getInt() : 2; m_player.setNumberOfChannels(channels); m_player.setPlayingStoppedCallback([this](){ defer([this](){ send(getNumberOfOutputs() - 1, {"bang"}); }); }); } SfPlayTilde::~SfPlayTilde() { closeFileDialog(); } void SfPlayTilde::receive(size_t index, std::vector<tool::Atom> const& args) { if (!args.empty() && index == 0) { if (args[0].isString() && args[0].getString() == "open") { if(args.size() > 1) { if(args[1].isString()) { openFile(juce::File(args[1].getString())); } } else { openFileDialog(); } } else if (args[0].isNumber()) { auto num = args[0].getInt(); if(num == 1) m_player.start(m_file_to_read); else if(num == 0) m_player.stop(); else warning("sf.play~: use 1 to play, 0 to stop"); } else if (args[0].getString() == "play") { if(args.size() > 1 && args[1].isNumber()) { const double start_ms = args[1].getFloat(); const double end_ms = ((args.size() > 2 && args[2].isNumber()) ? args[2].getFloat() : -1.); m_player.start(m_file_to_read, start_ms, end_ms); } else { warning("sf.play~: the \"play\" method requires a start position in ms, pass a second argument to specify the ending position"); } } else if (args[0].getString() == "loop") { if(args.size() == 2 && args[1].isNumber()) { m_player.setLoop(args[1].getInt()); } else { warning("sf.play~: loop message must be followed by 0 or 1"); } } else if (args[0].getString() == "print") { post("*sfplay~ infos*"); const auto filepath = m_file_to_read.getFullPathName(); if(filepath.isNotEmpty()) { m_player.printInfos(m_file_to_read, [this](juce::String const& line){ post(line.toStdString()); }); } else { post("- no file opened"); } } } } bool SfPlayTilde::openFile(juce::File file) { const auto file_path = file.getFullPathName(); if(!juce::File::isAbsolutePath(file_path)) { warning("sf.play~: is not an absolute path"); return false; } if(file.isDirectory()) { warning("sf.play~: invalid file path"); return false; } if(!file.exists()) { warning("sf.play~: file doesn't exist \"" + file_path.toStdString() + "\""); return false; } // that really exist. m_player.stop(); m_file_to_read = file; return true; } void SfPlayTilde::openFileDialog() { const auto default_dir = juce::File::getSpecialLocation(juce::File::userMusicDirectory); auto dir = (!m_file_to_read.getFullPathName().isEmpty() ? m_file_to_read.getParentDirectory() : default_dir); m_file_chooser = std::make_unique<juce::FileChooser>("Choose a file to read...", dir, m_player.getSupportedFormats(), true); deferMain([this, fc = m_file_chooser.get()]() { const int fc_flags = (juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles); fc->launchAsync(fc_flags, [this](juce::FileChooser const& chooser) { auto file = chooser.getResult(); if(file.getFullPathName().isNotEmpty()) { openFile(file); } }); }); } void SfPlayTilde::closeFileDialog() { deferMain([this]() { m_file_chooser.reset(); }); } void SfPlayTilde::prepare(dsp::Processor::PrepareInfo const& infos) { m_player.prepare(infos.sample_rate, infos.vector_size); setPerformCallBack(this, &SfPlayTilde::perform); } void SfPlayTilde::perform(dsp::Buffer const& input, dsp::Buffer& output) noexcept { m_player.read(output); } void SfPlayTilde::release() { m_player.release(); } }}
14,293
C++
.cpp
358
26.273743
148
0.488669
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,314
KiwiEngine_Pipe.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_Pipe.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_Pipe.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // OBJECT PIPE // // ================================================================================ // void Pipe::declare() { Factory::add<Pipe>("pipe", &Pipe::create); } std::unique_ptr<Object> Pipe::create(model::Object const& model, Patcher & patcher) { return std::make_unique<Pipe>(model, patcher); } Pipe::Pipe(model::Object const& model, Patcher& patcher): Object(model, patcher), m_delay(std::chrono::milliseconds(0)) { std::vector<tool::Atom> const& args = model.getArguments(); if (!args.empty()) { m_delay = std::chrono::milliseconds(args[0].getInt()); } } Pipe::~Pipe() { } void Pipe::receive(size_t index, std::vector<tool::Atom> const& args) { if (!args.empty()) { if (index == 0) { schedule([this, args](){send(0, args);}, m_delay); } else if(index == 1) { if (args[0].isNumber()) { m_delay = std::chrono::milliseconds(args[0].getInt()); } else { warning("pipe inlet 2 doesn't understand [" + args[0].getString() + "]"); } } } } }}
2,539
C++
.cpp
63
32
93
0.46959
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,315
KiwiEngine_PhasorTilde.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_PhasorTilde.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_PhasorTilde.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi{ namespace engine { // ================================================================================ // // PHASOR~ // // ================================================================================ // void PhasorTilde::declare() { Factory::add<PhasorTilde>("phasor~", &PhasorTilde::create); } std::unique_ptr<Object> PhasorTilde::create(model::Object const& model, Patcher & patcher) { return std::make_unique<PhasorTilde>(model, patcher); } PhasorTilde::PhasorTilde(model::Object const& model, Patcher& patcher): AudioObject(model, patcher) { std::vector<tool::Atom> const& args = model.getArguments(); if (!args.empty() && args[0].isNumber()) { setFrequency(args[0].getFloat()); } } void PhasorTilde::setFrequency(dsp::sample_t const& freq) noexcept { m_freq = freq; m_phase_inc.store(m_freq / m_sr); } void PhasorTilde::setSampleRate(dsp::sample_t const& sample_rate) { m_sr = sample_rate; m_phase_inc.store(m_freq / m_sr); } void PhasorTilde::setPhase(dsp::sample_t const& phase) noexcept { auto new_phase = phase; while(new_phase > 1.f) { new_phase -= 1.f; } while(new_phase < 0.f) { new_phase += 1.f; } m_phase.store(new_phase); } void PhasorTilde::receive(size_t index, std::vector<tool::Atom> const& args) { if (index == 0) { if (args[0].isNumber()) { setFrequency(args[0].getFloat()); } else { warning("phasor~ inlet 1 only take numbers"); } } else if(index == 1) { if (args[0].isNumber()) { setPhase(args[0].getFloat()); } else { warning("phasor~ inlet 2 only takes numbers"); } } } void PhasorTilde::prepare(PrepareInfo const& infos) { setSampleRate(static_cast<dsp::sample_t>(infos.sample_rate)); setPerformCallBack(this, (infos.inputs[0] ? &PhasorTilde::performSignal : &PhasorTilde::performValue)); } dsp::sample_t PhasorTilde::getAndIncrementPhase(const dsp::sample_t inc) { dsp::sample_t old_phase = m_phase.load(); dsp::sample_t phase = old_phase; if(phase > 1.f) { phase -= 1.f; } else if(phase < 0.f) { phase += 1.f; } m_phase.compare_exchange_strong(old_phase, phase += inc); return phase; } void PhasorTilde::performSignal(dsp::Buffer const& input, dsp::Buffer& output) noexcept { size_t sampleframes = output[0ul].size(); dsp::sample_t const* in = input[0ul].data(); dsp::sample_t* out = output[0ul].data(); dsp::sample_t freq = 0.f; while(sampleframes--) { freq = *in++; *out++ = getAndIncrementPhase(freq / m_sr); } } void PhasorTilde::performValue(dsp::Buffer const& input, dsp::Buffer& output) noexcept { size_t sampleframes = output[0ul].size(); dsp::sample_t *out = output[0ul].data(); while(sampleframes--) { *out++ = getAndIncrementPhase(m_phase_inc.load()); } } }}
4,566
C++
.cpp
117
30.076923
94
0.521739
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,316
KiwiEngine_SwitchTilde.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_SwitchTilde.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_SwitchTilde.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // SWITCH~ // // ================================================================================ // void SwitchTilde::declare() { Factory::add<SwitchTilde>("switch~", &SwitchTilde::create); } std::unique_ptr<Object> SwitchTilde::create(model::Object const& model, Patcher & patcher) { return std::make_unique<SwitchTilde>(model, patcher); } SwitchTilde::SwitchTilde(model::Object const& model, Patcher& patcher) : AudioObject(model, patcher), m_opened_input(), m_num_inputs(model.getArguments()[0].getInt()) { std::vector<tool::Atom> const& args = model.getArguments(); if (args.size() > 1) { openInput(args[1].getInt()); } } void SwitchTilde::openInput(int input) { m_opened_input = std::max(0, std::min(input, static_cast<int>(m_num_inputs))); } void SwitchTilde::receive(size_t index, std::vector<tool::Atom> const& args) { if (args.size() > 0) { if (index == 0) { if (args[0].isNumber()) { openInput(args[0].getInt()); } else { warning("switch~ inlet 1 receives only numbers"); } } } } void SwitchTilde::prepare(PrepareInfo const& infos) { if (infos.inputs[0]) { setPerformCallBack(this, &SwitchTilde::performSig); } else { setPerformCallBack(this, &SwitchTilde::performValue); } } void SwitchTilde::performValue(dsp::Buffer const& input, dsp::Buffer& output) noexcept { if (m_opened_input != 0) { output[0].copy(input[m_opened_input]); } else { output[0].fill(0); } } void SwitchTilde::performSig(dsp::Buffer const& input, dsp::Buffer& output) noexcept { dsp::sample_t const * route_signal = input[0].data(); dsp::sample_t * output_signal = output[0].data(); size_t sample_index = output[0ul].size(); size_t opened_input = 0; while(sample_index--) { opened_input = std::max((size_t) 0, std::min(m_num_inputs, (size_t) route_signal[sample_index])); output_signal[sample_index] = opened_input ? input[opened_input][sample_index] : 0; } } }}
3,703
C++
.cpp
95
30.431579
109
0.515661
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,317
KiwiEngine_LessEqualTilde.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_LessEqualTilde.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_LessEqualTilde.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // <=~ // // ================================================================================ // void LessEqualTilde::declare() { Factory::add<LessEqualTilde>("<=~", &LessEqualTilde::create); } std::unique_ptr<Object> LessEqualTilde::create(model::Object const& model, Patcher & patcher) { return std::make_unique<LessEqualTilde>(model, patcher); } LessEqualTilde::LessEqualTilde(model::Object const& model, Patcher& patcher): OperatorTilde(model, patcher) { } void LessEqualTilde::compute(dsp::sample_t & result, dsp::sample_t const& lhs, dsp::sample_t const& rhs) { result = lhs <= rhs ? 1 : 0; } }}
1,896
C++
.cpp
37
46.324324
108
0.52562
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,318
KiwiEngine_Message.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_Message.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiModel/KiwiModel_Objects/KiwiModel_Message.h> #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_Message.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // OBJECT MESSAGE // // ================================================================================ // void Message::declare() { Factory::add<Message>("message", &Message::create); } std::unique_ptr<Object> Message::create(model::Object const& model, Patcher& patcher) { return std::make_unique<Message>(model, patcher); } Message::Message(model::Object const& object_model, Patcher& patcher) : Object(object_model, patcher) , m_connection(object_model.getSignal<>(model::Message::Signal::outputMessage) .connect(std::bind(&Message::outputMessage, this))) { attributeChanged("text", object_model.getAttribute("text")); } Message::~Message() { } void Message::outputMessage() { defer([this]() { sendMessages(); }); } void Message::attributeChanged(std::string const& name, tool::Parameter const& parameter) { if (name == "text") { tool::Atom null; for(auto& input_args : m_input_args) { input_args = null; } prepareMessagesForText(parameter[0].getString()); } } void Message::receive(size_t index, std::vector<tool::Atom> const& args) { if (index == 0 && !args.empty()) { if(!args[0].isBang()) { for(size_t i = 0; i <= 9; i++) { if(i < args.size()) { m_input_args[i] = args[i]; } } } sendMessages(); } } void Message::prepareMessagesForText(std::string const& text) { static const int flags = (0 | tool::AtomHelper::ParsingFlags::Comma | tool::AtomHelper::ParsingFlags::Dollar); auto atoms = tool::AtomHelper::parse(text, flags); m_messages.clear(); if(!atoms.empty()) { std::vector<tool::Atom> atom_sequence; bool dollar_flag = false; for(auto&& atom : atoms) { if(atom.isComma()) { if(!atom_sequence.empty()) { m_messages.emplace_back(std::move(atom_sequence), dollar_flag); atom_sequence.clear(); dollar_flag = false; } } else { if(atom.isDollar()) { dollar_flag = true; } atom_sequence.emplace_back(std::move(atom)); } } if(!atom_sequence.empty()) { m_messages.emplace_back(std::move(atom_sequence), dollar_flag); } } } void Message::sendMessages() { for(auto const& message : m_messages) { if(message.has_dollar) { std::vector<tool::Atom> atoms = message.atoms; for(auto& atom : atoms) { if(atom.isDollar()) { const size_t index = atom.getDollarIndex() - 1; auto& atom_arg = m_input_args[index]; atom = !atom_arg.isNull() ? atom_arg : 0; } } send(0, atoms); } else { send(0, message.atoms); } } } }}
5,195
C++
.cpp
139
24.165468
93
0.443666
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,319
KiwiEngine_GreaterEqualTilde.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_GreaterEqualTilde.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_GreaterEqualTilde.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // >=~ // // ================================================================================ // void GreaterEqualTilde::declare() { Factory::add<GreaterEqualTilde>(">=~", &GreaterEqualTilde::create); } std::unique_ptr<Object> GreaterEqualTilde::create(model::Object const& model, Patcher & patcher) { return std::make_unique<GreaterEqualTilde>(model, patcher); } GreaterEqualTilde::GreaterEqualTilde(model::Object const& model, Patcher& patcher): OperatorTilde(model, patcher) { } void GreaterEqualTilde::compute(dsp::sample_t & result, dsp::sample_t const& lhs, dsp::sample_t const& rhs) { result = lhs >= rhs ? 1 : 0; } }}
1,923
C++
.cpp
37
47.054054
111
0.532573
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,320
KiwiEngine_Number.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_Number.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiModel/KiwiModel_Objects/KiwiModel_Number.h> #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_Number.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // OBJECT NUMBER // // ================================================================================ // void Number::declare() { Factory::add<Number>("number", &Number::create); } std::unique_ptr<Object> Number::create(model::Object const& model, Patcher& patcher) { return std::make_unique<Number>(model, patcher); } Number::Number(model::Object const& object_model, Patcher& patcher): Object(object_model, patcher), m_value(object_model.getParameter("value")[0].getFloat()), m_connection(object_model.getSignal<>(model::Number::Signal::OutputValue) .connect(std::bind(&Number::outputValue, this))) { } void Number::parameterChanged(std::string const& name, tool::Parameter const& parameter) { if (name == "value") { m_value = parameter[0].getFloat(); } } void Number::outputValue() { defer([this]() { send(0, {m_value}); }); } void Number::receive(size_t index, std::vector<tool::Atom> const& args) { if (index == 0 && !args.empty()) { if (args[0].isNumber()) { send(0, {args[0].getFloat()}); setParameter("value", tool::Parameter(tool::Parameter::Type::Float, {args[0].getFloat()})); } else if (args[0].isString()) { if (args[0].isBang()) { outputValue(); } else if(args[0].getString() == "set") { if (args.size() > 1 && args[1].isNumber()) { setParameter("value", tool::Parameter(tool::Parameter::Type::Float, {args[1].getFloat()})); } else { warning("number, \"set\" must be followed by a number"); } } else { warning("number doesn't understand symbol " + args[0].getString()); } } else { warning("number doesn't understand " + args[0].getString()); } } } }}
3,570
C++
.cpp
88
30.306818
115
0.474656
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,321
KiwiEngine_ClipTilde.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_ClipTilde.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_ClipTilde.h> #include <KiwiEngine/KiwiEngine_Factory.h> #include <algorithm> namespace kiwi { namespace engine { // ================================================================================ // // CLIP~ // // ================================================================================ // void ClipTilde::declare() { Factory::add<ClipTilde>("clip~", &ClipTilde::create); } std::unique_ptr<Object> ClipTilde::create(model::Object const& model, Patcher & patcher) { return std::make_unique<ClipTilde>(model, patcher); } ClipTilde::ClipTilde(model::Object const& model, Patcher& patcher): AudioObject(model, patcher), m_minimum(0.), m_maximum(0.) { std::vector<tool::Atom> const& args = model.getArguments(); if (args.size() > 0) { m_minimum.store(args[0].getFloat()); if (args.size() > 1) { m_maximum.store(args[1].getFloat()); } } } void ClipTilde::receive(size_t index, std::vector<tool::Atom> const& args) { if (!args.empty()) { if (index == 1) { if (args[0].isNumber()) { m_minimum.store(args[0].getFloat()); if (m_minimum.load() > m_maximum.load()) { warning("clip~ minimum is higher than maximum"); } } else { warning("clip~ inlet 2 only take numbers"); } } else if(index == 2) { if (args[0].isNumber()) { m_maximum.store(args[0].getFloat()); if (m_minimum.load() > m_maximum.load()) { warning("clip~ maximum is lower than minimum"); } } else { warning("clip~ inlet 3 only take numbers"); } } } } void ClipTilde::prepare(dsp::Processor::PrepareInfo const& infos) { if (infos.inputs[1] && infos.inputs[2]) { setPerformCallBack(this, &ClipTilde::performMinMax); } else if(infos.inputs[2]) { setPerformCallBack(this, &ClipTilde::performMax); } else if(infos.inputs[1]) { setPerformCallBack(this, &ClipTilde::performMin); } else { setPerformCallBack(this, &ClipTilde::perform); } } void ClipTilde::perform(dsp::Buffer const& input, dsp::Buffer& output) noexcept { dsp::sample_t *output_data = output[0ul].data(); dsp::sample_t const *input_data = input[0].data(); size_t sample_index = output[0ul].size(); while(sample_index--) { *output_data++ = std::max(static_cast<kiwi::dsp::sample_t>(m_minimum.load()), std::min(*input_data++, static_cast<kiwi::dsp::sample_t>(m_maximum.load()))); } } void ClipTilde::performMinMax(dsp::Buffer const& input, dsp::Buffer& output) noexcept { dsp::sample_t *output_data = output[0ul].data(); dsp::sample_t const *input_data = input[0].data(); dsp::sample_t const *input_min = input[1].data(); dsp::sample_t const *input_max = input[2].data(); size_t sample_index = output[0ul].size(); while(sample_index--) { *output_data++ = std::max(*input_min++, std::min(*input_data++, *input_max++)); } } void ClipTilde::performMin(dsp::Buffer const& input, dsp::Buffer& output) noexcept { dsp::sample_t *output_data = output[0ul].data(); dsp::sample_t const *input_data = input[0].data(); dsp::sample_t const *input_min = input[1].data(); size_t sample_index = output[0ul].size(); while(sample_index--) { *output_data++ = std::max(*input_min++, std::min(*input_data++, static_cast<kiwi::dsp::sample_t>(m_maximum.load()))); } } void ClipTilde::performMax(dsp::Buffer const& input, dsp::Buffer& output) noexcept { dsp::sample_t *output_data = output[0ul].data(); dsp::sample_t const *input_data = input[0].data(); dsp::sample_t const *input_max = input[2].data(); size_t sample_index = output[0ul].size(); while(sample_index--) { *output_data++ = std::max(static_cast<kiwi::dsp::sample_t>(m_minimum.load()), std::min(*input_data++, *input_max++)); } } }}
5,822
C++
.cpp
144
29.895833
167
0.502176
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,322
KiwiEngine_FaustTilde.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_FaustTilde.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_FaustTilde.h> #include <KiwiEngine/KiwiEngine_Factory.h> #include <faust/dsp/llvm-dsp.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_FaustTilde.h> #include <KiwiModel/KiwiModel_DocumentManager.h> #include "KiwiEngine_FaustTilde/KiwiEngine_FaustTilde_CodeEditor.cpp" #include "KiwiEngine_FaustTilde/KiwiEngine_FaustTilde_UIGLue.cpp" #include "KiwiEngine_FaustTilde/KiwiEngine_FaustTilde_FileSelector.cpp" namespace kiwi { namespace engine { // ================================================================================ // // FAUST~ // // ================================================================================ // void FaustTilde::declare() { Factory::add<FaustTilde>("faust~", &FaustTilde::create); } std::unique_ptr<Object> FaustTilde::create(model::Object const& model, Patcher & patcher) { return std::make_unique<FaustTilde>(model, patcher); } FaustTilde::FaustTilde(model::Object const& model, Patcher& patcher) : AudioObject(model, patcher) , m_factory(nullptr, deleteDSPFactory) , m_compile_options({"-I", getFaustLibsPath()}) , m_ui_glue(std::make_unique<UIGlue>(*this)) , m_file_selector(std::make_unique<FileSelector>(*this)) , m_code_editor(std::make_unique<CodeEditor>(*this)) , m_user_id(getUserId(model)) { attributeChanged("dspcodechanged", {tool::Parameter::Type::String, {std::string("")}}); attributeChanged("editcodechanged", {tool::Parameter::Type::String, {std::string("")}}); attributeChanged("compileoptionschanged", {tool::Parameter::Type::String, {std::string("")}}); if(auto const* fmodel = dynamic_cast<model::FaustTilde const*>(&model)) { attributeChanged("lockstate", {tool::Parameter::Type::Int, {fmodel->getLockState()}}); } } FaustTilde::~FaustTilde() {} // ================================================================================ // bool FaustTilde::grabLock(bool state) { if(!hasLock() && !canLock() && state) { warning("The object is already locked"); return false; } else if(hasLock() && !state) { setAttribute(std::string("lockstate"), {tool::Parameter::Type::Int, {0}}); } else if(canLock() && state) { setAttribute(std::string("lockstate"), {tool::Parameter::Type::Int, {m_user_id}}); } return true; } bool FaustTilde::hasLock() const { return m_lock_state == m_user_id; } bool FaustTilde::canLock() const { return m_lock_state == 0; } void FaustTilde::forceUnlock() { setAttribute(std::string("lockstate"), {tool::Parameter::Type::Int, {0}}); } std::string FaustTilde::getFaustLibsPath() const { const auto appfile = juce::File::getSpecialLocation(juce::File::SpecialLocationType::currentApplicationFile); #ifdef __APPLE__ return appfile.getChildFile("Contents/Resources/libs/faust").getFullPathName().toStdString(); #elif _WIN32 auto apppath = appfile.getParentDirectory().getFullPathName().toStdString(); std::replace(apppath.begin(), apppath.end(), '\\', '/'); return apppath + std::string("/libs/faust"); #else return appfile.getParentDirectory().getChildFile("libs/faust").getFullPathName().toStdString(); #endif } int64_t FaustTilde::getUserId(model::Object const& model) { int64_t temp; uint64_t userid = model.document().user(); std::memcpy(&temp, &userid, sizeof(temp)); return temp; } std::vector<std::string> FaustTilde::getCompileOptions() const { return m_compile_options; } void FaustTilde::setCompileOptions(std::vector<std::string>&& options) { if(!canLock() && !hasLock()) { warning("faust~: code is currently locked by another user"); return; } deferMain([this, noptions = std::move(options)]() { if(auto* model = dynamic_cast<model::FaustTilde*>(&getObjectModel())) { model->setCompileOptions(noptions); setAttribute(std::string("compileoptionschanged"), {tool::Parameter::Type::String, {juce::Uuid().toString().toStdString()}}); } }); } std::string const& FaustTilde::getDspCode() const { return m_dsp_code; } void FaustTilde::setDspCode(std::string&& code) { if(!canLock() && !hasLock()) { warning("faust~: code is currently locked by another user"); return; } deferMain([this, ncode = std::move(code)]() { if(auto* model = dynamic_cast<model::FaustTilde*>(&getObjectModel())) { model->setDSPCode(ncode); setAttribute(std::string("dspcodechanged"), {tool::Parameter::Type::String, {juce::Uuid().toString().toStdString()}}); } }); } std::string const& FaustTilde::getEditCode() const { return m_edit_code; } void FaustTilde::setEditCode(std::string&& code) { if(!canLock() && !hasLock()) { warning("faust~: code is currently locked by another user"); return; } deferMain([this, ncode = std::move(code)]() { if(auto* model = dynamic_cast<model::FaustTilde*>(&getObjectModel())) { model->setEditCode(ncode); setAttribute(std::string("editcodechanged"), {tool::Parameter::Type::String, {juce::Uuid().toString().toStdString()}}); } }); } void FaustTilde::openFile(std::string const& filepath) { juce::File const file(filepath); if(!file.exists()) { warning("faust~: " + filepath + " doesn't exist"); return; } if(!file.hasFileExtension(".dsp")) { warning("faust~: " + filepath + " is not a FAUST DSP file"); return; } const auto file_as_string = file.loadFileAsString(); setEditCode(file_as_string.toStdString()); setDspCode(file_as_string.toStdString()); } void FaustTilde::compileDspCode() { if(m_dsp_code.empty()) { m_ui_glue->prepareChanges(); { // Safetly release the instance std::lock_guard<std::mutex> guard(m_mutex); m_instance.reset(); } m_factory.reset(); return; } std::string errors; uptr_faust_factory nfactory(nullptr, deleteDSPFactory); if(startMTDSPFactories()) { const auto options = m_compile_options; const auto name = "kiwi" + juce::Uuid().toString().toStdString(); std::vector<char const*> argv(options.size()); for(size_t i = 0; i < options.size(); ++i) { argv[i] = options[i].c_str(); } nfactory = std::unique_ptr<llvm_dsp_factory, decltype(&deleteDSPFactory)>(createDSPFactoryFromString(name, m_dsp_code, options.size(), argv.data(), std::string(), errors), deleteDSPFactory); stopMTDSPFactories(); } else { warning("faust~: can't start multi-thread access"); } if(!errors.empty()) { warning("faust~: compilation failed - " + errors); } else if(nfactory) { log("faust~: compilation succeed - " + nfactory->getName()); auto ninstance = std::unique_ptr<llvm_dsp, nop>(nfactory->createDSPInstance()); if(ninstance) { m_ui_glue->prepareChanges(); // Safetly swap the factory { std::lock_guard<std::mutex> guard(m_mutex); m_instance = std::move(ninstance); } m_instance->buildUserInterface(m_ui_glue.get()); m_ui_glue->finishChanges(); log("faust~: DSP allocation succeed"); log("faust~: number of inputs " + std::to_string(m_instance->getNumInputs())); log("faust~: number of outputs " + std::to_string(m_instance->getNumOutputs())); m_ui_glue->log(); prepareDsp(m_sample_rate, m_block_size); } else { m_ui_glue->prepareChanges(); warning("faust~: DSP allocation failed"); { // Safetly release the instance std::lock_guard<std::mutex> guard(m_mutex); m_instance.reset(); } } m_factory = std::move(nfactory); return; } m_ui_glue->prepareChanges(); { // Safetly release the instance std::lock_guard<std::mutex> guard(m_mutex); m_instance.reset(); } m_factory.reset(); } // ================================================================================ // void FaustTilde::attributeChanged(std::string const& name, tool::Parameter const& parameter) { if (name == "dspcodechanged") { deferMain([this, value = parameter[0].getString()]() { if(auto* fmodel = dynamic_cast<model::FaustTilde*>(&getObjectModel())) { m_dsp_code = fmodel->getDSPCode(); compileDspCode(); } }); } else if(name == "editcodechanged") { deferMain([this]() { if(auto* fmodel = dynamic_cast<model::FaustTilde*>(&getObjectModel())) { m_edit_code = fmodel->getEditCode(); m_code_editor->downloadCode(); } }); } else if(name == "compileoptionschanged") { deferMain([this]() { if(auto const* fmodel = dynamic_cast<model::FaustTilde*>(&getObjectModel())) { auto noptions = fmodel->getCompileOptions(); m_compile_options.resize(2 + noptions.size()); for(size_t i = 0; i < noptions.size(); ++i) { m_compile_options[i+2].swap(noptions[i]); } m_code_editor->updateCompileOptions(); compileDspCode(); } }); } else if(name == "lockstate") { m_lock_state = parameter[0].getInt(); m_code_editor->updateLockState(); } } // The Kiwi Object interface // ================================================================================ // void FaustTilde::receive(size_t index, std::vector<tool::Atom> const& args) { if(!args.empty() && args[0].isString()) { const auto& name = args[0].getString(); if(name == "open") { if(args.size() == 1) { m_file_selector->show(); } else { if(args[1].isString()) { openFile(args[1].getString()); } else { warning(std::string("faust~: open method expects a path")); } if(args.size() > 2) { warning(std::string("faust~: open method extra arguments")); } } return; } if(name == "editor") { deferMain([this]() { std::string ncode = m_dsp_code; setEditCode(std::move(ncode)); m_code_editor->show(); }); if(args.size() > 1) { warning(std::string("faust~: editor method extra arguments")); } return; } if(name == "options") { std::vector<std::string> noptions(args.size() - 1); for(size_t i = 1; i < args.size(); ++i) { if(args[i].isNumber()) noptions[i-1] = std::to_string(args[i].getFloat()); else noptions[i-1] = args[i].getString(); } setCompileOptions(std::move(noptions)); return; } if(!m_factory || !m_instance) { return; } if(m_ui_glue->hasOutput(name)) { send(getNumberOfOutputs() - 1, {m_ui_glue->getOutput(name)}); return; } if(args.size() == 1) { m_ui_glue->setInput(name, 0); return; } if(args[1].isNumber()) { m_ui_glue->setInput(name, args[1].getFloat()); if(args.size() > 2) { warning(std::string("faust~: FAUST interface \"") + name + std::string("\" too many arguments")); } return; } warning(std::string("faust~: FAUST interface \"") + name + std::string("\" wrong arguments")); return; } warning(std::string("faust~: receive bad arguments")); } void FaustTilde::perform(dsp::Buffer const& input, dsp::Buffer& output) noexcept { const size_t nsamples = input.getVectorSize(); const size_t ninputs = m_inputs.size(); const size_t noutputs = m_outputs.size(); if(m_mutex.try_lock()) { if(m_instance) { for(size_t i = 0; i < ninputs; ++i) { m_inputs[i] = const_cast<dsp::sample_t*>(input[i].data()); } for(size_t i = 0; i < noutputs; ++i) { m_outputs[i] = output[i].data(); } m_instance->compute(nsamples, const_cast<FAUSTFLOAT**>(m_inputs.data()), m_outputs.data()); } else { for(size_t i = ninputs; i < noutputs; ++i) { std::fill_n(output[i].data(), nsamples, 0.f); } } m_mutex.unlock(); } else { for(size_t i = ninputs; i < noutputs; ++i) { std::fill_n(output[i].data(), nsamples, 0.f); } } } bool FaustTilde::prepareDsp(size_t sampleRate, size_t blockSize) noexcept { m_sample_rate = sampleRate; m_block_size = blockSize; if(static_cast<size_t>(m_instance->getNumInputs()) <= getNumberOfInputs() && static_cast<size_t>(m_instance->getNumOutputs()) <= getNumberOfOutputs() - 1) { m_ui_glue->saveStates(); const int sampling_rate = static_cast<int>(m_sample_rate); m_instance->init(sampling_rate); m_instance->instanceInit(sampling_rate); m_instance->instanceConstants(sampling_rate); m_ui_glue->recallStates(); m_inputs.resize(m_instance->getNumInputs()); m_outputs.resize(m_instance->getNumOutputs()); return true; } return false; } void FaustTilde::prepare(PrepareInfo const& infos) { if(m_instance) { if(prepareDsp(infos.sample_rate, infos.vector_size)) { setPerformCallBack(this, &FaustTilde::perform); } else { warning("faust~: DSP instance has invalid number of inputs and outputs, expected at least " + std::to_string(m_instance->getNumInputs()) + " inputs but has " + std::to_string(getNumberOfInputs()) + " and " + std::to_string(m_instance->getNumOutputs()) + " inputs but has " + std::to_string(getNumberOfOutputs() - 1)); } } } }}
17,673
C++
.cpp
452
27.128319
333
0.497635
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,323
KiwiEngine_SigTilde.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_SigTilde.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_SigTilde.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // SIG~ // // ================================================================================ // void SigTilde::declare() { Factory::add<SigTilde>("sig~", &SigTilde::create); } std::unique_ptr<Object> SigTilde::create(model::Object const& model, Patcher & patcher) { return std::make_unique<SigTilde>(model, patcher); } SigTilde::SigTilde(model::Object const& model, Patcher& patcher): AudioObject(model, patcher) { std::vector<tool::Atom> const& args = model.getArguments(); if (!args.empty() && args[0].isNumber()) { m_value = args[0].getFloat(); } } void SigTilde::receive(size_t index, std::vector<tool::Atom> const& args) { if (index == 0) { if (args[0].isNumber()) { m_value = args[0].getFloat(); } else { warning("sig~ inlet 1 must receive a number"); } } } void SigTilde::perform(dsp::Buffer const& input, dsp::Buffer& output) noexcept { size_t sample_index = output[0].size(); dsp::sample_t* output_sig = output[0].data(); dsp::sample_t const value = m_value; while(sample_index--) { *output_sig++ = value; } } void SigTilde::prepare(dsp::Processor::PrepareInfo const& infos) { setPerformCallBack(this, &SigTilde::perform); } }}
2,710
C++
.cpp
66
33.560606
91
0.50661
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,324
KiwiEngine_Receive.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_Receive.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Factory.h> #include <KiwiTool/KiwiTool_Scheduler.h> #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_Receive.h> namespace kiwi { namespace engine { // ================================================================================ // // OBJECT RECEIVE // // ================================================================================ // void Receive::declare() { Factory::add<Receive>("receive", &Receive::create); } std::unique_ptr<Object> Receive::create(model::Object const& model, Patcher& patcher) { return std::make_unique<Receive>(model, patcher); } Receive::Receive(model::Object const& model, Patcher& patcher): Object(model, patcher), m_name() { std::vector<tool::Atom> const& args = model.getArguments(); m_name = !args.empty() ? args[0].getString() : ""; if(!m_name.empty()) { tool::Beacon& beacon = getBeacon(m_name); beacon.bind(*this); } } Receive::~Receive() { if(!m_name.empty()) { tool::Beacon& beacon = getBeacon(m_name); beacon.unbind(*this); } } void Receive::receive(size_t, std::vector<tool::Atom> const& args) { } void Receive::receive(std::vector<tool::Atom> const& args) { defer([this, args]() { send(0, args); }); } }}
2,441
C++
.cpp
60
33.8
90
0.510231
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,325
KiwiEngine_AdcTilde.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_AdcTilde.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_AdcTilde.h> #include <KiwiEngine/KiwiEngine_Factory.h> namespace kiwi { namespace engine { // ================================================================================ // // ADC~ // // ================================================================================ // void AdcTilde::declare() { Factory::add<AdcTilde>("adc~", &AdcTilde::create); } std::unique_ptr<Object> AdcTilde::create(model::Object const& model, Patcher & patcher) { return std::make_unique<AdcTilde>(model, patcher); } AdcTilde::AdcTilde(model::Object const& model, Patcher& patcher): AudioInterfaceObject(model, patcher) { } void AdcTilde::perform(dsp::Buffer const& input, dsp::Buffer& output) noexcept { for (size_t outlet = 0; outlet < m_routes.size(); ++outlet) { m_audio_controler.getFromChannel(m_routes[outlet], output[outlet]); } } void AdcTilde::prepare(dsp::Processor::PrepareInfo const& infos) { setPerformCallBack(this, &AdcTilde::perform); } }}
2,100
C++
.cpp
44
42.227273
91
0.533134
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,326
KiwiEngine_Print.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_Print.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiTool/KiwiTool_Atom.h> #include <KiwiEngine/KiwiEngine_Factory.h> #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_Print.h> namespace kiwi { namespace engine { // ================================================================================ // // OBJECT PRINT // // ================================================================================ // void Print::declare() { Factory::add<Print>("print", &Print::create); } std::unique_ptr<Object> Print::create(model::Object const& model, Patcher& patcher) { return std::make_unique<Print>(model, patcher); } Print::Print(model::Object const& model, Patcher& patcher) : Object(model, patcher) { std::vector<tool::Atom> const& args = model.getArguments(); if (!args.empty()) { if (args[0].isFloat()) { m_name = std::to_string(args[0].getFloat()); } else if(args[0].isInt()) { m_name = std::to_string(args[0].getInt()); } else { m_name = args[0].getString(); } } else { m_name = "print"; } } void Print::receive(size_t, std::vector<tool::Atom> const& args) { if(!args.empty()) { // do not include quotes in printed atoms post(m_name + " \xe2\x80\xa2 " + tool::AtomHelper::toString(args, false)); } } }}
2,493
C++
.cpp
62
32.419355
90
0.481684
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,327
KiwiEngine_FaustTilde_FileSelector.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_FaustTilde/KiwiEngine_FaustTilde_FileSelector.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_FaustTilde.h> #include <juce_gui_basics/juce_gui_basics.h> namespace kiwi { namespace engine { // ================================================================================ // class FaustTilde::FileSelector { public: FileSelector(FaustTilde& owner) : m_owner(owner) { } void show() { auto directory = juce::File(m_last_directory); if(!directory.exists()) { directory = juce::File::getSpecialLocation(juce::File::userMusicDirectory); } m_file_chooser = std::make_unique<juce::FileChooser>("Choose a DSP file to read...", directory, juce::String("*.dsp"), true); m_owner.deferMain([this]() { m_file_chooser->launchAsync(juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles, [this](juce::FileChooser const& chooser) { auto file = chooser.getResult(); if(file.getFullPathName().isNotEmpty()) { m_owner.openFile(file.getFullPathName().toStdString()); m_last_directory = file.getParentDirectory().getFullPathName().toStdString(); } }); }); } private: FaustTilde& m_owner; std::unique_ptr<juce::FileChooser> m_file_chooser; std::string m_last_directory; }; }}
2,786
C++
.cpp
53
37.132075
167
0.472947
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,328
KiwiEngine_FaustTilde_CodeEditor.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_FaustTilde/KiwiEngine_FaustTilde_CodeEditor.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_FaustTilde.h> #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_FaustCodeTokenizer.h> #include <KiwiEngine/KiwiEngine_Factory.h> #include <faust/dsp/llvm-dsp.h> #include <juce_core/juce_core.h> #include <juce_gui_basics/juce_gui_basics.h> #include <juce_gui_extra/juce_gui_extra.h> namespace kiwi { namespace engine { // ================================================================================ // class FaustTilde::CodeEditor : public juce::Component , public juce::CodeDocument::Listener , public juce::Button::Listener , public juce::Timer { public: CodeEditor(FaustTilde& owner) : m_owner(owner) , m_editor(m_document, &m_highlither) , m_lock(true) , m_code_changed(true) , m_error_line(-1) { setBounds(0, 0, 512, 384); m_editor.setColour(juce::CodeEditorComponent::backgroundColourId, juce::Colours::white); m_editor.setColour(juce::CodeEditorComponent::lineNumberBackgroundId, juce::Colours::lightgrey); m_editor.setScrollbarThickness(8); addAndMakeVisible(&m_editor); m_button_sync.setButtonText("Synchronize Audio"); m_button_sync.setClickingTogglesState(false); m_button_sync.setName("update"); m_button_sync.addListener(this); m_button_sync.setTooltip("Synchonize the audio engine with this code"); m_button_sync.setWantsKeyboardFocus(false); m_button_sync.setColour(juce::TextButton::buttonColourId, juce::Colours::darkgrey); addAndMakeVisible(&m_button_sync); m_button_lock.setName("lock"); m_button_lock.addListener(this); m_button_lock.setWantsKeyboardFocus(false); addAndMakeVisible(&m_button_lock); m_button_errs.setButtonText(juce::String(juce::CharPointer_UTF8 ("•"))); m_button_errs.setName("error"); m_button_errs.addListener(this); m_button_errs.setTooltip("Move the caret to the error line"); m_button_errs.setWantsKeyboardFocus(false); addAndMakeVisible(&m_button_errs); m_console.setReadOnly(true); m_console.setColour(juce::TextEditor::backgroundColourId, juce::Colours::lightgrey); m_console.setColour(juce::TextEditor::textColourId, juce::Colours::black); m_console.setBorder({ 1, 0, 1, 3 }); m_console.setSelectAllWhenFocused(true); m_console.onFocusLost = [this]() { m_console.setCaretPosition(0); }; addAndMakeVisible(&m_console); resized(); updateLockState(); m_window.setContentNonOwned(this, true); } // The Juce Component interface // ================================================================================ // void paint (juce::Graphics& g) override { g.fillAll(juce::Colours::grey); } void paintOverChildren (juce::Graphics& g) override { if(!m_owner.hasLock()) { g.setColour(juce::Colours::grey.withAlpha(0.2f)); g.fillRect(0, 0, getWidth(), getHeight() - 26); } } void resized() override { const auto width = getWidth(); const auto height = getHeight(); const auto hsize = 24; const auto yoffset = height - hsize - 2; m_editor.setBounds(0, 0, width, yoffset - 2); int y = 2, btnw = 0; { btnw = 106; m_button_sync.setBounds(y, yoffset, btnw, hsize); y += (2 + btnw); } { btnw = 84; m_button_lock.setBounds(y, yoffset, btnw, hsize); y += (2 + btnw); } { btnw = hsize; m_button_errs.setBounds(y, yoffset, btnw, hsize); y += (2 + btnw); } { btnw = width - y - 2; m_console.setBounds(y, yoffset + 1, btnw, hsize - 2); } } void visibilityChanged() override { if(isVisible()) { m_code_changed = true; computeErrors(); m_document.addListener(this); startTimer(3000); } else { m_document.removeListener(this); stopTimer(); } } // The Juce Timer interface // ================================================================================ // void timerCallback() override { computeErrors(); } // The Juce CodeDocument::Listener interface // ================================================================================ // void codeDocumentTextInserted(const juce::String& , int ) override { uploadToEditCode(); } void codeDocumentTextDeleted(int , int ) override { uploadToEditCode(); } // The Juce Button::Listener interface // ================================================================================ // void buttonClicked(juce::Button* btn) override { auto const name = btn->getName(); if(name == "update") { uploadToDspCode(); } else if(name == "lock") { if(!m_owner.canLock() && !m_owner.hasLock()) { forceUnlock(); } else if(m_owner.canLock() && !m_owner.hasLock()) { setLock(true); } else { setLock(false); } } else if(name == "error") { if(m_error_line >= 0) { juce::CodeDocument::Position const pos(m_document, m_error_line-1, 0); m_editor.moveCaretTo(pos, false); } } } void buttonStateChanged (juce::Button* btn) override { ; } // The public interface // ================================================================================ // // ================================================================================ // //! @brief Display the Code editor void show() { m_owner.deferMain([this]() { downloadCode(); if(!m_window.isShowing()) { m_window.addToDesktop(); } else { m_window.toFront(true); } }); } //! @brief Download the code from the owner and update the editor content void downloadCode() { setCode(m_owner.getEditCode()); } void updateLockState() { m_owner.deferMain([this]() { const juce::MessageManagerLock mmLock; m_editor.setReadOnly(!m_owner.hasLock()); m_button_sync.setEnabled(m_owner.hasLock()); if(!m_owner.canLock() && !m_owner.hasLock()) { m_button_lock.setButtonText("Unlock Edition"); m_button_lock.setTooltip("Force another user to unlock the editor and make it available for you or other users"); m_button_lock.setColour(juce::TextButton::buttonColourId, juce::Colours::red); } else if(m_owner.canLock() && !m_owner.hasLock()) { m_button_lock.setButtonText("Start Edition"); m_button_lock.setTooltip("Lock the editor and make it enable for you"); m_button_lock.setColour(juce::TextButton::buttonColourId, juce::Colours::green); } else { m_button_lock.setButtonText("Leave Edition"); m_button_lock.setTooltip("Unlock the editor and make it available for other users"); m_button_lock.setColour(juce::TextButton::buttonColourId, juce::Colours::darkgrey); } repaint(); }); } void updateCompileOptions() { m_code_changed = true; } private: // The private interface // ================================================================================ // //! @brief Set the current code void setCode(std::string const& code) { juce::CodeEditorComponent::State state(m_editor); m_lock = false; m_editor.loadContent(juce::String(code)); state.restoreState(m_editor); m_lock = true; m_code_changed = true; } //! @brief Get the current code std::string getCode() const { return m_document.getAllContent().toStdString(); } //! @brief Upload the current code to the DSP code of the owner void uploadToDspCode() { m_owner.setDspCode(getCode()); } //! @brief Upload the current code to the Edition code of the owner void uploadToEditCode() { if(m_lock) { m_owner.setEditCode(getCode()); } m_code_changed = true; } //! @brief Ensure that the lock is freed and ask for to synchronize the code if needed bool shouldClose() { if(m_owner.hasLock()) { auto const current_code = getCode(); if(m_owner.getDspCode() != current_code) { const int r = juce::AlertWindow::showYesNoCancelBox(juce::AlertWindow::QuestionIcon, juce::String("Closing document..."), juce::String("Do you want to synchronize the changes?"), juce::String("Synchronize"), juce::String("Discard changes"), juce::String("Cancel"), &m_window); if(r == 1) // Synchronize { m_owner.setDspCode(std::string(current_code)); m_owner.grabLock(false); return 1; } else if(r == 2) // Discard changes { m_owner.grabLock(false); return 1; } return false; } m_owner.grabLock(false); } return true; } // Try to set the lock state void setLock(bool state) { m_owner.grabLock(state); } // Force unlock void forceUnlock() { const int r = juce::AlertWindow::showOkCancelBox(juce::AlertWindow::QuestionIcon, juce::String("Force Unlock"), juce::String("Are you sure, you want to force to unlock the editor?\nPerhaps somebody else is using it..."), juce::String("Unlock"), juce::String("Cancel"), &m_window); if(r == 1) // save button { m_owner.forceUnlock(); } } // Set the current error line void setErrorLine(int line) { m_error_line = line; if(m_error_line == -1) { m_console.setTooltip(juce::String("No error")); m_console.setText(juce::String("")); m_console.repaint(); m_button_errs.setEnabled(false); m_button_errs.setColour(juce::TextButton::textColourOnId, juce::Colours::black); m_button_errs.setColour(juce::TextButton::textColourOffId, juce::Colours::black); } else { m_button_errs.setEnabled(true); m_button_errs.setColour(juce::TextButton::textColourOnId, juce::Colours::red); m_button_errs.setColour(juce::TextButton::textColourOffId, juce::Colours::red); } } //! @brief Get the compile options std::vector<std::string> getCompileOptions() { return m_owner.getCompileOptions(); } //! @brief Compute the errors of the current code void computeErrors() { if(!m_code_changed || !isVisible()) { return; } m_code_changed = false; if(m_document.getNumCharacters() == 0) { setErrorLine(-1); return; } std::string const code = getCode(); if(code.empty() || code.find_first_not_of("\n\r\t\v\f ") == std::string::npos) { setErrorLine(-1); return; } std::string errors; if(startMTDSPFactories()) { std::vector<std::string> options(m_owner.getCompileOptions()); std::vector<char const*> argv(options.size()); for(size_t i = 0; i < options.size(); ++i) { argv[i] = options[i].c_str(); } uptr_faust_factory nfactory = std::unique_ptr<llvm_dsp_factory, bool(*)(llvm_dsp_factory*)>(createDSPFactoryFromString("", code, options.size(), argv.data(), std::string(), errors), deleteDSPFactory); stopMTDSPFactories(); } auto pos = errors.find_first_of("\r\n"); if(pos != std::string::npos) { errors.erase(pos); } pos = errors.find("ERROR : "); if(pos != std::string::npos) { errors.erase(pos, 8); } if(!errors.empty()) { int line; errors.replace(0, 3, "l."); try { line = std::stoi(errors.substr(2)); } catch(...) { line = -2; } setErrorLine(line); m_console.setText(errors); m_console.setTooltip(juce::String(errors)); } else { setErrorLine(-1); } } // ================================================================================ // class Window : public juce::DocumentWindow { public: Window() : juce::DocumentWindow("FAUST Code Editor", juce::Colours::white, juce::DocumentWindow::allButtons, false) { setUsingNativeTitleBar(true); setResizable(true, true); setVisible(true); setTopLeftPosition(40, 40); } void closeButtonPressed() override { auto* content = dynamic_cast<FaustTilde::CodeEditor *>(getContentComponent()); if(content) { if(content->shouldClose()) { removeFromDesktop(); } } else { removeFromDesktop(); } } }; FaustTilde& m_owner; juce::TextButton m_button_sync; juce::TextButton m_button_lock; juce::TextButton m_button_errs; juce::TextEditor m_console; FaustTokeniser m_highlither; juce::CodeDocument m_document; juce::CodeEditorComponent m_editor; std::atomic<bool> m_lock; std::atomic<bool> m_code_changed; int m_error_line; Window m_window; }; }}
18,471
C++
.cpp
450
25.524444
216
0.447877
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,329
KiwiEngine_FaustTilde_UIGLue.cpp
Musicoll_Kiwi/Modules/KiwiEngine/KiwiEngine_Objects/KiwiEngine_FaustTilde/KiwiEngine_FaustTilde_UIGLue.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_FaustTilde.h> #include <faust/gui/UI.h> namespace kiwi { namespace engine { // ================================================================================ // //! @brief The User Interface Glue for FAUST class FaustTilde::UIGlue : public UI { public: typedef FAUSTFLOAT param_type; UIGlue(FaustTilde& owner) : m_owner(owner) { } // ================================================================================ // // The FAUST interface // ================================================================================ // // Active widgets // ================================================================================ // void addButton(const char* label, param_type* zone) override { addParameter(label, Parameter::Type::Button, zone, 0, 0, 0, 0); } void addCheckButton(const char* label, param_type* zone) override { addParameter(label, Parameter::Type::CheckButton, zone, 0.f, 1.f, 1.f, 0.f); } void addVerticalSlider(const char* label, param_type* zone, param_type init, param_type min, param_type max, param_type step) override { addParameter(label, Parameter::Type::Float, zone, min, max, step, init); } virtual void addHorizontalSlider(const char* label, param_type* zone, param_type init, param_type min, param_type max, param_type step) override { addParameter(label, Parameter::Type::Float, zone, min, max, step, init); } virtual void addNumEntry(const char* label, param_type* zone, param_type init, param_type min, param_type max, param_type step) override { addParameter(label, Parameter::Type::Float, zone, min, max, step, init); } // Passive widgets // ================================================================================ // void addHorizontalBargraph(const char* label, param_type* zone, param_type min, param_type max) override { addOutput(label, zone, min, max); } void addVerticalBargraph(const char* label, param_type* zone, param_type min, param_type max) override { addOutput(label, zone, min, max); } void addSoundfile(const char* label, const char* filename, Soundfile** sf_zone) override { } // Widget layout // ================================================================================ // void openTabBox(const char* label) override { m_params_path.push_back(label); } void openHorizontalBox(const char* label) override { m_params_path.push_back(label); } void openVerticalBox(const char* label) override { m_params_path.push_back(label); } void closeBox() override { m_params_path.pop_back(); } // Meta data // ================================================================================ // void declare(param_type*, const char* key, const char* value) override { //m_owner.log(std::string("faust~: declare ") + std::string(key) + std::string(" - ") + std::string(value)); } // ================================================================================ // // The Kiwi interface // ================================================================================ // void log() { std::lock_guard<std::mutex> guard(m_mutex_glue); m_owner.log("faust~: number of parameters " + std::to_string(m_params_short.size())); for(auto const& param : m_params_short) { m_owner.log("faust~: parameter " + param.first + " " + param.second.toString()); } } param_type getOutput(const std::string& name) { if(m_mutex_glue.try_lock()) { auto it = m_outputs.find(name); if(it == m_outputs.end()) { m_mutex_glue.unlock(); m_owner.warning(std::string("no such FAUST interface \"") + name + std::string("\"")); return 0; } param_type value = *(it->second.zone); m_mutex_glue.unlock(); return value; } return 0; } bool hasOutput(const std::string& name) { if(m_mutex_glue.try_lock()) { auto it = m_outputs.find(name); if(it == m_outputs.end()) { m_mutex_glue.unlock(); return false; } m_mutex_glue.unlock(); return true; } return false; } void setInput(const std::string& name, param_type value) { if(m_mutex_glue.try_lock()) { auto it = m_params_short.find(name); if(it == m_params_short.end()) { it = m_params_long.find(name); if(it == m_params_long.end()) { m_mutex_glue.unlock(); m_owner.warning(std::string("no such FAUST interface \"") + name + std::string("\"")); return; } } if(it->second.dirty) { m_mutex_glue.unlock(); m_owner.warning(std::string("FAUST interfaces \"") + name + std::string("\" not valid anymore")); return; } if(it->second.type == Parameter::Type::Button) { *(it->second.zone) = 0; *(it->second.zone) = 1; m_mutex_glue.unlock(); m_owner.schedule([this, name]() { if(m_mutex_glue.try_lock()) { auto it = m_params_short.find(name); if(it != m_params_short.end()) { *(it->second.zone) = 0; } m_mutex_glue.unlock(); } } , std::chrono::milliseconds(static_cast<size_t>(std::floor(m_owner.getBlockSizeInMS())))); return; } else if(it->second.type == Parameter::Type::CheckButton) { *(it->second.zone) = static_cast<param_type>(value < std::numeric_limits<param_type>::epsilon()); m_mutex_glue.unlock(); return; } else if(it->second.type == Parameter::Type::Float) { *(it->second.zone) = std::max(std::min(it->second.max, value), it->second.min); m_mutex_glue.unlock(); return; } m_owner.warning(std::string("FAUST interface \"") + name + std::string("\" is doesn't requires a value")); m_mutex_glue.unlock(); return; } m_owner.warning(std::string("FAUST interfaces being processed - please wait")); } void resetToDefault() { std::lock_guard<std::mutex> guard(m_mutex_glue); for(auto& param : m_params_short) { *param.second.zone = param.second.dflt; } } void saveStates() { std::lock_guard<std::mutex> guard(m_mutex_glue); for(auto& param : m_params_short) { if(param.second.type != Parameter::Type::Button) { param.second.saved = *param.second.zone; } } } void recallStates() { std::lock_guard<std::mutex> guard(m_mutex_glue); for(auto& param : m_params_short) { if(param.second.type != Parameter::Type::Button) { *param.second.zone = param.second.saved; } } } void prepareChanges() { std::lock_guard<std::mutex> guard(m_mutex_glue); for(auto& param : m_params_short) { param.second.dirty = true; } m_params_path.clear(); m_params_long.clear(); m_outputs.clear(); } void finishChanges() { std::lock_guard<std::mutex> guard(m_mutex_glue); for(auto it = m_params_short.begin(); it != m_params_short.end();) { if(it->second.dirty) { it = m_params_short.erase(it); } else { it++; } } m_params_path.clear(); } private: //! @brief The Parameter class Parameter { public: enum class Type { Button, CheckButton, Float }; Type type; param_type* zone; param_type min; param_type max; param_type step; param_type dflt; param_type saved; bool dirty; // If the parameter should be deleted std::string toString() const { return std::string((type == Type::Button) ? " button" : ((type == Type::CheckButton) ? " check button" : "float")) + " [" + std::to_string(min) + " " + std::to_string(max) + "] " + std::to_string(dflt); } }; std::string getLongName(const char* name) { std::string longname; for(auto const& step : m_params_path) longname += step + "/"; return longname + name; } void addParameter(const char* name, Parameter::Type type, param_type* zone, param_type min, param_type max, param_type step, param_type init) { std::lock_guard<std::mutex> guard(m_mutex_glue); auto it = m_params_short.find(name); if(it != m_params_short.end()) { if(it->second.type != type || it->second.min != min || it->second.max != max || it->second.step != step || it->second.dflt != init) { it->second = Parameter({type, zone, min, max, step, init, init, false}); m_params_long[getLongName(name)] = it->second; *zone = init; } else { it->second.saved = *it->second.zone; it->second.zone = zone; it->second.dirty = false; m_params_long[getLongName(name)] = it->second; *zone = it->second.saved; } } else { m_params_short[name] = Parameter({type, zone, min, max, step, init, init, false}); m_params_long[getLongName(name)] = it->second; *zone = init; } } void addOutput(const char* name, param_type* zone, param_type min, param_type max) { std::lock_guard<std::mutex> guard(m_mutex_glue); m_outputs[name] = Parameter({Parameter::Type::Float, zone, min, max, 0, 0, 0, false}); } std::map<std::string, Parameter> m_params_short; std::map<std::string, Parameter> m_params_long; std::map<std::string, Parameter> m_outputs; std::vector<std::string> m_params_path; FaustTilde& m_owner; std::mutex m_mutex_glue; }; }}
13,714
C++
.cpp
323
27.563467
218
0.434272
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,330
KiwiDsp_Chain.cpp
Musicoll_Kiwi/Modules/KiwiDsp/KiwiDsp_Chain.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include "KiwiDsp_Chain.h" #include "KiwiDsp_Misc.h" namespace kiwi { namespace dsp { // ==================================================================================== // // NODE // // ==================================================================================== // Chain::Node::Node(std::shared_ptr<Processor> processor) : m_processor(processor), m_inlets(), m_outlets(), m_inputs(), m_outputs(), m_buffer_copy(), m_index(0) { const size_t inlets = processor->getNumberOfInputs(); const size_t outlets = processor->getNumberOfOutputs(); if(inlets) { m_inlets.reserve(inlets); for(size_t i = 0; i < inlets; ++i) { m_inlets.emplace_back(*this, i); } } if(outlets) { m_outlets.reserve(outlets); for(size_t i = 0; i < outlets; ++i) { m_outlets.emplace_back(*this, i); } } m_buffer_copy.resize(processor->getNumberOfInputs()); } Chain::Node::~Node() { try { m_processor->release(); } catch(Error& e) { } } bool Chain::Node::connectInput(const size_t input_index, Node& other_node, const size_t output_index) { assert(input_index < m_inlets.size() && output_index < other_node.m_outlets.size()); return m_inlets[input_index].connect(other_node.m_outlets[output_index]); } bool Chain::Node::disconnectInput(const size_t input_index, Node& other_node, const size_t output_index) { assert(input_index < m_inlets.size() && output_index < other_node.m_outlets.size()); return m_inlets[input_index].disconnect(other_node.m_outlets[output_index]); } bool Chain::Node::prepare(Chain& chain) { // ======================================================================== // // INITIALIZE SAMPLE RATE, VECTOR SIZE // // ======================================================================== // size_t samplerate = chain.getSampleRate(); size_t vectorsize = chain.getVectorSize(); // ======================================================================== // // PREPARES INLETS, INPUT BUFFER // // ======================================================================== // std::vector<Signal::sPtr> inputs; for(Pin& inlet : m_inlets) { if (inlet.m_ties.size() == 0) { inlet.m_signal = chain.getSignalIn(); } else if(inlet.m_ties.size() == 1) { inlet.m_signal = inlet.m_ties.begin()->m_pin.m_signal; } else { inlet.m_signal = chain.getSignalInlet(inlet.m_index); std::vector<std::shared_ptr<Signal>> tie_signals; for(Tie tie : inlet.m_ties) { tie_signals.push_back(tie.m_pin.m_signal); } m_buffer_copy[inlet.m_index].setChannels(tie_signals); } inputs.push_back(inlet.m_signal); } m_inputs.setChannels(inputs); // ======================================================================== // // PREPARE OUTLETS, OUTPUT BUFFER // // ======================================================================== // std::vector<Signal::sPtr> outputs; for(Pin& outlet : m_outlets) { if (outlet.m_ties.size() == 0) { outlet.m_signal = chain.getSignalOutlet(outlet.m_index); } else { outlet.m_signal = std::make_shared<Signal>(vectorsize); } outputs.push_back(outlet.m_signal); } m_outputs.setChannels(outputs); // ======================================================================== // // INITIALIZE INFO FOR PREPARING PROCESSOR // // ======================================================================== // std::vector<bool> input_status(m_inlets.size()); for (size_t i = 0; i < m_inlets.size(); ++i) { input_status[i] = !m_inlets[i].m_ties.empty(); } Processor::PrepareInfo prepare_info {samplerate, vectorsize, input_status}; // ======================================================================== // // PREPARE PROCESSORS // // ======================================================================== // m_processor->prepare(prepare_info); return m_processor->shouldPerform(); } void Chain::Node::perform() noexcept { const size_t nchannels = m_buffer_copy.size(); for(size_t i = 0; i < nchannels; ++i) { Buffer const& buffer_copy = m_buffer_copy[i]; if(!buffer_copy.empty()) { Signal& inputs = m_inputs[i]; inputs.copy(buffer_copy[0]); const size_t ncopies = buffer_copy.getNumberOfChannels(); for(size_t j = 1; j < ncopies; ++j) { inputs.add(buffer_copy[j]); } } } m_processor->perform(m_inputs, m_outputs); } void Chain::Node::release() { m_index = 0; // ======================================================================== // // RELEASE INLET AND INPUT BUFFER // // ======================================================================== // for (Pin& inlet : m_inlets) { inlet.m_signal.reset(); } m_inputs.clear(); // ======================================================================== // // RELEASE INLET AND INPUT BUFFER // // ======================================================================== // for (Pin& outlet : m_outlets) { outlet.m_signal.reset(); } m_outputs.clear(); // ======================================================================== // // CLEAR BUFFER COPY // // ======================================================================== // std::for_each(m_buffer_copy.begin(), m_buffer_copy.end(), [](Buffer &buf){ buf.clear();}); // ======================================================================== // // RELEASE PROCESSOR // // ======================================================================== / m_processor->release(); } // ==================================================================================== // // NODE::PIN // // ==================================================================================== // Chain::Node::Pin::Pin(Node& owner, const size_t index) : m_owner(owner), m_index(index), m_signal(), m_ties() { ; } Chain::Node::Pin::Pin(Pin && other): m_owner(other.m_owner), m_index(other.m_index), m_signal(std::move(other.m_signal)), m_ties(std::move(other.m_ties)) { } Chain::Node::Pin::~Pin() { disconnect(); } bool Chain::Node::Pin::connect(Pin& other_pin) { return m_ties.insert(Tie(other_pin)).second && other_pin.m_ties.insert(Tie(*this)).second; } bool Chain::Node::Pin::disconnect(Pin& other_pin) { return m_ties.erase(Tie(other_pin)) && other_pin.m_ties.erase(Tie(*this)); } void Chain::Node::Pin::disconnect() { for (std::set<Tie>::iterator tie = m_ties.begin(); tie != m_ties.end();) { tie->m_pin.m_ties.erase(Tie(*this)); tie = m_ties.erase(tie); } } // ==================================================================================== // // NODE::TIE // // ==================================================================================== // Chain::Node::Tie::Tie(Pin& pin): m_pin(pin) { } bool Chain::Node::Tie::operator<(Tie const& other) const noexcept { return (&m_pin.m_owner < &other.m_pin.m_owner || (&m_pin.m_owner == &other.m_pin.m_owner && m_pin.m_index < other.m_pin.m_index)); } // ==================================================================================== // // CHAIN // // ==================================================================================== // Chain::Chain() : m_nodes(), m_sample_rate(), m_vector_size(), m_state(State::NotPrepared), m_tick_mutex() { ; } Chain::~Chain() { m_nodes.clear(); } // ============================================================================ // // THE UPDATE AND PREPARE // // ============================================================================ // void Chain::update() { if (!m_commands.empty()) { State prev_state = m_state; const size_t prev_samplerate = getSampleRate(); const size_t prev_vectorsize = getVectorSize(); release(); while(!m_commands.empty()) { m_commands.front().operator()(); m_commands.pop_front(); } if (prev_state == State::Prepared || prev_state == State::Preparing) { prepare(prev_samplerate, prev_vectorsize); } } } void Chain::prepare(const size_t samplerate, const size_t vector_size) { release(); update(); m_state = State::Preparing; m_sample_rate = samplerate; m_vector_size = vector_size; indexNodes(); sortNodes(); for(auto node = m_nodes.begin(); node != m_nodes.end();) { if ((*node)->prepare(*this)) { ++node; } else { restackNode(**node); node = m_nodes.erase(node); } } m_state = State::Prepared; } void Chain::restackNode(Node & node) { // ======================================================================== // // RESTACK INLET CONNECTIONS // // ======================================================================== // for(Node::Pin& inlet : node.m_inlets) { for(Node::Tie tie : inlet.m_ties) { Node::Pin& prev_pin = tie.m_pin; Node& prev_node = tie.m_pin.m_owner; std::function<void(void)> call_back = std::bind(&Chain::execConnect, this, prev_node.m_processor.get(), prev_pin.m_index, node.m_processor.get(), inlet.m_index); m_commands.push_front(call_back); } } // ======================================================================== // // RESTACK OUTLET CONNECTIONS // // ======================================================================== // for(Node::Pin& outlet : node.m_outlets) { for(Node::Tie tie : outlet.m_ties) { Node::Pin& next_pin = tie.m_pin; Node& next_node = tie.m_pin.m_owner; std::function<void(void)> call_back = std::bind(&Chain::execConnect, this, node.m_processor.get(), outlet.m_index, next_node.m_processor.get(), next_pin.m_index); m_commands.push_front(call_back); } } // ======================================================================== // // RESTACK PROCESSOR // // ======================================================================== // m_commands.push_front(std::bind(&Chain::execAddProcessor, this, node.m_processor)); } // ============================================================================ // // THE RELEASE METHOD // // ============================================================================ // void Chain::release() { std::lock_guard<std::mutex> lock(m_tick_mutex); m_state = State::NotPrepared; m_sample_rate = 0.; m_vector_size = 0.; for(auto node = m_nodes.begin(); node != m_nodes.end(); ++node) { (*node)->release(); } } size_t Chain::getSampleRate() const noexcept { return m_sample_rate; } size_t Chain::getVectorSize() const noexcept { return m_vector_size; } void Chain::tick() noexcept { std::unique_lock<std::mutex> lock(m_tick_mutex, std::defer_lock); if (m_state == State::Prepared && lock.try_lock()) { size_t const node_number = m_nodes.size(); for(size_t i = 0; i < node_number; ++i) { m_nodes[i]->perform(); } lock.unlock(); } } // ============================================================================ // // NODE MANGEMENT // // ============================================================================ // struct Chain::compare_proc { compare_proc(Processor const& proc):m_proc(proc){} bool operator()(Node::uPtr const& node) { return &m_proc == &(*node->m_processor); } Processor const& m_proc; }; std::vector<Chain::Node::uPtr>::iterator Chain::findNode(Processor& proc) { return std::find_if(m_nodes.begin(), m_nodes.end(), compare_proc(proc)); } std::vector<std::unique_ptr<Chain::Node>>::const_iterator Chain::findNode(Processor& proc) const { return std::find_if(m_nodes.begin(), m_nodes.end(), compare_proc(proc)); } struct Chain::index_node { index_node(): m_next_index(1ul){} void computeIndex(Node& node) { if (node.m_index == 0) { m_loop_nodes.insert(&node); for(Node::Pin& inlet : node.m_inlets) { for(Node::Tie tie : inlet.m_ties) { Node& parent_node = tie.m_pin.m_owner; if (!parent_node.m_index) { if (m_loop_nodes.find(&parent_node) != m_loop_nodes.end()) { throw LoopError("A loop is detected"); } else { this->computeIndex(parent_node); } } } } m_loop_nodes.erase(&node); node.m_index = m_next_index++; } } void operator()(Node::uPtr const& node) { computeIndex(*node.get()); } size_t m_next_index; std::set<Node*> m_loop_nodes; }; void Chain::indexNodes() { for_each(m_nodes.begin(), m_nodes.end(), index_node()); } void Chain::sortNodes() { struct compare_index { bool operator()(std::unique_ptr<Node> const& l_node, std::unique_ptr<Node> const& r_node) { return l_node->m_index < r_node->m_index; } }; std::sort(m_nodes.begin(), m_nodes.end(), compare_index()); } // ============================================================================ // // NODE MODIFICATIONS // // ============================================================================ // void Chain::addProcessor(std::shared_ptr<Processor> processor) { std::function<void(void)> func = std::bind(&Chain::execAddProcessor, this, processor); m_commands.push_back(func); } void Chain::removeProcessor(Processor& proc) { std::function<void(void)> func = std::bind(&Chain::execRemoveProcessor, this, &proc); m_commands.push_back(func); } void Chain::connect(Processor& source, size_t outlet_index, Processor& dest, size_t inlet_index) { std::function<void(void)> call_back = std::bind(&Chain::execConnect, this, &source, outlet_index, &dest, inlet_index); m_commands.push_back(call_back); } void Chain::disconnect(Processor& source, size_t outlet_index, Processor& dest, size_t inlet_index) { std::function<void(void)> call_back = std::bind(&Chain::execDisconnect, this, &source, outlet_index, &dest, inlet_index); m_commands.push_back(call_back); } // ==================================================================================== // // SIGNAL MANAGEMENT // // ==================================================================================== // std::shared_ptr<Signal> Chain::getSignalIn() { std::shared_ptr<Signal> signal_in = m_signal_in.lock(); if (!signal_in) { signal_in = std::make_shared<Signal>(m_vector_size); m_signal_in = signal_in; } return signal_in; } std::shared_ptr<Signal> Chain::getSignalInlet(size_t inlet_index) { std::shared_ptr<Signal> signal_inlet = m_signal_inlet[inlet_index].lock(); if (!signal_inlet) { signal_inlet = std::make_shared<Signal>(m_vector_size); m_signal_inlet[inlet_index] = signal_inlet; } return signal_inlet; } std::shared_ptr<Signal> Chain::getSignalOutlet(size_t outlet_index) { std::shared_ptr<Signal> signal_outlet = m_signal_outlet[outlet_index].lock(); if (!signal_outlet) { signal_outlet = std::make_shared<Signal>(m_vector_size); m_signal_outlet[outlet_index] = signal_outlet; } return signal_outlet; } // ==================================================================================== // // CHAIN COMMANDS // // ==================================================================================== // void Chain::execAddProcessor(std::shared_ptr<Processor> proc) { if (findNode(*proc) == m_nodes.end()) { m_nodes.emplace_back(Node::uPtr(new Node(proc))); } else { throw Error("Adding same processor twice"); } } void Chain::execRemoveProcessor(Processor* proc) { auto node = findNode(*proc); if (node != m_nodes.end()) { m_nodes.erase(findNode(*proc)); } else { throw Error("Removing non existing processor"); } } void Chain::execConnect(Processor* source, size_t outlet_index, Processor* dest, size_t inlet_index) { auto source_node = findNode(*source); auto dest_node = findNode(*dest); if (source_node != m_nodes.end() && dest_node != m_nodes.end()) { (*dest_node)->connectInput(inlet_index, **source_node, outlet_index); } else { throw Error("Connecting two non existing nodes : "); } } void Chain::execDisconnect(Processor* source, size_t outlet_index, Processor* dest, size_t inlet_index) { auto source_node = findNode(*source); auto dest_node = findNode(*dest); if (source_node != m_nodes.end() && dest_node != m_nodes.end()) { (*dest_node)->disconnectInput(inlet_index, **source_node, outlet_index); } else { throw Error("Disconnecting non existing node : "); } } } }
26,508
C++
.cpp
562
29.83274
115
0.348434
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,331
KiwiDsp_Signal.cpp
Musicoll_Kiwi/Modules/KiwiDsp/KiwiDsp_Signal.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include "KiwiDsp_Signal.h" #include "KiwiDsp_Misc.h" namespace kiwi { namespace dsp { // ================================================================================ // // SIGNAL // // ================================================================================ // Signal::Signal(const size_t size, const sample_t val) : m_size(size), m_samples(new sample_t[size]) { assert(size && "size must be greater than 0"); fill(val); } Signal::Signal(Signal&& other) noexcept : m_size(std::move(other.m_size)), m_samples(std::move(other.m_samples)) { other.m_size = 0ul; other.m_samples = nullptr; } Signal& Signal::operator=(Signal&& other) noexcept { m_size = std::move(other.m_size); m_samples = std::move(other.m_samples); other.m_size = 0ul; other.m_samples = nullptr; return *this; } Signal::~Signal() { if(m_samples != nullptr) { delete [] m_samples; } m_samples = nullptr; m_size = 0ul; } size_t Signal::size() const noexcept { return m_size; } sample_t const* Signal::data() const noexcept { return const_cast<sample_t const*>(m_samples); } sample_t* Signal::data() noexcept { return m_samples; } sample_t const& Signal::operator[](const size_t index) const { assert(index < size() && "Index out of range."); return m_samples[index]; } sample_t& Signal::operator[](const size_t index) { assert(index < size() && "Index out of range."); return m_samples[index]; } void Signal::fill(sample_t const& value) noexcept { std::fill(m_samples, m_samples + m_size, value); } void Signal::copy(Signal const& other_signal) noexcept { assert(m_size == other_signal.size() && "Copying signals of different size"); sample_t const* in = other_signal.m_samples; sample_t* out = m_samples; for(size_t i = m_size>>3; i; --i, in += 8, out += 8) { out[0] = in[0]; out[1] = in[1]; out[2] = in[2]; out[3] = in[3]; out[4] = in[4]; out[5] = in[5]; out[6] = in[6]; out[7] = in[7]; } for(size_t i = m_size&7; i; --i, in++, out++) { out[0] = in[0]; } } void Signal::add(Signal const& other_signal) noexcept { assert(m_size == other_signal.size() && "Adding signals of different size"); sample_t const* in = other_signal.m_samples; sample_t* out = m_samples; for(size_t i = m_size>>3; i; --i, in += 8, out += 8) { out[0] += in[0]; out[1] += in[1]; out[2] += in[2]; out[3] += in[3]; out[4] += in[4]; out[5] += in[5]; out[6] += in[6]; out[7] += in[7]; } for(size_t i = m_size&7; i; --i, in++, out++) { out[0] += in[0]; } } void Signal::add(Signal const& signal_1, Signal const& signal_2, Signal& result) { const size_t size = signal_1.size(); assert(size == signal_2.size() && "The two signals must have an equal size"); sample_t const* in1 = signal_1.m_samples; sample_t const* in2 = signal_2.m_samples; sample_t* out = result.m_samples; for(size_t i = size>>3; i; --i, in1 += 8, in2 += 8, out += 8) { out[0] = in1[0] + in2[0]; out[1] = in1[1] + in2[1]; out[2] = in1[2] + in2[2]; out[3] = in1[3] + in2[3]; out[4] = in1[4] + in2[4]; out[5] = in1[5] + in2[5]; out[6] = in1[6] + in2[6]; out[7] = in1[7] + in2[7]; } for(size_t i = size&7; i; --i, in1++, in2++, out++) { out[0] = in1[0] + in2[0]; } } // ================================================================================ // // BUFFER // // ================================================================================ // Buffer::Buffer(): m_vectorsize(), m_signals() { } Buffer::Buffer(std::vector<Signal::sPtr> signals) { const size_t nsignals = signals.size(); if(nsignals) { m_signals.reserve(nsignals); const Signal::sPtr first_sig(signals[0]); const size_t vectorsize = first_sig->size(); m_signals.emplace_back(std::move(first_sig)); for(size_t i = 1; i < signals.size(); ++i) { const Signal::sPtr sig(signals[i]); assert(sig->size() == vectorsize && "Aggregating signals with different vector size"); m_signals.emplace_back(std::move(sig)); } m_vectorsize = vectorsize; } else { m_vectorsize = 0; } } Buffer::Buffer(const size_t nchannels, const size_t nsamples, const sample_t val) : m_vectorsize(nsamples) { m_signals.reserve(nchannels); for(size_t i = 0ul; i < nchannels; i++) { m_signals.emplace_back(std::make_shared<Signal>(nsamples, val)); } } Buffer::Buffer(Buffer&& other) noexcept : m_vectorsize(std::move(other.m_vectorsize)), m_signals(std::move(other.m_signals)) { other.m_vectorsize = 0ul; } Buffer& Buffer::operator=(Buffer&& other) noexcept { m_vectorsize = std::move(other.m_vectorsize); m_signals = std::move(other.m_signals); other.m_vectorsize = 0; return *this; } Buffer::~Buffer() { ; } void Buffer::setChannels(std::vector<Signal::sPtr> signals) { m_signals.clear(); const size_t nsignals = signals.size(); if(nsignals) { m_signals.reserve(nsignals); const Signal::sPtr first_sig(signals[0]); const size_t vectorsize = first_sig->size(); m_signals.emplace_back(std::move(first_sig)); for(int i = 1; i < signals.size(); ++i) { const Signal::sPtr sig(signals[i]); assert(sig->size() == vectorsize && "Aggregating signals with different vector size"); m_signals.emplace_back(std::move(sig)); } m_vectorsize = vectorsize; } else { m_vectorsize = 0; } } void Buffer::clear() { m_signals.clear(); } size_t Buffer::getVectorSize() const noexcept { return m_vectorsize; } size_t Buffer::getNumberOfChannels() const noexcept { return m_signals.size(); } bool Buffer::empty() const noexcept { return (m_signals.size() == 0ul); } Signal const& Buffer::operator[](const size_t index) const { assert(index < m_signals.size() && "Index out of range."); return *m_signals[index].get(); } Signal& Buffer::operator[](const size_t index) { assert(index < m_signals.size() && "Index out of range."); return *m_signals[index].get(); } } }
9,618
C++
.cpp
239
26.523013
94
0.441871
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,332
KiwiServer_Server.cpp
Musicoll_Kiwi/Modules/KiwiServer/KiwiServer_Server.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiServer/KiwiServer_Server.h> #include <json.hpp> #include <flip/BackEndBinary.h> #include <flip/contrib/DataProviderFile.h> #include <flip/contrib/DataConsumerFile.h> #include <flip/contrib/RunLoopTimer.h> #include <KiwiModel/KiwiModel_DataModel.h> #include <KiwiModel/KiwiModel_Def.h> #include <KiwiModel/KiwiModel_Converters/KiwiModel_Converter.h> #include <iomanip> namespace kiwi { namespace server { // ================================================================================ // // SERVER // // ================================================================================ // using json = nlohmann::json; std::string hexadecimal_convert(uint64_t hexa_decimal) { std::stringstream converter; converter << std::setfill('0') << std::setw(16) << std::hex << hexa_decimal; return converter.str(); } const char* Server::kiwi_file_extension = "kiwi"; Server::Server(uint16_t port, juce::File backend_directory, std::string const& open_token, std::string const& kiwi_version) : m_backend_directory(std::move(backend_directory)) , m_open_token(open_token) , m_kiwi_version(kiwi_version) , m_sessions() , m_socket(*this, port) , m_ports() , m_logger(m_backend_directory.getChildFile("log.txt"), "server port: " + std::to_string(port) + " server model version: " + KIWI_MODEL_VERSION_STRING + " server kiwi version: " + m_kiwi_version) { if (m_backend_directory.exists() && !m_backend_directory.isDirectory()) { throw std::runtime_error("Specified backend directory is a file"); } else if(!m_backend_directory.exists()) { m_backend_directory.createDirectory(); } if(!createEmptyDocument()) { throw std::runtime_error("Failed to create empty document"); } } Server::~Server() { m_socket.reset(); } void Server::process() { m_socket.process(); } std::set<uint64_t> Server::getSessions() const { std::set<uint64_t> sessions; for(auto & session : m_sessions) { sessions.insert(session.first); } return sessions; } std::set<uint64_t> Server::getConnectedUsers(uint64_t session_id) const { auto session = m_sessions.find(session_id); return session != m_sessions.end() ? session->second.getConnectedUsers() : std::set<uint64_t>(); } bool Server::createEmptyDocument() { juce::File empty_file = m_backend_directory.getChildFile("empty").withFileExtension(".kiwi"); if (!empty_file.exists()) { if (empty_file.create().wasOk()) { model::PatcherValidator validator; flip::DocumentServer empty_document(model::DataModel::use(), validator, 0); empty_document.commit(); flip::BackEndIR backend(empty_document.write()); flip::DataConsumerFile consumer(empty_file.getFullPathName().toStdString().c_str()); backend.write<flip::BackEndBinary>(consumer); } } return empty_file.exists(); } juce::File Server::getSessionFile(uint64_t session_id) const { return m_backend_directory.getChildFile(juce::String(hexadecimal_convert(session_id))) .withFileExtension(kiwi_file_extension); } void Server::onConnected(flip::PortBase & port) { const auto session_id = port.session(); const auto session = m_sessions.find(session_id); if(session == m_sessions.end()) { juce::File session_file = getSessionFile(session_id); const auto session_hex_id = hexadecimal_convert(session_id); m_logger.log("Creating new session (" + session_hex_id + ")"); auto session = m_sessions .insert(std::make_pair(session_id, Session(session_id, session_file, m_open_token, m_kiwi_version, m_logger))); if (session_file.exists()) { //m_logger.log("loading session file for session_id : " + session_hex_id); if (!(*session.first).second.load()) { m_logger.log("opening document session : " + session_hex_id + " failed"); m_sessions.erase(session_id); throw std::runtime_error("loading session failed."); } } (*session.first).second.bind(port); } else { session->second.bind(port); } } void Server::onDisconnected(flip::PortBase & port) { port.impl_activate(false); auto session = m_sessions.find(port.session()); if (session != m_sessions.end()) { session->second.unbind(port); if (session->second.getConnectedUsers().empty()) { m_sessions.erase(session); } } } void Server::port_factory_add(flip::PortBase& port) { port.impl_bind (*this); m_ports.insert (&port); } void Server::port_factory_remove(flip::PortBase& port) { if (m_ports.erase (&port)) {port.impl_unbind (*this);} onDisconnected(port); } void Server::port_greet(flip::PortBase& port) { if (m_ports.erase (&port)) { port.impl_unbind (*this); } onConnected(port); } void Server::port_commit(flip::PortBase& /* port */, const flip::Transaction& /* tx */) { // nothing } void Server::port_squash(flip::PortBase& /* port */, const flip::TxIdRange& /* range */, const flip::Transaction& /* tx */) { // nothing } void Server::port_push(flip::PortBase& /* port */, const flip::Transaction& /* tx */) { // port was rebound in greet flip_FATAL; } void Server::port_signal(flip::PortBase& /* port */, const flip::SignalData& /* data */) { // port was rebound in greet flip_FATAL; } // ================================================================================ // // SERVER LOGGER // // ================================================================================ // Server::Logger::Logger(juce::File const& file, juce::String const& welcome): m_limit(10 * 1000 * 1000), // 10 Mo m_jlogger(file, welcome, m_limit) { } Server::Logger::~Logger() { } void Server::Logger::log(juce::String const& message) { if (m_jlogger.getLogFile().getSize() > m_limit) { juce::FileLogger::trimFileSize(m_jlogger.getLogFile(), m_limit); } auto time = juce::Time::Time::getCurrentTime().toString(true, true, true); juce::String log = "[server] - "; log << time << juce::newLine; log << message; m_jlogger.logMessage(log); } // ================================================================================ // // SERVER SESSION // // ================================================================================ // Server::Session::Session(Session && other) : m_identifier(other.m_identifier) , m_hex_id(other.m_hex_id) , m_validator(std::move(other.m_validator)) , m_document(std::move(other.m_document)) , m_signal_connections(std::move(other.m_signal_connections)) , m_backend_file(std::move(other.m_backend_file)) , m_token(std::move(other.m_token)) , m_kiwi_version(std::move(other.m_kiwi_version)) , m_logger(other.m_logger) { ; } Server::Session::Session(uint64_t identifier, juce::File const& backend_file, std::string const& token, std::string const& kiwi_version, Server::Logger & logger) : m_identifier(identifier) , m_hex_id(hexadecimal_convert(identifier)) , m_validator(new model::PatcherValidator()) , m_document(new flip::DocumentServer(model::DataModel::use(), *m_validator, m_identifier)) , m_signal_connections() , m_backend_file(backend_file) , m_token(token) , m_kiwi_version(kiwi_version) , m_logger(logger) { model::Patcher& patcher = m_document->root<model::Patcher>(); auto cnx = patcher.signal_get_connected_users.connect(std::bind(&Server::Session::sendConnectedUsers, this)); m_signal_connections.emplace_back(std::move(cnx)); } Server::Session::~Session() { if (m_document) { for (auto* port : m_document->ports()) { m_document->port_factory_remove(*port); } } } uint64_t Server::Session::getId() const { return m_identifier; } bool Server::Session::save() const { flip::BackEndIR backend(m_document->write()); flip::DataConsumerFile consumer(m_backend_file.getFullPathName().toStdString().c_str()); try { backend.write<flip::BackEndBinary>(consumer); } catch(...) { return false; } return true; } bool Server::Session::load() { bool success = false; flip::BackEndIR backend; backend.register_backend<flip::BackEndBinary>(); flip::DataProviderFile provider(m_backend_file.getFullPathName().toStdString().c_str()); try { backend.read(provider); } catch (...) { m_logger.log("Fail to read " + m_backend_file.getFileName().toStdString()); return false; } const auto current_version = model::Converter::getLatestVersion(); const auto backend_version = backend.version; if(!model::Converter::canConvertToLatestFrom(backend_version)) { m_logger.log("Bad document version: no conversion available from " + backend_version + " to " + current_version); return false; } if (model::Converter::process(backend)) { try { m_document->read(backend); m_document->commit(); success = true; } catch(...) { m_logger.log("Failed to read " + m_backend_file.getFileName().toStdString()); return false; } } else { m_logger.log("Failed to convert document from version " + backend_version + " to " + current_version); return false; } return success; } bool Server::Session::authenticateUser(uint64_t user, std::string metadata) const { json j; try { j = json::parse(metadata); } catch (json::parse_error& e) { std::cout << "message: " << e.what() << '\n'; return false; } static const auto model_version = "model_version"; static const auto open_token = "open_token"; static const auto kiwi_version = "kiwi_version"; return ((j.count(model_version) && j[model_version] == KIWI_MODEL_VERSION_STRING) && (j.count(open_token) && j[open_token] == m_token) && (j.count(kiwi_version) && j[kiwi_version] == m_kiwi_version)); } void Server::Session::bind(flip::PortBase & port) { m_logger.log("user (" + std::to_string(port.user()) + ") connecting to session (" + hexadecimal_convert(m_identifier) + ")"); if (authenticateUser(port.user(), port.metadata())) { // disconnect client if already connected. std::set<flip::PortBase*> ports = m_document->ports(); std::set<flip::PortBase*>::iterator port_user = std::find_if(ports.begin(), ports.end(), [&port](flip::PortBase * const document_port) { return document_port->user() == port.user(); }); if (port_user != ports.end()) { m_document->port_factory_remove(**port_user); } m_document->port_factory_add(port); m_document->port_greet(port); model::Patcher& patcher = m_document->root<model::Patcher>(); std::set<uint64_t> user_lit = getConnectedUsers(); std::vector<uint64_t> users(user_lit.begin(), user_lit.end()); // send a list of connected users to the user that is connecting. m_document->send_signal_if(patcher.signal_receive_connected_users.make(users), [&port](flip::PortBase& current_port) { return port.user() == current_port.user(); }); // Notify other users that this one is connected. m_document->send_signal_if(patcher.signal_user_connect.make(port.user()), [&port](flip::PortBase& current_port) { return port.user() != current_port.user(); }); } else { m_logger.log("user (" + std::to_string(port.user()) + ") failed to authenticate \n" + "with metadata : " + port.metadata()); throw std::runtime_error("authentication failed"); } } void Server::Session::unbind(flip::PortBase & port) { m_logger.log("disconnecting user (" + std::to_string(port.user()) + ") from session (" + m_hex_id + ')'); std::set<flip::PortBase*> ports = m_document->ports(); if (ports.find(&port) != ports.end()) { model::Patcher& patcher = m_document->root<model::Patcher>(); m_document->send_signal_if(patcher.signal_user_disconnect.make(port.user()), [](flip::PortBase& port) { return true; }); m_document->port_factory_remove(port); if (m_document->ports().empty()) { if(!m_backend_file.exists()) { m_backend_file.create(); } m_logger.log("saving session : " + m_hex_id + " in file : " + m_backend_file.getFileName().toStdString()); if (!save()) { m_logger.log("saving session to " + m_backend_file.getFileName() + " failed"); } } } } std::set<uint64_t> Server::Session::getConnectedUsers() const { std::set<uint64_t> users; auto const& ports = m_document->ports(); for(auto const& port : ports) { users.emplace(port->user()); } return users; } void Server::Session::sendConnectedUsers() const { model::Patcher& patcher = m_document->root<model::Patcher>(); std::set<uint64_t> user_list = getConnectedUsers(); std::vector<uint64_t> users(user_list.begin(), user_list.end()); m_document->reply_signal(patcher.signal_receive_connected_users.make(users)); } } }
19,888
C++
.cpp
430
28.897674
131
0.465852
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,333
KiwiApp.cpp
Musicoll_Kiwi/Client/Source/KiwiApp.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <KiwiModel/KiwiModel_DataModel.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Objects.h> #include <KiwiEngine/KiwiEngine_Objects/KiwiEngine_Objects.h> #include <KiwiApp_Patcher/KiwiApp_Factory.h> #include <KiwiApp_Patcher/KiwiApp_Objects/KiwiApp_Objects.h> #include <KiwiApp.h> #include <KiwiApp_General/KiwiApp_CommandIDs.h> #include <KiwiApp_General/KiwiApp_IDs.h> namespace kiwi { // ================================================================================ // // MENU // // ================================================================================ // KiwiApp::MainMenuModel::MainMenuModel() { setApplicationCommandManagerToWatch(&getCommandManager()); } juce::StringArray KiwiApp::MainMenuModel::getMenuBarNames() { return KiwiApp::use().getMenuNames(); } juce::PopupMenu KiwiApp::MainMenuModel::getMenuForIndex(int topLevelMenuIndex, const juce::String& menuName) { juce::PopupMenu menu; KiwiApp::use().createMenu(menu, menuName); return menu; } void KiwiApp::MainMenuModel::menuItemSelected(int menuItemID, int topLevelMenuIndex) { KiwiApp::use().handleMainMenuCommand(menuItemID); } //============================================================================== enum { objectHelpBaseID = 100, examplesBaseID = 300 }; // ================================================================================ // // ASYNC QUIT RETRIER // // ================================================================================ // class KiwiApp::AsyncQuitRetrier : private juce::Timer { public: AsyncQuitRetrier() { startTimer (500); } void timerCallback() { stopTimer(); delete this; if (JUCEApplicationBase* app = JUCEApplicationBase::getInstance()) { app->systemRequestedQuit(); } } JUCE_DECLARE_NON_COPYABLE(AsyncQuitRetrier) }; // ================================================================================ // // JUCEApplication // // ================================================================================ // void KiwiApp::initialise(juce::String const& commandLine) { #if ! JUCE_MAC if(sendCommandLineToPreexistingInstance()) { DBG ("Another instance is running - quitting..."); quit(); return; } #endif model::DataModel::init(); declareEngineObjects(); declareObjectViews(); initResources(); juce::Desktop::getInstance().setGlobalScaleFactor(1.); juce::LookAndFeel::setDefaultLookAndFeel(&m_looknfeel); m_command_manager = std::make_unique<juce::ApplicationCommandManager>(); m_settings = std::make_unique<StoredSettings>(); m_settings->network().addListener(*this); m_menu_model.reset(new MainMenuModel()); m_scheduler.reset(new tool::Scheduler<>()); m_api_controller.reset(new ApiController()); m_api.reset(new Api(*m_api_controller)); m_instance = std::make_unique<Instance>(); m_command_manager->registerAllCommandsForTarget(this); #if JUCE_WINDOWS openCommandFile(commandLine); #endif #if JUCE_MAC juce::PopupMenu macMainMenuPopup; macMainMenuPopup.addCommandItem(&getCommandManager(), CommandIDs::showAboutAppWindow); macMainMenuPopup.addSeparator(); macMainMenuPopup.addCommandItem(&getCommandManager(), CommandIDs::showAppSettingsWindow); juce::MenuBarModel::setMacMainMenu(m_menu_model.get(), &macMainMenuPopup, TRANS("Open Recent")); #endif pingServer(); startTimer(TimerIds::MainScheduler, 10); // main scheduler update startTimer(TimerIds::ServerPing, 3000); // Server ping } void KiwiApp::anotherInstanceStarted(juce::String const& command_line) { openCommandFile(command_line); } void KiwiApp::declareEngineObjects() { engine::NewBox::declare(); engine::ErrorBox::declare(); engine::Slider::declare(); engine::Print::declare(); engine::Receive::declare(); engine::Plus::declare(); engine::Times::declare(); engine::Delay::declare(); engine::Metro::declare(); engine::Pipe::declare(); engine::Bang::declare(); engine::Toggle::declare(); engine::AdcTilde::declare(); engine::DacTilde::declare(); engine::OscTilde::declare(); engine::Loadmess::declare(); engine::SigTilde::declare(); engine::TimesTilde::declare(); engine::PlusTilde::declare(); engine::MeterTilde::declare(); engine::DelaySimpleTilde::declare(); engine::Message::declare(); engine::NoiseTilde::declare(); engine::PhasorTilde::declare(); engine::SahTilde::declare(); engine::SnapshotTilde::declare(); engine::Trigger::declare(); engine::LineTilde::declare(); engine::Minus::declare(); engine::Divide::declare(); engine::Equal::declare(); engine::Less::declare(); engine::Greater::declare(); engine::Different::declare(); engine::Pow::declare(); engine::Modulo::declare(); engine::MinusTilde::declare(); engine::DivideTilde::declare(); engine::LessTilde::declare(); engine::GreaterTilde::declare(); engine::EqualTilde::declare(); engine::DifferentTilde::declare(); engine::LessEqual::declare(); engine::LessEqualTilde::declare(); engine::GreaterEqual::declare(); engine::GreaterEqualTilde::declare(); engine::Comment::declare(); engine::Pack::declare(); engine::Unpack::declare(); engine::Random::declare(); engine::Scale::declare(); engine::Select::declare(); engine::Number::declare(); engine::NumberTilde::declare(); engine::Hub::declare(); engine::Mtof::declare(); engine::Send::declare(); engine::Gate::declare(); engine::Switch::declare(); engine::GateTilde::declare(); engine::SwitchTilde::declare(); engine::Float::declare(); engine::ClipTilde::declare(); engine::Clip::declare(); engine::SfPlayTilde::declare(); engine::SfRecordTilde::declare(); engine::FaustTilde::declare(); engine::Route::declare(); engine::OSCReceive::declare(); engine::OSCSend::declare(); } void KiwiApp::declareObjectViews() { SliderView::declare(); BangView::declare(); ToggleView::declare(); MeterTildeView::declare(); MessageView::declare(); CommentView::declare(); NumberView::declare(); NumberTildeView::declare(); } void KiwiApp::shutdown() { #if JUCE_MAC juce::MenuBarModel::setMacMainMenu(nullptr); #endif stopTimer(TimerIds::MainScheduler); stopTimer(TimerIds::ServerPing); m_instance.reset(); m_api->cancelAll(); m_api.reset(); m_api_controller.reset(); m_scheduler.reset(); m_settings.reset(); } void KiwiApp::systemRequestedQuit() { if(juce::ModalComponentManager::getInstance()->cancelAllModalComponents()) { new AsyncQuitRetrier(); } else { if(m_instance->closeAllPatcherWindows()) { quit(); } } } const juce::String KiwiApp::getApplicationName() { return ProjectInfo::projectName; } const juce::String KiwiApp::getApplicationVersion() { return ProjectInfo::versionString; } bool KiwiApp::moreThanOneInstanceAllowed() { return true; } void KiwiApp::timerCallback(int timer_id) { if(timer_id == TimerIds::MainScheduler) { m_instance->tick(); m_scheduler->process(); } else if(timer_id == TimerIds::ServerPing) { // ping server pingServer(); } } bool KiwiApp::isMacOSX() { return (juce::SystemStats::getOperatingSystemType() & juce::SystemStats::MacOSX) != 0; } bool KiwiApp::isLinux() { return juce::SystemStats::getOperatingSystemType() == juce::SystemStats::Linux; } bool KiwiApp::isWindows() { return (juce::SystemStats::getOperatingSystemType() & juce::SystemStats::Windows) != 0; } // ================================================================================ // // STATIC QUERY // // ================================================================================ // KiwiApp& KiwiApp::use() { KiwiApp* const app = getApp(); assert(app != nullptr); return *app; } KiwiApp* KiwiApp::getApp() { return dynamic_cast<KiwiApp*>(JUCEApplication::getInstance()); } engine::Instance& KiwiApp::useEngineInstance() { return KiwiApp::use().m_instance->useEngineInstance(); } Instance& KiwiApp::useInstance() { return *KiwiApp::use().m_instance; } Api& KiwiApp::useApi() { return *KiwiApp::use().m_api; } tool::Scheduler<>& KiwiApp::useScheduler() { return *KiwiApp::use().m_scheduler; } juce::File KiwiApp::getKiwiResourcesDirectory() { using juce::File; const auto apppath = File::getSpecialLocation(File::SpecialLocationType::currentApplicationFile); #if JUCE_MAC return apppath.getChildFile("Contents/Resources"); #else return apppath.getParentDirectory(); #endif } juce::File KiwiApp::getKiwiObjectHelpDirectory() { static const auto helps = getKiwiResourcesDirectory().getChildFile("helps"); return helps; } juce::File KiwiApp::getKiwiExamplesDirectory() { static const auto examples = getKiwiResourcesDirectory().getChildFile("examples"); return examples; } void KiwiApp::initResources() { // initialise help file aliases, ex: // helpfile > < operators // will associate classname "<" and ">" to helpfile "operators.kiwihelp" static const auto help_aliases_filename = "help-alias.txt"; m_help_aliases.clear(); const auto help_dir = KiwiApp::use().getKiwiObjectHelpDirectory(); const auto help_aliases_file = help_dir.getChildFile(help_aliases_filename); if(help_aliases_file.existsAsFile()) { static const auto help_extension = ".kiwihelp"; juce::StringArray lines; help_aliases_file.readLines(lines); for (auto& line : lines) { auto tokens = juce::StringArray::fromTokens(line, " ", "\""); if(tokens.size() >= 3 && tokens[0] == "helpfile") { auto const& file_token = tokens.getReference(tokens.size() - 1); auto help_file = help_dir.getChildFile(file_token.unquoted() + help_extension); if(help_file.existsAsFile()) { for(int i = 1; i < tokens.size() - 1; ++i) { m_help_aliases.emplace(tokens[i].toStdString(), help_file); } } } } } } juce::File KiwiApp::findHelpFile(std::string const& classname) const { static const auto help_extension = ".kiwihelp"; const auto help_dir = KiwiApp::use().getKiwiObjectHelpDirectory(); auto help_file = help_dir.getChildFile(classname + help_extension); if(help_file.existsAsFile()) { return help_file; } // look for aliases help file name const auto alias = m_help_aliases.find(classname); if(alias != m_help_aliases.cend()) { help_file = alias->second; if(help_file.existsAsFile()) { return help_file; } } return {}; } void KiwiApp::setAuthUser(Api::AuthUser const& auth_user) { (*KiwiApp::use().m_api_controller).setAuthUser(auth_user); KiwiApp::useInstance().login(); } Api::AuthUser const& KiwiApp::getCurrentUser() { return KiwiApp::use().m_api_controller->getAuthUser(); } static juce::String getGlobalDirKey(KiwiApp::FileLocations location) { switch (location) { case KiwiApp::FileLocations::Save: { return "last_save_dir"; } case KiwiApp::FileLocations::Open: { return "last_open_dir"; } case KiwiApp::FileLocations::Download: { return "last_download_dir"; } case KiwiApp::FileLocations::Upload: { return "last_upload_dir"; } default: return {}; } } juce::File KiwiApp::getGlobalDirectoryFor(FileLocations location) { const juce::String dir_key = getGlobalDirKey(location); if(dir_key.isNotEmpty()) { auto global_dir = juce::File(getGlobalProperties().getValue(dir_key, "")); if(global_dir.exists() && global_dir.isDirectory()) { return global_dir; } } return juce::File::getSpecialLocation(juce::File::userHomeDirectory); } void KiwiApp::setGlobalDirectoryFor(FileLocations location, juce::File path) { assert(path.isDirectory()); const juce::String dir_key = getGlobalDirKey(location); if(dir_key.isNotEmpty()) { getGlobalProperties().setValue(dir_key, path.getFullPathName()); } } void KiwiApp::logout() { useInstance().handleConnectionLost(); KiwiApp::use().m_api_controller->logout(); KiwiApp::commandStatusChanged(); } bool KiwiApp::canConnectToServer() { const auto server_version = KiwiApp::use().m_last_server_version_check; return (!server_version.empty() && server_version != "null" && KiwiApp::use().canConnectToServerVersion(server_version)); } bool KiwiApp::canConnectToServerVersion(std::string const& server_version) { const auto& version = KiwiApp::use().getApplicationVersion(); return (version.compare(server_version) == 0); } void KiwiApp::pingSucceed(std::string const& new_server_version) { bool was_connected = canConnectToServer(); if((new_server_version == m_last_server_version_check) && was_connected) return; if (was_connected) { logout(); } if (canConnectToServerVersion(new_server_version)) { useInstance().login(); } else if(m_last_server_version_check != new_server_version) { const auto current_version = KiwiApp::use().getApplicationVersion().toStdString(); warning("Can't connect to server! Requires Kiwi " + new_server_version + ", please visit:"); warning("https://github.com/Musicoll/Kiwi/releases"); } m_last_server_version_check = new_server_version; if(!was_connected && canConnectToServer()) { const auto api_host = m_api_controller->getHost(); post("Connection established to " + api_host); } } void KiwiApp::pingFailed(Api::Error error) { static const std::string ping_failed = "null"; const bool was_connected = canConnectToServer(); if(was_connected) { KiwiApp::error("Connection lost"); m_instance->handleConnectionLost(); } else if(m_last_server_version_check != ping_failed) { KiwiApp::error("Connection to server failed: " + error.getMessage()); } m_last_server_version_check = ping_failed; } void KiwiApp::pingServer() { Api::CallbackFn<std::string const&> success = [this](std::string const& server_version) { KiwiApp::useScheduler().schedule([this, server_version]() { pingSucceed(server_version); }); }; useApi().getRelease(success, [this](Api::Error err) { KiwiApp::useScheduler().schedule([this, err = std::move(err)]() { pingFailed(err); }); }); } void KiwiApp::networkSettingsChanged(NetworkSettings const& settings, juce::Identifier const& id) { if (id == Ids::server_address) { auto& api = *m_api_controller; const auto host = settings.getHost(); const auto api_port = settings.getApiPort(); //const auto session_port = settings.getSessionPort(); if((api.getHost() != host) || (api_port != api.getPort())) { // settings changed m_api_controller->setHost(settings.getHost()); m_api_controller->setPort(settings.getApiPort()); pingServer(); } } } void KiwiApp::openCommandFile(juce::String const& command_line) { if (command_line.length() > 0) { juce::File file(command_line.unquoted()); if (file.hasFileExtension(".kiwi;.kiwihelp") && m_instance) { m_instance->openFile(file); } } } uint64_t KiwiApp::userID() { // refactor this (maybe a useless method) return KiwiApp::use().m_instance->getUserId(); } StoredSettings& KiwiApp::useSettings() { return *KiwiApp::use().m_settings; } juce::MenuBarModel* KiwiApp::getMenuBarModel() { return KiwiApp::use().m_menu_model.get(); } LookAndFeel& KiwiApp::useLookAndFeel() { return KiwiApp::use().m_looknfeel; } TooltipWindow& KiwiApp::useTooltipWindow() { return KiwiApp::use().m_tooltip_window; } // ================================================================================ // // CONSOLE // // ================================================================================ // void KiwiApp::log(std::string const& text) { useEngineInstance().log(text); } void KiwiApp::post(std::string const& text) { useEngineInstance().post(text); } void KiwiApp::warning(std::string const& text) { useEngineInstance().warning(text); } void KiwiApp::error(std::string const& text) { useEngineInstance().error(text); } void KiwiApp::closeWindow(Window& window) { if(m_instance) { m_instance->closeWindow(window); } } // ================================================================================ // // APPLICATION COMMAND // // ================================================================================ // void KiwiApp::bindToCommandManager(ApplicationCommandTarget* target) { KiwiApp& app = KiwiApp::use(); if(app.m_command_manager) { app.m_command_manager->registerAllCommandsForTarget(target); } } void KiwiApp::bindToKeyMapping(juce::Component* target) { KiwiApp& app = KiwiApp::use(); if(app.m_command_manager) { target->addKeyListener(app.m_command_manager->getKeyMappings()); } } juce::ApplicationCommandManager& KiwiApp::getCommandManager() { juce::ApplicationCommandManager* cm = KiwiApp::use().m_command_manager.get(); assert(cm != nullptr); return *cm; } void KiwiApp::commandStatusChanged() { KiwiApp* const app = KiwiApp::getApp(); if(app && app->m_command_manager) { app->m_command_manager->commandStatusChanged(); } } juce::KeyPressMappingSet* KiwiApp::getKeyMappings() { KiwiApp* const app = KiwiApp::getApp(); if(app && app->m_command_manager) { return app->m_command_manager->getKeyMappings(); } return nullptr; } // ================================================================================ // // APPLICATION MENU // // ================================================================================ // juce::StringArray KiwiApp::getMenuNames() { const char* const names[] = { "Account", "File", "Edit", "View", "Options", "Window", "Help", nullptr }; return juce::StringArray(names); } void KiwiApp::createMenu(juce::PopupMenu& menu, const juce::String& menuName) { if (menuName == "Account") createAccountMenu (menu); else if (menuName == "File") createFileMenu (menu); else if (menuName == "Edit") createEditMenu (menu); else if (menuName == "View") createViewMenu (menu); else if (menuName == "Options") createOptionsMenu (menu); else if (menuName == "Window") createWindowMenu (menu); else if (menuName == "Help") createHelpMenu (menu); else assert(false); // names have changed? } void KiwiApp::createOpenRecentPatchersMenu(juce::PopupMenu& menu) { } void KiwiApp::createAccountMenu(juce::PopupMenu& menu) { menu.addCommandItem(&getCommandManager(), CommandIDs::remember_me); menu.addSeparator(); menu.addCommandItem(&getCommandManager(), CommandIDs::login); menu.addCommandItem(&getCommandManager(), CommandIDs::signup); menu.addSeparator(); menu.addCommandItem(&getCommandManager(), CommandIDs::logout); } void KiwiApp::createFileMenu(juce::PopupMenu& menu) { menu.addCommandItem(m_command_manager.get(), CommandIDs::newPatcher); menu.addSeparator(); menu.addCommandItem(m_command_manager.get(), CommandIDs::openFile); createOpenRecentPatchersMenu(menu); menu.addCommandItem(m_command_manager.get(), CommandIDs::closeWindow); menu.addSeparator(); menu.addCommandItem(m_command_manager.get(), CommandIDs::save); menu.addCommandItem(m_command_manager.get(), CommandIDs::saveAs); #if ! JUCE_MAC menu.addSeparator(); menu.addCommandItem(m_command_manager.get(), juce::StandardApplicationCommandIDs::quit); #endif } void KiwiApp::createEditMenu(juce::PopupMenu& menu) { menu.addCommandItem(m_command_manager.get(), juce::StandardApplicationCommandIDs::undo); menu.addCommandItem(m_command_manager.get(), juce::StandardApplicationCommandIDs::redo); menu.addSeparator(); menu.addCommandItem(m_command_manager.get(), juce::StandardApplicationCommandIDs::cut); menu.addCommandItem(m_command_manager.get(), juce::StandardApplicationCommandIDs::copy); menu.addCommandItem(m_command_manager.get(), juce::StandardApplicationCommandIDs::paste); menu.addCommandItem(m_command_manager.get(), juce::StandardApplicationCommandIDs::del); menu.addSeparator(); menu.addCommandItem(m_command_manager.get(), CommandIDs::pasteReplace); menu.addCommandItem(m_command_manager.get(), CommandIDs::duplicate); menu.addCommandItem(m_command_manager.get(), juce::StandardApplicationCommandIDs::selectAll); menu.addCommandItem(m_command_manager.get(), juce::StandardApplicationCommandIDs::deselectAll); menu.addSeparator(); } void KiwiApp::createViewMenu(juce::PopupMenu& menu) { menu.addCommandItem(m_command_manager.get(), CommandIDs::newPatcherView); menu.addSeparator(); menu.addCommandItem(m_command_manager.get(), CommandIDs::editModeSwitch); menu.addSeparator(); menu.addCommandItem(m_command_manager.get(), CommandIDs::zoomIn); menu.addCommandItem(m_command_manager.get(), CommandIDs::zoomOut); menu.addCommandItem(m_command_manager.get(), CommandIDs::zoomNormal); } void KiwiApp::createOptionsMenu(juce::PopupMenu& menu) { menu.addCommandItem(m_command_manager.get(), CommandIDs::startDsp); menu.addCommandItem(m_command_manager.get(), CommandIDs::stopDsp); menu.addSeparator(); menu.addCommandItem(m_command_manager.get(), CommandIDs::showAudioStatusWindow); #if ! JUCE_MAC menu.addCommandItem(&getCommandManager(), CommandIDs::showAppSettingsWindow); #endif } void KiwiApp::createWindowMenu(juce::PopupMenu& menu) { menu.addCommandItem(m_command_manager.get(), CommandIDs::minimizeWindow); menu.addCommandItem(m_command_manager.get(), CommandIDs::maximizeWindow); menu.addSeparator(); menu.addCommandItem(m_command_manager.get(), CommandIDs::showConsoleWindow); menu.addSeparator(); menu.addCommandItem(m_command_manager.get(), CommandIDs::showDocumentBrowserWindow); menu.addCommandItem(m_command_manager.get(), CommandIDs::showBeaconDispatcherWindow); } void KiwiApp::createHelpMenu(juce::PopupMenu& menu) { #if ! JUCE_MAC menu.addCommandItem(m_command_manager.get(), CommandIDs::showAboutAppWindow); menu.addSeparator(); #endif menu.addCommandItem(m_command_manager.get(), CommandIDs::openObjectHelp); { juce::PopupMenu objects_submenu; createObjectHelpPopupMenu(objects_submenu); if(m_num_help_files > 0) { menu.addSubMenu("Objects", objects_submenu); } } { juce::PopupMenu examples_submenu; createExamplesPopupMenu(examples_submenu); if(m_num_example_files > 0) { menu.addSubMenu("Examples", examples_submenu); } } menu.addSeparator(); menu.addCommandItem(m_command_manager.get(), CommandIDs::showDocumentation); } void KiwiApp::handleMainMenuCommand(int menu_item_ID) { if (menu_item_ID >= objectHelpBaseID && menu_item_ID < (objectHelpBaseID + m_num_help_files)) { findAndOpenHelpFile(menu_item_ID - objectHelpBaseID); } else if (menu_item_ID >= examplesBaseID && menu_item_ID < (examplesBaseID + m_num_help_files)) { findAndOpenExample(menu_item_ID - examplesBaseID); } } void KiwiApp::createObjectHelpPopupMenu(juce::PopupMenu& menu) { m_num_help_files = 0; const auto help_dir = getKiwiObjectHelpDirectory(); for (auto const& f : getSortedObjectHelpFilesInDirectory(help_dir)) { menu.addItem(objectHelpBaseID + m_num_help_files, f.getFileNameWithoutExtension()); ++m_num_help_files; } } void KiwiApp::findAndOpenHelpFile(int selected_index) { const auto help_files = getSortedObjectHelpFilesInDirectory(getKiwiObjectHelpDirectory()); if (selected_index < help_files.size()) { useInstance().openFile(help_files.getUnchecked(selected_index)); } } juce::Array<juce::File> KiwiApp::getSortedObjectHelpFilesInDirectory(juce::File const& dir) const noexcept { juce::Array<juce::File> help_files; juce::DirectoryIterator iter (dir, false, "*.kiwihelp", juce::File::findFiles | juce::File::ignoreHiddenFiles); while(iter.next()) { help_files.add (iter.getFile()); } help_files.sort(); return help_files; } void KiwiApp::createExamplesPopupMenu(juce::PopupMenu& menu) noexcept { m_num_example_files = 0; for (auto& dir : getSortedExampleDirectories()) { juce::PopupMenu m; for (auto& f : getSortedExampleFilesInDirectory (dir)) { m.addItem (examplesBaseID + m_num_example_files, f.getFileNameWithoutExtension()); ++m_num_example_files; } menu.addSubMenu (dir.getFileName(), m); } } juce::Array<juce::File> KiwiApp::getSortedExampleDirectories() noexcept { juce::Array<juce::File> example_directories; const auto examples_dir = getKiwiExamplesDirectory(); if (! examples_dir.exists() || ! examples_dir.isDirectory() || ! examples_dir.containsSubDirectories()) return {}; juce::DirectoryIterator iter (examples_dir, false, "*", juce::File::findDirectories); while (iter.next()) { auto example_directory = iter.getFile(); if (example_directory.getNumberOfChildFiles (juce::File::findFiles | juce::File::ignoreHiddenFiles) > 0) { example_directories.add (example_directory); } } example_directories.sort(); return example_directories; } juce::Array<juce::File> KiwiApp::getSortedExampleFilesInDirectory(juce::File const& directory) const noexcept { juce::Array<juce::File> example_files; juce::DirectoryIterator iter (directory, false, "*.kiwi", juce::File::findFiles); while (iter.next()) example_files.add(iter.getFile()); example_files.sort(); return example_files; } void KiwiApp::findAndOpenExample(int selected_index) { juce::File example; for (auto& dir : getSortedExampleDirectories()) { auto example_files = getSortedExampleFilesInDirectory(dir); if (selected_index < example_files.size()) { example = example_files.getUnchecked(selected_index); break; } selected_index -= example_files.size(); } // example doesn't exist? assert(example != juce::File()); useInstance().openFile(example); } //============================================================================== void KiwiApp::getAllCommands(juce::Array<juce::CommandID>& commands) { juce::JUCEApplication::getAllCommands(commands); // get the standard quit command const juce::CommandID ids[] = { CommandIDs::newPatcher, CommandIDs::openFile, CommandIDs::showConsoleWindow, CommandIDs::showAboutAppWindow, CommandIDs::showDocumentation, CommandIDs::showAudioStatusWindow, CommandIDs::showAppSettingsWindow, CommandIDs::showDocumentBrowserWindow, CommandIDs::showBeaconDispatcherWindow, CommandIDs::switchDsp, CommandIDs::startDsp, CommandIDs::stopDsp, CommandIDs::login, CommandIDs::signup, CommandIDs::logout, CommandIDs::remember_me, }; commands.addArray(ids, juce::numElementsInArray(ids)); } void KiwiApp::getCommandInfo(juce::CommandID commandID, juce::ApplicationCommandInfo& result) { switch(commandID) { case CommandIDs::newPatcher: { result.setInfo(TRANS("New Patcher..."), TRANS("Create a new Patcher"), CommandCategories::general, 0); result.addDefaultKeypress('n', juce::ModifierKeys::commandModifier); break; } case CommandIDs::openFile: { result.setInfo(TRANS("Open..."), TRANS("Open a Patcher File"), CommandCategories::general, 0); result.addDefaultKeypress('o', juce::ModifierKeys::commandModifier); break; } case CommandIDs::showConsoleWindow: { result.setInfo(TRANS("Console"), TRANS("Show Kiwi Console Window"), CommandCategories::windows, 0); result.addDefaultKeypress('k', juce::ModifierKeys::commandModifier); break; } case CommandIDs::login: { auto const& user = getCurrentUser(); const bool logged = user.isLoggedIn(); result.setInfo(logged ? juce::String(TRANS("Logged-in as ") + user.getName()) : TRANS("Login"), TRANS("Show the \"Login form\" Window"), CommandCategories::windows, 0); result.setActive(!logged); break; } case CommandIDs::signup: { result.setInfo(TRANS("Register"), TRANS("Show the \"Register form\" Window"), CommandCategories::windows, 0); result.setActive(!getCurrentUser().isLoggedIn()); break; } case CommandIDs::logout: { result.setInfo(TRANS("Logout"), TRANS("Log out current user"), CommandCategories::windows, 0); result.setActive(getCurrentUser().isLoggedIn()); break; } case CommandIDs::remember_me: { result.setInfo(TRANS("Remember me"), TRANS("Remember current user"), CommandCategories::windows, 0); auto const& user = getCurrentUser(); result.setActive(user.isLoggedIn()); result.setTicked(getAppSettings().network().getRememberUserFlag()); break; } case CommandIDs::showAboutAppWindow: { result.setInfo(TRANS("About Kiwi"), TRANS("Show the \"About Kiwi\" Window"), CommandCategories::windows, 0); break; } case CommandIDs::showDocumentation: { result.setInfo(TRANS("Documentation"), TRANS("Show the documentation"), CommandCategories::windows, 0); break; } case CommandIDs::showAppSettingsWindow: { result.setInfo(TRANS("Preferences..."), TRANS("Show kiwi application settings"), CommandCategories::windows, 0); result.addDefaultKeypress(',', juce::ModifierKeys::commandModifier); break; } case CommandIDs::showAudioStatusWindow: { result.setInfo(TRANS("Audio Settings"), TRANS("Show kiwi settings"), CommandCategories::windows, 0); break; } case CommandIDs::showDocumentBrowserWindow: { result.setInfo(TRANS("Show Document Browser panel"), TRANS("Show Document Browser panel"), CommandCategories::windows, 0); break; } case CommandIDs::showBeaconDispatcherWindow: { result.setInfo(TRANS("Show Beacon dispatcher window"), TRANS("Show Beacon dispatcher window"), CommandCategories::windows, 0); break; } case CommandIDs::switchDsp: { result.setInfo(TRANS("Switch global DSP state"), TRANS("Switch global DSP state"), CommandCategories::general, 0); result.setTicked(m_instance->useEngineInstance().getAudioControler().isAudioOn()); break; } case CommandIDs::startDsp: { result.setInfo(TRANS("Start dsp"), TRANS("Start dsp"), CommandCategories::general, 0); result.setActive(!m_instance->useEngineInstance().getAudioControler().isAudioOn()); break; } case CommandIDs::stopDsp: { result.setInfo(TRANS("Stop dsp"), TRANS("Stop dsp"), CommandCategories::general, 0); result.setActive(m_instance->useEngineInstance().getAudioControler().isAudioOn()); break; } case juce::StandardApplicationCommandIDs::quit: { result.setInfo(TRANS("Quit Kiwi"), TRANS("Quits the application"), CommandCategories::general, 0); result.addDefaultKeypress('q', juce::ModifierKeys::commandModifier); break; } default: { break; } } } bool KiwiApp::perform(InvocationInfo const& info) { switch(info.commandID) { case CommandIDs::newPatcher : { m_instance->newPatcher(); break; } case CommandIDs::openFile : { m_instance->askUserToOpenPatcherDocument(); break; } case CommandIDs::login: { m_instance->showAuthWindow(AuthPanel::FormType::Login); break; } case CommandIDs::signup: { m_instance->showAuthWindow(AuthPanel::FormType::SignUp); break; } case CommandIDs::logout: { KiwiApp::logout(); break; } case CommandIDs::remember_me: { auto& settings = getAppSettings().network(); settings.setRememberUserFlag(!settings.getRememberUserFlag()); commandStatusChanged(); break; } case CommandIDs::showConsoleWindow : { m_instance->showConsoleWindow(); break; } case CommandIDs::showAboutAppWindow : { m_instance->showAboutKiwiWindow(); break; } case CommandIDs::showDocumentation : { const auto docs_index = getKiwiResourcesDirectory().getChildFile("docs/index.html"); if(docs_index.existsAsFile()) { docs_index.startAsProcess(); } else { KiwiApp::error("can't open documentation!"); } break; } case CommandIDs::showAppSettingsWindow : { m_instance->showAppSettingsWindow(); break; } case CommandIDs::showAudioStatusWindow : { m_instance->showAudioSettingsWindow(); break; } case CommandIDs::showDocumentBrowserWindow : { m_instance->showDocumentBrowserWindow(); break; } case CommandIDs::showBeaconDispatcherWindow : { m_instance->showBeaconDispatcherWindow(); break; } case CommandIDs::switchDsp : { auto& audio_controler = m_instance->useEngineInstance().getAudioControler(); if(audio_controler.isAudioOn()) { audio_controler.stopAudio(); } else { audio_controler.startAudio(); } break; } case CommandIDs::startDsp : { m_instance->useEngineInstance().getAudioControler().startAudio(); break; } case CommandIDs::stopDsp : { m_instance->useEngineInstance().getAudioControler().stopAudio(); break; } default : return JUCEApplication::perform(info); } return true; } }
44,740
C++
.cpp
1,084
28.329336
114
0.535925
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,334
Main.cpp
Musicoll_Kiwi/Client/Source/Main.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include "KiwiApp.h" //============================================================================== // This macro generates the main() routine that launches the app. START_JUCE_APPLICATION(kiwi::KiwiApp)
1,097
C++
.cpp
18
56.888889
91
0.532701
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,335
KiwiApp_ApiController.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Network/KiwiApp_ApiController.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include "KiwiApp_ApiController.h" #include "../KiwiApp_General/KiwiApp_IDs.h" #include "../KiwiApp.h" namespace kiwi { ApiController::ApiController() { auto& settings = getAppSettings().network(); setHost(settings.getHost()); setPort(settings.getApiPort()); restoreAuthUserProfile(); } ApiController::~ApiController() { auto& settings = getAppSettings().network(); if(!settings.getRememberUserFlag()) { clearToken(); } saveAuthUserProfile(); } bool ApiController::saveAuthUserProfile() const { return saveJsonToFile("UserProfile", {{"user", getAuthUser()}}); } bool ApiController::restoreAuthUserProfile() { auto j = getJsonFromFile("UserProfile"); if(j.count("user")) { from_json(j["user"], m_auth_user); return true; } return false; } void ApiController::setAuthUser(Api::AuthUser const& auth_user) { m_auth_user.resetWith(auth_user); } void ApiController::logout() { Api::Controller::clearToken(); } }
2,085
C++
.cpp
58
29.034483
90
0.58475
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,336
KiwiApp_Api.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Network/KiwiApp_Api.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include "KiwiApp_Api.h" #include <juce_core/juce_core.h> #include <iomanip> namespace kiwi { const std::string Api::Endpoint::root = "/api"; const std::string Api::Endpoint::login {Api::Endpoint::root + "/login"}; const std::string Api::Endpoint::documents {Api::Endpoint::root + "/documents"}; const std::string Api::Endpoint::users {Api::Endpoint::root + "/users"}; const std::string Api::Endpoint::releases {Api::Endpoint::root + "/releases"}; std::string Api::Endpoint::document(std::string const& document_id) { return Api::Endpoint::documents + '/' + document_id; } std::string Api::Endpoint::user(std::string const& user_id) { return Api::Endpoint::users + '/' + user_id; } // ================================================================================ // // API // // ================================================================================ // Api::Api(Api::Controller& controller) : m_controller(controller), m_requests() { ; } Api::~Api() { } // ================================================================================ // // API REQUESTS // // ================================================================================ // void Api::cancelRequest(uint64_t request_id) { auto request = std::find_if(m_requests.begin(), m_requests.end(), [request_id](std::unique_ptr<Session> const& session) { return session->getId() == request_id; }); if (request != m_requests.end()) { (*request)->cancel(); m_requests.erase(request); } } bool Api::isPending(uint64_t request_id) { auto request = std::find_if(m_requests.begin(), m_requests.end(), [request_id](std::unique_ptr<Session> const& session) { return session->getId() == request_id; }); return request != m_requests.end() && !(*request)->executed(); } void Api::cancelAll() { for (auto request = m_requests.begin(); request != m_requests.end(); ++request) { (*request)->cancel(); } } uint64_t Api::login(std::string const& username_or_email, std::string const& password, CallbackFn<AuthUser> success_cb, ErrorCallback error_cb) { assert(!username_or_email.empty()); assert(!password.empty()); auto session = makeSession(Endpoint::login, false); session->setPayload({ {"username", username_or_email}, {"password", password} }); auto cb = [success = std::move(success_cb), fail = std::move(error_cb)](Response res) { if (!res.error && hasJsonHeader(res) && res.result() == beast::http::status::ok) { json j; try { j = json::parse(res.body()); } catch (json::parse_error& e) { std::cerr << "json::parse_error: " << e.what() << '\n'; } if(j.is_object() && j.count("user")) { AuthUser user(j["user"].get<AuthUser>()); if(user.isLoggedIn()) { success(std::move(user)); } else { fail({res.result_int(), "Failed to parse result"}); } return; } } fail(res); }; session->PostAsync(std::move(cb)); return storeSession(std::move(session)); } uint64_t Api::signup(std::string const& username, std::string const& email, std::string const& password, CallbackFn<std::string> success_cb, ErrorCallback error_cb) { assert(!username.empty()); assert(!email.empty()); assert(!password.empty()); auto session = makeSession(Endpoint::users, false); session->setPayload({ {"username", username}, {"email", email}, {"password", password} }); auto cb = [success = std::move(success_cb), fail = std::move(error_cb)](Response res) { if (!res.error && hasJsonHeader(res) && res.result() == beast::http::status::ok) { json j; try { j = json::parse(res.body()); } catch (json::parse_error& e) { std::cerr << "json::parse_error: " << e.what() << '\n'; } if(j.is_object() && j.count("message")) { success(j["message"]); } else { fail({res.result_int(), "Failed to parse result"}); } } else { fail(res); } }; session->PostAsync(std::move(cb)); return storeSession(std::move(session)); } uint64_t Api::getUsers(std::unordered_set<uint64_t> const& user_ids, CallbackFn<Api::Users> success_cb, ErrorCallback error_cb) { auto cb = [success = std::move(success_cb), fail = std::move(error_cb)] (Response res) { if (!res.error && hasJsonHeader(res) && res.result() == beast::http::status::ok) { json j; try { j = json::parse(res.body()); } catch (json::parse_error& e) { std::cerr << "json::parse_error: " << e.what() << '\n'; } success(j); } else { fail(res); } }; auto session = makeSession(Endpoint::users); json j_users; for(uint64_t user_id : user_ids) { std::stringstream converter; converter << std::setfill('0') << std::setw(16) << std::hex << std::uppercase << user_id; j_users.push_back(converter.str()); } session->setParameters({{"ids", j_users.dump()}}); session->GetAsync(std::move(cb)); return storeSession(std::move(session)); } uint64_t Api::getDocuments(std::function<void(Response, Api::Documents)> callback) { auto cb = [callback = std::move(callback)](Response res) { if (!res.error && res.result() == beast::http::status::ok) { if(hasJsonHeader(res)) { json j; try { j = json::parse(res.body()); } catch (json::parse_error& e) { std::cerr << "json::parse_error: " << e.what() << '\n'; } if(j.is_array()) { // parse each json objects as document and store them in a vector. callback(std::move(res), j); return; } } } callback(std::move(res), {}); }; auto session = makeSession(Endpoint::documents); session->GetAsync(std::move(cb)); return storeSession(std::move(session)); } uint64_t Api::createDocument(std::string const& document_name, std::function<void(Response, Api::Document)> callback) { auto cb = [callback = std::move(callback)](Response res) { if (!res.error && res.result() == beast::http::status::ok) { if(hasJsonHeader(res)) { json j; try { j = json::parse(res.body()); } catch (json::parse_error& e) { std::cerr << "json::parse_error: " << e.what() << '\n'; } if(j.is_object()) { // parse object as a document callback(std::move(res), j); return; } } } callback(std::move(res), {}); }; auto session = makeSession(Endpoint::documents); if(!document_name.empty()) { session->setPayload({ {"name", document_name} }); } session->PostAsync(std::move(cb)); return storeSession(std::move(session)); } uint64_t Api::uploadDocument(std::string const& name, std::string const& data, std::string const& kiwi_version, std::function<void(Response, Api::Document)> callback) { auto cb = [callback = std::move(callback)](Response res) { if (!res.error && res.result() == beast::http::status::ok && hasJsonHeader(res)) { json j; try { j = json::parse(res.body()); } catch (json::parse_error& e) { std::cerr << "json::parse_error: " << e.what() << '\n'; } if(j.is_object()) { // parse object as a document callback(std::move(res), j); return; } } callback(std::move(res), {}); }; auto session = makeSession(Endpoint::documents + "/upload"); session->setParameters({{"name", name}, {"kiwi_version", kiwi_version}}); session->setBody(data); session->PostAsync(std::move(cb)); return storeSession(std::move(session)); } uint64_t Api::duplicateDocument(std::string const& document_id, Callback callback) { auto session = makeSession(Endpoint::document(document_id) + "/clone"); session->PostAsync(std::move(callback)); return storeSession(std::move(session)); } uint64_t Api::renameDocument(std::string document_id, std::string const& new_name, Callback callback) { assert(!new_name.empty() && "name should not be empty!"); auto session = makeSession(Endpoint::document(document_id)); session->setPayload({ {"name", new_name} }); session->PutAsync(std::move(callback)); return storeSession(std::move(session)); } uint64_t Api::untrashDocument(std::string document_id, Callback callback) { auto session = makeSession(Endpoint::document(document_id)); session->setPayload({ {"trashed", false} }); session->PutAsync(std::move(callback)); return storeSession(std::move(session)); } uint64_t Api::trashDocument(std::string document_id, Callback callback) { auto session = makeSession(Endpoint::document(document_id)); session->setPayload({ {"trashed", true} }); session->PutAsync(std::move(callback)); return storeSession(std::move(session)); } uint64_t Api::getOpenToken(std::string document_id, CallbackFn<std::string const&> success_cb, ErrorCallback error_cb) { auto session = makeSession(Endpoint::document(document_id) + "/opentoken"); auto callback = [success = std::move(success_cb), fail = std::move(error_cb)](Response res) { if (!res.error && hasJsonHeader(res) && res.result() == beast::http::status::ok) { json j; try { j = json::parse(res.body()); } catch (json::parse_error& e) { std::cerr << "json::parse_error: " << e.what() << '\n'; } if(j.count("token")) { success(j["token"]); return; } } fail(res); }; session->GetAsync(std::move(callback)); return storeSession(std::move(session)); } uint64_t Api::downloadDocument(std::string document_id, Callback callback) { auto session = makeSession(Endpoint::document(document_id) + "/download"); session->setParameters({{"alt", "download"}}); session->GetAsync(std::move(callback)); return storeSession(std::move(session)); } uint64_t Api::getRelease(CallbackFn<std::string const&> success_cb, ErrorCallback error_cb) { auto session = makeSession(Endpoint::releases); auto cb = [success = std::move(success_cb), fail = std::move(error_cb)](Response res) { if (!res.error && hasJsonHeader(res) && res.result() == beast::http::status::ok) { json j; try { j = json::parse(res.body()); } catch (json::parse_error& e) { std::cerr << "json::parse_error: " << e.what() << '\n'; } if(j.is_object() && j.count("release")) { std::string latest_release = j["release"]; success(latest_release); } } else { fail(res); } }; session->GetAsync(std::move(cb)); return storeSession(std::move(session)); } uint64_t Api::requestPasswordToken(std::string const& user_mail, CallbackFn<std::string const&> success_cb, ErrorCallback error_cb) { auto session = makeSession(Endpoint::users + "/passtoken"); session->setPayload({ {"email", user_mail} }); auto cb = [success = std::move(success_cb), fail = std::move(error_cb)](Response res) { if (!res.error && hasJsonHeader(res) && res.result() == beast::http::status::ok) { json j; try { j = json::parse(res.body()); } catch (json::parse_error& e) { std::cerr << "json::parse_error: " << e.what() << '\n'; } if(j.is_object() && j.count("message")) { std::string message = j["message"]; success(message); } } else { fail(res); } }; session->PostAsync(std::move(cb)); return storeSession(std::move(session)); } uint64_t Api::resetPassword(std::string const& token, std::string const& newpass, CallbackFn<std::string const&> success_cb, ErrorCallback error_cb) { auto session = makeSession(Endpoint::users + "/passreset"); session->setPayload({ {"token", token}, {"newpass", newpass} }); auto cb = [success = std::move(success_cb), fail = std::move(error_cb)](Response res) { if (!res.error && hasJsonHeader(res) && res.result() == beast::http::status::ok) { json j; try { j = json::parse(res.body()); } catch (json::parse_error& e) { std::cerr << "json::parse_error: " << e.what() << '\n'; } if(j.is_object() && j.count("message")) { std::string message = j["message"]; success(message); } } else { fail(res); } }; session->PostAsync(std::move(cb)); return storeSession(std::move(session)); } std::string Api::convertDate(std::string const& date) { const bool with_date = true; const bool with_time = true; const bool with_second = false; const bool use_24_hour_clock = true; return (juce::Time::fromISO8601(juce::String(date)) .toString(with_date, with_time, with_second, use_24_hour_clock) .toStdString()); } bool Api::hasJsonHeader(Response const& res) { return (res[beast::http::field::content_type] == "application/json; charset=utf-8"); } std::unique_ptr<Api::Session> Api::makeSession(std::string const& endpoint, bool add_auth) { auto session = std::make_unique<Session>(); session->setHost(m_controller.getHost()); session->setPort(std::to_string(m_controller.getPort())); session->setTarget(endpoint); session->setTimeout(http::Timeout(3000)); const AuthUser& user = m_controller.getAuthUser(); if(add_auth && user.isLoggedIn()) { session->setAuthorization("JWT " + user.getToken()); } return session; } uint64_t Api::storeSession(std::unique_ptr<Session> session) { for(auto it = m_requests.begin(); it != m_requests.end();) { if ((*it)->executed()) { it = m_requests.erase(it); } else { ++it; } } uint64_t session_id = session->getId(); m_requests.emplace(std::move(session)); return session_id; } // ================================================================================ // // API ERROR // // ================================================================================ // Api::Error::Error() : m_status_code(0) , m_message("Unknown Error") { ; } Api::Error::Error(unsigned status_code, std::string const& message) : m_status_code(status_code) , m_message(message) { } Api::Error::Error(Api::Response const& res) : m_status_code(res.result_int()) , m_message(res.error ? res.error.message() : "Unknown Error") { if(!res.error && hasJsonHeader(res)) { json j; try { j = json::parse(res.body()); } catch (json::parse_error& e) { std::cerr << "json::parse_error: " << e.what() << '\n'; } if(j.count("message")) { m_message = j["message"]; } } } unsigned Api::Error::getStatusCode() const { return m_status_code; } std::string const& Api::Error::getMessage() const { return m_message; } // ================================================================================ // // API USER // // ================================================================================ // std::string const& Api::User::getName() const { return m_name; } std::string const& Api::User::getEmail() const { return m_email; } std::string const& Api::User::getIdAsString() const { return m_id; } uint64_t Api::User::getIdAsInt() const { uint64_t result = 0ull; std::stringstream converter(m_id); converter >> std::hex >> result; return result; } bool Api::User::isValid() const noexcept { return (!m_id.empty() && !m_email.empty()); } int Api::User::getApiVersion() const { return m_api_version; } void Api::User::resetWith(User const& other) { m_api_version = other.m_api_version; m_id = other.m_id; m_name = other.m_name; m_email = other.m_email; } void to_json(json& j, Api::User const& user) { j = json{ {"__v", user.getApiVersion()}, {"_id", user.getIdAsString()}, {"username", user.getName()}, {"email", user.getEmail()} }; } void from_json(json const& j, Api::User& user) { user.m_api_version = Api::getJsonValue<int>(j, "__v"); user.m_id = Api::getJsonValue<std::string>(j, "_id"); user.m_name = Api::getJsonValue<std::string>(j, "username"); user.m_email = Api::getJsonValue<std::string>(j, "email"); } // ================================================================================ // // API AUTH USER // // ================================================================================ // Api::AuthUser::AuthUser(User const& other) : Api::User(other) , m_token() { } Api::AuthUser::AuthUser(AuthUser const& other) : Api::User(other) , m_token(other.getToken()) { } Api::AuthUser::AuthUser(AuthUser&& other) : Api::User(std::forward<User>(other)) , m_token(std::move(other.m_token)) { } void Api::AuthUser::resetWith(AuthUser const& other) { User::resetWith(static_cast<User const&>(other)); m_token = other.m_token; } bool Api::AuthUser::isLoggedIn() const { return isValid() && !m_token.empty(); } std::string const& Api::AuthUser::getToken() const { return m_token; } //! @brief Helper function to convert an Api::AuthUser into a json object void to_json(json& j, Api::AuthUser const& user) { to_json(j, static_cast<Api::User const&>(user)); j["token"] = user.getToken(); } void from_json(json const& j, Api::AuthUser& user) { from_json(j, static_cast<Api::User&>(user)); user.m_token = Api::getJsonValue<std::string>(j, "token"); } // ================================================================================ // // API DOCUMENT // // ================================================================================ // void to_json(json& j, Api::Document const& doc) { std::stringstream session_id_converter; session_id_converter << std::hex << doc.session_id; j = json{ {"_id", doc._id}, {"name", doc.name}, {"session_id", session_id_converter.str()}, {"createdBy", doc.author_name}, {"createdAt", doc.creation_time.toISO8601(true).toStdString()}, {"lastOpenedAt", doc.opened_time.toISO8601(true).toStdString()}, {"lastModdifyBy", doc.opened_user} }; if (doc.trashed) { j.at("trashed") = true; j.at("trash_date") = doc.trashed_time.toISO8601(true).toStdString(); } else { j.at("trashed") = false; } } void from_json(json const& j, Api::Document& doc) { doc._id = Api::getJsonValue<std::string>(j, "_id"); doc.name = Api::getJsonValue<std::string>(j, "name"); doc.author_name = Api::getJsonValue<std::string>(j.at("createdBy"), "username"); doc.creation_time = juce::Time::fromISO8601(Api::getJsonValue<std::string>(j, "createdAt")); doc.opened_time = juce::Time::fromISO8601(Api::getJsonValue<std::string>(j, "lastOpenedAt")); doc.opened_user = Api::getJsonValue<std::string>(j.at("lastOpenedBy"), "username"); doc.trashed = Api::getJsonValue<bool>(j, "trashed"); if(doc.trashed) { doc.trashed_time = juce::Time::fromISO8601(Api::getJsonValue<std::string>(j, "trashedDate")); } doc.session_id = 0ul; if(j.count("session_id")) { std::stringstream converter(j["session_id"].get<std::string>()); converter >> std::hex >> doc.session_id; } } bool Api::Document::operator==(Api::Document const& other_doc) const { return (_id == other_doc._id); } // ================================================================================ // // API CONTROLLER // // ================================================================================ // Api::Controller::Controller() : Api::Controller("127.0.0.1", 80) { ; } Api::Controller::Controller(std::string const& host, uint16_t port) : m_host(host) , m_port(port) , m_auth_user() { ; } void Api::Controller::setHost(std::string const& host) { m_host = host; } std::string const& Api::Controller::getHost() const { return m_host; } void Api::Controller::setPort(uint16_t port) noexcept { m_port = port; } uint16_t Api::Controller::getPort() const noexcept { return m_port; } bool Api::Controller::isUserLoggedIn() const { return m_auth_user.isLoggedIn(); } Api::AuthUser const& Api::Controller::getAuthUser() const { return m_auth_user; } void Api::Controller::clearToken() { m_auth_user.m_token.clear(); } }
27,785
C++
.cpp
714
26.371148
108
0.465562
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,337
KiwiApp_CarrierSocket.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Network/KiwiApp_CarrierSocket.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include <cassert> #include "KiwiApp_CarrierSocket.h" #include <KiwiModel/KiwiModel_PatcherUser.h> namespace kiwi { // ================================================================================ // // CARRIER SOCKET // // ================================================================================ // CarrierSocket::CarrierSocket(flip::DocumentBase& document): m_transport_socket(nullptr), m_document(document), m_state(State::Disconnected), m_state_func(), m_transfer_func() { } void CarrierSocket::onStateTransition(flip::CarrierBase::Transition transition, flip::CarrierBase::Error error) { if (transition == flip::CarrierBase::Transition::Disconnected) { m_state = State::Disconnected; } else if (transition == flip::CarrierBase::Transition::Connecting) { m_state = State::Connecting; } else if (transition == flip::CarrierBase::Transition::Connected) { m_state = State::Connected; } if (m_state_func) { m_state_func(transition, error); } } void CarrierSocket::onTransferBackend(size_t cur, size_t total) { if (m_transfer_func) { m_transfer_func(cur, total); } } void CarrierSocket::listenStateTransition(std::function <void (flip::CarrierBase::Transition, flip::CarrierBase::Error error)> call_back) { m_state_func = call_back; } void CarrierSocket::listenTransferBackend(std::function <void (size_t, size_t)> call_back) { m_transfer_func = call_back; } void CarrierSocket::process() { if (m_transport_socket != nullptr) { m_transport_socket->process(); } } void CarrierSocket::disconnect() { m_transport_socket.reset(); } bool CarrierSocket::isConnected() const { return m_transport_socket != nullptr && m_state == State::Connected; } void CarrierSocket::connect(std::string const& host, uint16_t port, uint64_t session_id, std::string & metadata) { m_transport_socket.reset(new flip::CarrierTransportSocketTcp(m_document, session_id, metadata, host, port)); m_transport_socket->listen_state_transition(std::bind(&CarrierSocket::onStateTransition, this, std::placeholders::_1, std::placeholders::_2)); m_transport_socket->listen_transfer_backend(std::bind(&CarrierSocket::onTransferBackend, this, std::placeholders::_1, std::placeholders::_2)); } CarrierSocket::~CarrierSocket() { disconnect(); } }
4,222
C++
.cpp
101
29.861386
116
0.495153
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,338
KiwiApp_DocumentBrowser.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Network/KiwiApp_DocumentBrowser.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include "KiwiApp_DocumentBrowser.h" #include "../KiwiApp.h" #include <iostream> #include <sstream> #include <iomanip> #include "../KiwiApp_General/KiwiApp_IDs.h" namespace kiwi { // ================================================================================ // // DOCUMENT BROWSER // // ================================================================================ // DocumentBrowser::DocumentBrowser(std::string const& drive_name, int refresh_time) : m_distant_drive(new Drive(drive_name)), m_refresh_time(refresh_time) { if(m_refresh_time > 0) { startTimer(m_refresh_time); } } DocumentBrowser::~DocumentBrowser() { stopTimer(); } void DocumentBrowser::setDriveName(std::string const& name) { m_distant_drive->setName(name); } DocumentBrowser::Drive* DocumentBrowser::getDrive() const { return m_distant_drive.get(); } void DocumentBrowser::timerCallback() { m_distant_drive->refresh_internal(); } void DocumentBrowser::handleDeniedRequest() { if (KiwiApp::getCurrentUser().isLoggedIn()) { KiwiApp::logout(); KiwiApp::error("Session has expired. Please login."); } else { KiwiApp::error("Request denied. Please login."); } } // ================================================================================ // // DOCUMENT BROWSER DRIVE // // ================================================================================ // DocumentBrowser::Drive::Drive(std::string const& name) : m_name(name), m_documents(), m_listeners(), m_sort([](DocumentSession const& l_hs, DocumentSession const& r_hs) { return l_hs.getName() < r_hs.getName(); }), m_drive(this, [](DocumentBrowser::Drive*){}) { ; }; void DocumentBrowser::Drive::addListener(Listener& listener) { m_listeners.add(listener); } void DocumentBrowser::Drive::removeListener(Listener& listener) { m_listeners.remove(listener); } void DocumentBrowser::Drive::setName(std::string const& name) { m_name = name; m_listeners.call(&Listener::driveChanged); } std::string const& DocumentBrowser::Drive::getName() const { return m_name; } void DocumentBrowser::Drive::setSort(Comp comp) { m_sort = comp; std::sort(m_documents.begin(), m_documents.end(), [comp](std::unique_ptr<DocumentSession> const& l_hs, std::unique_ptr<DocumentSession> const& r_hs) { return comp(*l_hs, *r_hs); }); m_listeners.call(&Listener::driveChanged); } void DocumentBrowser::Drive::uploadDocument(std::string const& name, std::string const& data) { std::weak_ptr<DocumentBrowser::Drive> drive(m_drive); KiwiApp::useApi().uploadDocument(name, data, KiwiApp::use().getApplicationVersion().toStdString(), [drive](Api::Response res, Api::Document document) { KiwiApp::useScheduler().schedule([drive, res, document]() { std::shared_ptr<DocumentBrowser::Drive> drive_ptr = drive.lock(); if (drive_ptr != nullptr) { if (res.result() == beast::http::status::forbidden) { DocumentBrowser::handleDeniedRequest(); } else if(res.error) { KiwiApp::error("Error: can't create document"); KiwiApp::error("=> " + res.error.message()); } else { drive_ptr->refresh(); } } }); }); } void DocumentBrowser::Drive::createNewDocument(std::string const& name) { std::weak_ptr<DocumentBrowser::Drive> drive(m_drive); KiwiApp::useApi().createDocument(name, [drive](Api::Response res, Api::Document document) { KiwiApp::useScheduler().schedule([drive, res, document]() { std::shared_ptr<DocumentBrowser::Drive> drive_ptr = drive.lock(); if(drive_ptr != nullptr) { if (res.result() == beast::http::status::forbidden) { DocumentBrowser::handleDeniedRequest(); } else if(res.error) { KiwiApp::error("Error: can't create document"); KiwiApp::error("=> " + res.error.message()); } else { drive_ptr->refresh(); } } }); }); } DocumentBrowser::Drive::DocumentSessions const& DocumentBrowser::Drive::getDocuments() const { return m_documents; } DocumentBrowser::Drive::DocumentSessions& DocumentBrowser::Drive::getDocuments() { return m_documents; } void DocumentBrowser::Drive::updateDocumentList(Api::Documents docs) { bool changed = false; DocumentSessions new_documents; new_documents.reserve(docs.size()); for(auto && doc : docs) { new_documents.emplace_back(std::make_unique<DocumentSession>(*this, std::move(doc))); } // drive removed notification for(auto doc_it = m_documents.begin(); doc_it != m_documents.end();) { auto it = std::find_if(new_documents.begin(), new_documents.end(), [&new_doc = *(doc_it->get())](auto const& doc){ return *(doc.get()) == new_doc; }); if(it == new_documents.end()) { m_listeners.call(&Listener::documentRemoved, *(doc_it->get())); doc_it = m_documents.erase(doc_it); changed = true; continue; } ++doc_it; } // drive added or changed notification for(auto && new_doc : new_documents) { auto it = std::find_if(m_documents.begin(), m_documents.end(), [&new_doc = *new_doc](auto const& doc){ return *(doc.get()) == new_doc; }); // new document if(it == m_documents.end()) { it = m_documents.emplace(it, std::move(new_doc)); auto& doc = *(it->get()); m_listeners.call(&Listener::documentAdded, doc); changed = true; } else { // name is currently the only document field that can change. if(new_doc->getName() != (*it)->getName() || new_doc->isTrashed() != (*it)->isTrashed() || new_doc->getOpenedTime() != (*it)->getOpenedTime()) { (*it)->m_document = new_doc->m_document; auto& doc = *(it->get()); m_listeners.call(&Listener::documentChanged, doc); changed = true; } } } if(changed) { std::sort(m_documents.begin(), m_documents.end(), [this](std::unique_ptr<DocumentSession> const& l_hs, std::unique_ptr<DocumentSession> const& r_hs) { return m_sort(*l_hs, *r_hs); }); m_listeners.call(&Listener::driveChanged); } } void DocumentBrowser::Drive::refresh_internal() { const bool is_connected = KiwiApp::canConnectToServer(); const bool was_connected = m_was_connected; if(was_connected != is_connected) { // dirty connection state manager :( // todo: need to refactor all document browser system m_listeners.call(&Listener::driveConnectionStatusChanged, is_connected); } m_was_connected = is_connected; if(was_connected && !is_connected) { m_drive->updateDocumentList({}); return; } std::weak_ptr<DocumentBrowser::Drive> drive(m_drive); KiwiApp::useApi().getDocuments([drive](Api::Response res, Api::Documents docs) { KiwiApp::useScheduler().schedule([drive, res, docs]() { std::shared_ptr<DocumentBrowser::Drive> drive_ptr = drive.lock(); if (drive_ptr != nullptr && res.result() == beast::http::status::ok && !res.error) { drive_ptr->updateDocumentList(docs); } }); }); } void DocumentBrowser::Drive::refresh() { std::weak_ptr<DocumentBrowser::Drive> drive(m_drive); KiwiApp::useApi().getDocuments([drive](Api::Response res, Api::Documents docs) { KiwiApp::useScheduler().schedule([drive, res, docs]() { std::shared_ptr<DocumentBrowser::Drive> drive_ptr = drive.lock(); if(drive_ptr != nullptr) { if (res.result() == beast::http::status::forbidden) { DocumentBrowser::handleDeniedRequest(); } else if(res.error) { KiwiApp::error("Kiwi API error: can't get documents => " + res.error.message()); } else { drive_ptr->updateDocumentList(docs); } } }); }); } // ================================================================================ // // DRIVE DOCUMENT // // ================================================================================ // DocumentBrowser::Drive::DocumentSession::DocumentSession(DocumentBrowser::Drive& parent, Api::Document document) : m_drive(parent), m_document(std::move(document)), m_open_token(""), m_session(this, [](DocumentSession *){}) { } DocumentBrowser::Drive::DocumentSession::~DocumentSession() { ; } std::string DocumentBrowser::Drive::DocumentSession::getName() const { return m_document.name; } uint64_t DocumentBrowser::Drive::DocumentSession::getSessionId() const { return m_document.session_id; } DocumentBrowser::Drive const& DocumentBrowser::Drive::DocumentSession::useDrive() const { return m_drive; } juce::Time const& DocumentBrowser::Drive::DocumentSession::getCreationTime() const { return m_document.creation_time; } std::string DocumentBrowser::Drive::DocumentSession::getCreationDate() const { return getCreationTime().toString(true, true, false, true).toStdString(); } std::string const& DocumentBrowser::Drive::DocumentSession::getAuthor() const { return m_document.author_name; } bool DocumentBrowser::Drive::DocumentSession::isTrashed() const { return m_document.trashed; } juce::Time const& DocumentBrowser::Drive::DocumentSession::getTrashedTime() const { return m_document.trashed_time; } std::string DocumentBrowser::Drive::DocumentSession::getTrashedDate() const { return getTrashedTime().toString(true, true, false, true).toStdString(); } juce::Time const& DocumentBrowser::Drive::DocumentSession::getOpenedTime() const { return m_document.opened_time; } std::string DocumentBrowser::Drive::DocumentSession::getOpenedDate() const { return getOpenedTime().toString(true, true, false, true).toStdString(); } std::string const& DocumentBrowser::Drive::DocumentSession::getOpenedUser() const { return m_document.opened_user; } std::string const& DocumentBrowser::Drive::DocumentSession::getOpenToken() const { return m_open_token; } void DocumentBrowser::Drive::DocumentSession::untrash() { std::weak_ptr<DocumentSession> session(m_session); KiwiApp::useApi().untrashDocument(m_document._id, [session](Api::Response res) { KiwiApp::useScheduler().schedule([session, res]() { std::shared_ptr<DocumentSession> session_ptr = session.lock(); if (session_ptr != nullptr) { if (res.result() == beast::http::status::forbidden) { DocumentBrowser::handleDeniedRequest(); } else if(res.error) { KiwiApp::error(res.error.message()); } else { session_ptr->m_drive.refresh(); } } }); }); } void DocumentBrowser::Drive::DocumentSession::trash() { std::weak_ptr<DocumentSession> session(m_session); KiwiApp::useApi().trashDocument(m_document._id, [session](Api::Response res) { KiwiApp::useScheduler().schedule([session, res]() { std::shared_ptr<DocumentSession> session_ptr = session.lock(); if (session_ptr != nullptr) { if (res.result() == beast::http::status::forbidden) { DocumentBrowser::handleDeniedRequest(); } else if(res.error) { KiwiApp::error(res.error.message()); } else { session_ptr->m_drive.refresh(); } } }); }); } void DocumentBrowser::Drive::DocumentSession::duplicate() { std::weak_ptr<DocumentSession> session(m_session); KiwiApp::useApi().duplicateDocument(m_document._id, [session](Api::Response res) { KiwiApp::useScheduler().schedule([res, session]() { std::shared_ptr<DocumentSession> session_ptr = session.lock(); if (session_ptr != nullptr) { if (res.result() == beast::http::status::forbidden) { DocumentBrowser::handleDeniedRequest(); } else if (res.result() == beast::http::status::not_found) { KiwiApp::error("error: document not found"); } else if(res.error) { KiwiApp::error(res.error.message()); } else { session_ptr->m_drive.refresh(); } } }); }); } void DocumentBrowser::Drive::DocumentSession::rename(std::string const& new_name) { if(new_name.empty()) { return; } std::weak_ptr<DocumentSession> session(m_session); KiwiApp::useApi().renameDocument(m_document._id, new_name, [session](Api::Response res) { KiwiApp::useScheduler().schedule([session, res]() { std::shared_ptr<DocumentSession> session_ptr = session.lock(); if (session_ptr != nullptr) { if (res.result() == beast::http::status::forbidden) { DocumentBrowser::handleDeniedRequest(); } else if(res.error) { KiwiApp::error(res.error.message()); } else { session_ptr->m_drive.refresh(); } } }); }); } void DocumentBrowser::Drive::DocumentSession::download(std::function<void(std::string const&)> callback) { std::weak_ptr<DocumentSession> session(m_session); KiwiApp::useApi().downloadDocument(m_document._id, [session, cb = std::move(callback)](Api::Response res) { KiwiApp::useScheduler().schedule([session, res, func = std::bind(cb, res.body())]() { std::shared_ptr<DocumentSession> session_ptr = session.lock(); if (session_ptr) { if (res.result() == beast::http::status::forbidden) { DocumentBrowser::handleDeniedRequest(); } else if (res.result() == beast::http::status::not_found) { KiwiApp::error("error: document not found"); } else if(res.error) { KiwiApp::error(res.error.message()); } else { func(); } } }); }); } bool DocumentBrowser::Drive::DocumentSession::operator==(DocumentSession const& other_doc) const { return (&m_drive == &other_doc.useDrive()) && (m_document == other_doc.m_document); } DocumentBrowser::Drive& DocumentBrowser::Drive::DocumentSession::useDrive() { return m_drive; } void DocumentBrowser::Drive::DocumentSession::open() { std::weak_ptr<DocumentSession> session(m_session); auto success = [session](std::string const& token) { KiwiApp::useScheduler().schedule([session, token]() { std::shared_ptr<DocumentSession> session_ptr = session.lock(); if (session_ptr != nullptr) { session_ptr->m_open_token = token; session_ptr->m_drive.refresh(); KiwiApp::useInstance().openRemotePatcher(*session_ptr); } }); }; auto error = [session](Api::Error er) { KiwiApp::useScheduler().schedule([session, er]() { std::shared_ptr<DocumentSession> session_ptr = session.lock(); if (session_ptr != nullptr) { if (er.getStatusCode() == static_cast<unsigned>(beast::http::status::forbidden)) { DocumentBrowser::handleDeniedRequest(); } else { KiwiApp::error(er.getMessage()); } } }); }; KiwiApp::useApi().getOpenToken(m_document._id, success, error); } }
21,438
C++
.cpp
549
25.016393
108
0.477635
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,339
KiwiApp_StoredSettings.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_General/KiwiApp_StoredSettings.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include "KiwiApp_StoredSettings.h" #include "../KiwiApp.h" #include "../KiwiApp_Resources/KiwiApp_BinaryData.h" #include "KiwiApp_IDs.h" namespace kiwi { // ================================================================================ // // GLOBAL FUNCTIONS // // ================================================================================ // StoredSettings& getAppSettings() { return KiwiApp::useSettings(); } juce::PropertiesFile& getGlobalProperties() { return getAppSettings().getGlobalProperties(); } juce::PropertiesFile::Options getPropertyFileOptionsFor(juce::String const& filename, juce::String const& suffix) { assert(suffix.isNotEmpty() && "need an extension"); juce::PropertiesFile::Options options; options.applicationName = filename; options.filenameSuffix = suffix; options.osxLibrarySubFolder = "Application Support"; #if JUCE_LINUX options.folderName = "~/.config/Kiwi"; #else options.folderName = "Kiwi"; #endif return options; } static std::unique_ptr<juce::PropertiesFile> createPropsFile(const juce::String& filename) { return std::make_unique<juce::PropertiesFile>(getPropertyFileOptionsFor(filename)); } bool saveJsonToFile(juce::String const& filename, json const& j) { juce::File file = getPropertyFileOptionsFor(filename, "json").getDefaultFile(); juce::TemporaryFile tempFile(file); { juce::FileOutputStream out(tempFile.getFile()); if (!out.openedOk()) return false; std::string json_str = j.dump(4); out.write(json_str.data(), json_str.size()); out.flush(); // (called explicitly to force an fsync on posix) if (out.getStatus().failed()) return false; } return tempFile.overwriteTargetFileWithTemporary(); } json getJsonFromFile(juce::String const& filename) { const juce::File file = getPropertyFileOptionsFor(filename, "json").getDefaultFile(); if (file.exists()) { std::string json_user_str = file.loadFileAsString().toStdString(); json j; try { j = json::parse(json_user_str); } catch (json::parse_error& e) { std::cerr << "message: " << e.what() << '\n'; } return j; } return {}; } // ================================================================================ // // NETWORK SETTINGS // // ================================================================================ // NetworkSettings::NetworkSettings() : m_settings(Ids::NETWORK_CONFIG) { resetToDefault(); m_settings.addListener(this); } NetworkSettings::~NetworkSettings() { m_settings.removeListener(this); } void NetworkSettings::resetToDefault() { m_settings.removeAllChildren(nullptr); m_settings.removeAllProperties(nullptr); m_settings.removeAllChildren(nullptr); std::unique_ptr<juce::XmlElement> xml(nullptr); auto str = juce::String::createStringFromData(binary_data::settings::network_settings, binary_data::settings::network_settings_size); xml.reset(juce::XmlDocument::parse(str)); assert(xml != nullptr); juce::ValueTree tree = juce::ValueTree::fromXml(*xml); if (tree.hasProperty(Ids::remember_me)) { m_settings.setProperty(Ids::remember_me, tree.getProperty(Ids::remember_me), nullptr); } juce::ValueTree server_tree = tree.getChildWithName(Ids::server_address).createCopy(); if (server_tree.isValid()) { m_settings.addChild(server_tree, 0, nullptr); } } juce::ValueTree NetworkSettings::getServerAddress() { return m_settings.getChildWithName(Ids::server_address).createCopy(); } void NetworkSettings::setServerAddress(std::string const& host, uint16_t api_port, uint16_t session_port) { juce::ValueTree tree(Ids::server_address); tree.setProperty(Ids::host, juce::String(host), nullptr); tree.setProperty(Ids::api_port, api_port, nullptr); tree.setProperty(Ids::session_port, session_port, nullptr); m_settings.removeChild(m_settings.getChildWithName(Ids::server_address), nullptr); m_settings.addChild(tree, 0, nullptr); } void NetworkSettings::readFromXml(juce::XmlElement const& xml) { if(xml.hasTagName(m_settings.getType().toString())) { const auto new_settings(juce::ValueTree::fromXml(xml)); if (new_settings.hasProperty(Ids::remember_me)) { m_settings.setProperty(Ids::remember_me, new_settings.getProperty(Ids::remember_me), nullptr); } juce::ValueTree server_tree = new_settings.getChildWithName(Ids::server_address).createCopy(); if (server_tree.isValid()) { m_settings.removeChild(m_settings.getChildWithName(Ids::server_address), nullptr); m_settings.addChild(server_tree, 0, nullptr); } } } juce::ValueTree& NetworkSettings::use() { return m_settings; } std::string NetworkSettings::getHost() const { return m_settings.getChildWithName(Ids::server_address).getProperty(Ids::host).toString().toStdString(); } uint16_t NetworkSettings::getApiPort() const { int port = m_settings.getChildWithName(Ids::server_address).getProperty(Ids::api_port); return static_cast<uint16_t>(port); } uint16_t NetworkSettings::getSessionPort() const { int port = m_settings.getChildWithName(Ids::server_address).getProperty(Ids::session_port); return static_cast<uint16_t>(port); } void NetworkSettings::setRememberUserFlag(bool remember_me) { m_settings.setProperty(Ids::remember_me, remember_me, nullptr); } bool NetworkSettings::getRememberUserFlag() const { return m_settings.getProperty(Ids::remember_me); } void NetworkSettings::addListener(Listener& listener) { m_listeners.add(listener); } void NetworkSettings::removeListener(Listener& listener) { m_listeners.remove(listener); } void NetworkSettings::valueTreePropertyChanged(juce::ValueTree&, juce::Identifier const& id) { m_listeners.call(&Listener::networkSettingsChanged, *this, id); } void NetworkSettings::valueTreeChildAdded(juce::ValueTree& parent, juce::ValueTree& child) { m_listeners.call(&Listener::networkSettingsChanged, *this, child.getType()); } // ================================================================================ // // STORED SETTINGS // // ================================================================================ // StoredSettings::StoredSettings() { reload(); m_network.use().addListener(this); } StoredSettings::~StoredSettings() { m_network.use().removeListener(this); flush(); } juce::PropertiesFile& StoredSettings::getGlobalProperties() { return *m_property_files[0]; } void StoredSettings::flush() { for(int i = m_property_files.size(); --i >= 0;) { m_property_files[i]->saveIfNeeded(); } } void StoredSettings::reload() { m_property_files.clear(); m_property_files.emplace_back(createPropsFile("kiwi_settings")); // Try to reload User settings std::unique_ptr<juce::XmlElement> xml(getGlobalProperties().getXmlValue("Network Settings")); if (xml) { m_network.readFromXml(*xml); } } NetworkSettings& StoredSettings::network() { return m_network; } void StoredSettings::saveValueTree(juce::ValueTree const& vt, std::string const& key_name) { std::unique_ptr<juce::XmlElement> xml_value(vt.createXml()); getGlobalProperties().setValue(key_name, xml_value.get()); } void StoredSettings::changed() { saveValueTree(m_network.use(), "Network Settings"); } }
10,307
C++
.cpp
240
32.0625
118
0.552736
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
754,340
KiwiApp_LookAndFeel.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_General/KiwiApp_LookAndFeel.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016-2019, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v3 (or any later version). Details can be found at: www.gnu.org/licenses KIWI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ Contact : cicm.mshparisnord@gmail.com ============================================================================== */ #include "../KiwiApp_General/KiwiApp_LookAndFeel.h" #include "../KiwiApp_Resources/KiwiApp_BinaryData.h" #include <KiwiApp_Patcher/KiwiApp_PatcherView.h> #include <KiwiApp_Patcher/KiwiApp_Objects/KiwiApp_ObjectView.h> #include <KiwiApp_Patcher/KiwiApp_LinkView.h> namespace bfonts = kiwi::binary_data::fonts; namespace kiwi { LookAndFeel::LookAndFeel() : juce::LookAndFeel_V4(getGreyColourScheme()) { setUsingNativeAlertWindows(true); initColours(); } float LookAndFeel::getObjectBorderSize() const { return m_box_border_size; } juce::TextLayout LookAndFeel::layoutTooltipText(juce::String const& text, juce::Colour colour) noexcept { const float font_size = 13.0f; const int max_width = 400; juce::AttributedString s; s.setColour(colour); s.setJustification(juce::Justification::centred); s.append(text, juce::Font(font_size, juce::Font::bold), colour); juce::TextLayout tl; tl.createLayoutWithBalancedLineLengths(s, (float) max_width); return tl; } juce::Typeface::Ptr LookAndFeel::getTypefaceForFont(juce::Font const& font) { juce::Typeface::Ptr typeface; if (font.getTypefaceName() == juce::Font::getDefaultSansSerifFontName()) { if (font.getStyleFlags() & juce::Font::FontStyleFlags::bold) { if (font.getStyleFlags() & juce::Font::FontStyleFlags::italic) { typeface = juce::Typeface::createSystemTypefaceFor(bfonts::open_sans::OpenSans_BoldItalic_ttf, bfonts::open_sans::OpenSans_BoldItalic_ttf_size); } else { typeface = juce::Typeface::createSystemTypefaceFor(bfonts::open_sans::OpenSans_Bold_ttf, bfonts::open_sans::OpenSans_Bold_ttf_size); } } else if(font.getStyleFlags() & juce::Font::FontStyleFlags::italic) { typeface = juce::Typeface::createSystemTypefaceFor(bfonts::open_sans::OpenSans_SemiboldItalic_ttf, bfonts::open_sans::OpenSans_SemiboldItalic_ttf_size); } else { typeface = juce::Typeface::createSystemTypefaceFor(bfonts::open_sans::OpenSans_Semibold_ttf, bfonts::open_sans::OpenSans_Semibold_ttf_size); } } if (typeface == nullptr) { typeface = juce::Font::getDefaultTypefaceForFont (font); } return typeface; } void LookAndFeel::drawPropertyPanelSectionHeader(juce::Graphics& g, const juce::String& name, bool is_open, int width, int height) { //@see drawPropertyPanelCategoryHeader const float button_size = height * 0.75f; const float button_indent = (height - button_size) * 0.5f; //@see drawConcertinaPanelHeader const juce::Colour bkg(juce::Colours::grey); g.setGradientFill(juce::ColourGradient(bkg.withAlpha(0.2f), 0.f, 0.f, bkg.withAlpha(0.4f), 0., height, false)); g.fillAll(); g.setColour(bkg.contrasting(0.5).withAlpha(0.1f)); g.drawHorizontalLine(0.f, 0.f, width); g.drawHorizontalLine(height - 1, 0.f, width); const int text_indent = (int)(button_indent * 2.0f + button_size + 2.0f); g.setColour(bkg.contrasting()); g.setFont(juce::Font(height * 0.6f).boldened()); g.drawFittedText(name, text_indent, 0, width - text_indent - 4, height, juce::Justification::centredLeft, 1); //@see drawTreeviewPlusMinusBox const juce::Rectangle<float> plusRect{button_indent, button_indent, button_size, button_size}; juce::Path p; p.addTriangle(0.0f, 0.0f, 1.0f, is_open ? 0.0f : 0.5f, is_open ? 0.5f : 0.0f, 1.0f); g.setColour(juce::Colours::white.contrasting().withAlpha(0.5f)); g.fillPath(p, p.getTransformToScaleToFit(plusRect.reduced(2, plusRect.getHeight() / 4), true)); } void LookAndFeel::drawTableHeaderColumn(juce::Graphics& g, juce::TableHeaderComponent&, juce::String const& columnName, int /*columnId*/, int width, int height, bool isMouseOver, bool isMouseDown, int columnFlags) { if(isMouseDown) g.fillAll(juce::Colours::white.withAlpha(0.2f)); else if(isMouseOver) g.fillAll(juce::Colours::white.withAlpha(0.1f)); juce::Rectangle<int> area(width, height); area.reduce(4, 0); if ((columnFlags & (juce::TableHeaderComponent::sortedForwards | juce::TableHeaderComponent::sortedBackwards)) != 0) { juce::Path sortArrow; sortArrow.addTriangle (0.0f, 0.0f, 0.5f, (columnFlags & juce::TableHeaderComponent::sortedForwards) != 0 ? -0.8f : 0.8f, 1.0f, 0.0f); g.setColour(juce::Colour (0x99000000)); g.fillPath(sortArrow, sortArrow.getTransformToScaleToFit(area.removeFromRight(height / 2).reduced (2).toFloat(), true)); } g.setColour(getCurrentColourScheme() .getUIColour(juce::LookAndFeel_V4::ColourScheme::UIColour::windowBackground) .contrasting(0.9)); g.setFont(juce::Font(height * 0.5f, juce::Font::bold)); g.drawFittedText(columnName, area, juce::Justification::centredLeft, 1); } void LookAndFeel::drawTableHeaderBackground(juce::Graphics& g, juce::TableHeaderComponent& header) { auto r(header.getLocalBounds()); const auto bdcolor = juce::Colours::black.withAlpha(0.5f); g.setColour(getCurrentColourScheme() .getUIColour(juce::LookAndFeel_V4::ColourScheme::UIColour::windowBackground)); g.fillRect(r); g.setColour(bdcolor); g.fillRect(r.removeFromBottom(1)); g.setColour(bdcolor); for(int i = header.getNumColumns(true) - 1; --i >= 0;) { g.fillRect(header.getColumnPosition(i).removeFromRight(1)); } } void LookAndFeel::drawButtonBackground(juce::Graphics& g, juce::Button& btn, juce::Colour const& bgcolor, bool mouse_over, bool mouse_down) { juce::Colour baseColour(bgcolor.withMultipliedSaturation(btn.hasKeyboardFocus (true) ? 1.3f : 0.9f).withMultipliedAlpha(btn.isEnabled() ? 0.9f : 0.5f)); if (mouse_down || mouse_over) baseColour = baseColour.contrasting(mouse_down ? 0.2f : 0.1f); const bool flatOnLeft = btn.isConnectedOnLeft(); const bool flatOnRight = btn.isConnectedOnRight(); const bool flatOnTop = btn.isConnectedOnTop(); const bool flatOnBottom = btn.isConnectedOnBottom(); const float width = btn.getWidth() - 1.0f; const float height = btn.getHeight() - 1.0f; if(width > 0 && height > 0) { const float cornerSize = 1.0f; juce::Path outline; outline.addRoundedRectangle(0.5f, 0.5f, width, height, cornerSize, cornerSize, ! (flatOnLeft || flatOnTop), ! (flatOnRight || flatOnTop), ! (flatOnLeft || flatOnBottom), ! (flatOnRight || flatOnBottom)); g.setColour(baseColour); g.fillPath(outline); g.setColour(btn.hasKeyboardFocus(false) ? baseColour.contrasting(0.5) : baseColour.contrasting(0.2)); g.strokePath(outline, juce::PathStrokeType(1.0f)); } } void LookAndFeel::paintToolbarBackground(juce::Graphics& g, int w, int h, juce::Toolbar& toolbar) { g.fillAll(toolbar.findColour(juce::Toolbar::backgroundColourId)); } void LookAndFeel::paintToolbarButtonBackground(juce::Graphics& g, int /*width*/, int /*height*/, bool isMouseOver, bool isMouseDown, juce::ToolbarItemComponent& component) { // don't draw toolbar button background } void LookAndFeel::initColours() { // ------ Application setColour(juce::ScrollBar::ColourIds::thumbColourId, juce::Colours::grey.withAlpha(0.7f)); // ------ patcherview colors const auto patcherview_bg = juce::Colour::fromFloatRGBA(0.8, 0.8, 0.8, 1.); setColour(PatcherView::ColourIds::BackgroundUnlocked, patcherview_bg); setColour(PatcherView::ColourIds::BackgroundLocked, patcherview_bg); const auto selection_color = juce::Colour::fromFloatRGBA(0., 0.5, 1., 1.); setColour(PatcherView::ColourIds::Selection, selection_color); setColour(PatcherView::ColourIds::SelectionOtherView, selection_color.contrasting(0.4)); setColour(PatcherView::ColourIds::SelectionOtherUser, juce::Colour(0xFFFF8C00)); // ------ objectbox colors const juce::Colour box_bgcolor = juce::Colours::white; const auto box_bdcolor = box_bgcolor.contrasting(0.4); const auto link_control_color = box_bdcolor.contrasting(0.1f); const auto link_signal_color = juce::Colour(0xff444444); setColour(ObjectView::ColourIds::PinControl, link_control_color); setColour(ObjectView::ColourIds::PinSignal, link_signal_color); setColour(ObjectView::ColourIds::Error, juce::Colour::fromRGBA(223, 97, 94, 250)); setColour(ObjectView::ColourIds::Background, box_bgcolor); setColour(ObjectView::ColourIds::Text, juce::Colours::black); setColour(ObjectView::ColourIds::Outline, box_bdcolor); setColour(ObjectView::ColourIds::Highlight, juce::Colour::fromFloatRGBA(0., 0.5, 1., 0.4)); setColour(ObjectView::ColourIds::Active, juce::Colour(0xff21ba90)); // ------ link colors setColour(LinkView::ColourIds::ControlBackground, link_control_color); setColour(LinkView::ColourIds::SignalBackground, link_signal_color); } }
12,146
C++
.cpp
224
39.200893
160
0.579493
Musicoll/Kiwi
134
11
7
GPL-3.0
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false