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,341
KiwiApp_BeaconDispatcher.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Application/KiwiApp_BeaconDispatcher.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 : [email protected] ============================================================================== */ #include "KiwiApp_BeaconDispatcher.h" #include "../KiwiApp.h" #include "../KiwiApp_Resources/KiwiApp_BinaryData.h" #include "../KiwiApp_General/KiwiApp_CommandIDs.h" #include "../KiwiApp_General/KiwiApp_StoredSettings.h" namespace kiwi { BeaconDispatcherElem::TextValueComponent::TextValueComponent(BeaconDispatcherElem& owner) : m_owner(owner), m_message_editor("message_editor"), m_send_button("Send") { // message field m_message_editor.setReturnKeyStartsNewLine(false); m_message_editor.setMultiLine(false, false); m_message_editor.setTextToShowWhenEmpty("Message to send", findColour(juce::TextEditor::ColourIds::textColourId).withAlpha(0.3f)); m_message_editor.setColour(juce::TextEditor::backgroundColourId, juce::Colours::transparentBlack); //button m_send_button.addListener(this); addAndMakeVisible(m_message_editor); addAndMakeVisible(m_send_button); } BeaconDispatcherElem::TextValueComponent::~TextValueComponent() { m_send_button.removeListener(this); } void BeaconDispatcherElem::TextValueComponent::buttonClicked(juce::Button* btn) { if(btn == &m_send_button) { std::string args = m_message_editor.getText().toStdString(); m_owner.sendValue(tool::AtomHelper::parse(args)); } } void BeaconDispatcherElem::TextValueComponent::resized() { int margin_top = 6; auto bounds = getLocalBounds(); bounds.removeFromTop(margin_top); m_send_button.setBounds(bounds.removeFromRight(60)); bounds.removeFromRight(4); m_message_editor.setBounds(bounds); } // ================================================================================ // // BEACON DISPATCHER ELEM // // ================================================================================ // BeaconDispatcherElem::BeaconDispatcherElem(engine::Instance& instance) : m_instance(instance), m_beacon_name_editor("beacon_name_editor"), m_text_value(*this), m_message_slider("message_slider"), m_toggle_value("On/Off"), m_message_tab(juce::TabbedButtonBar::Orientation::TabsAtTop) { setInterceptsMouseClicks(false, true); // beacon name field m_beacon_name_editor.setReturnKeyStartsNewLine(false); m_beacon_name_editor.setMultiLine(false, false); m_beacon_name_editor.setTextToShowWhenEmpty("Symbol name", findColour(juce::TextEditor::ColourIds::textColourId).withAlpha(0.3f)); // slider value m_message_slider.setRange(0., 1., 0.001); m_message_slider.setSliderStyle(juce::Slider::SliderStyle::LinearHorizontal); m_message_slider.addListener(this); // toggle value m_toggle_value.addListener(this); // message value tab m_message_tab.addTab("text", juce::Colours::black.withAlpha(0.f), &m_text_value, false); m_message_tab.addTab("slider", juce::Colours::black.withAlpha(0.f), &m_message_slider, false); m_message_tab.addTab("toggle", juce::Colours::black.withAlpha(0.f), &m_toggle_value, false); m_message_tab.setOutline(0); m_message_tab.setTabBarDepth(20); addAndMakeVisible(m_beacon_name_editor); addAndMakeVisible(m_message_tab); setSize(310, 100); } BeaconDispatcherElem::~BeaconDispatcherElem() { m_message_slider.removeListener(this); m_toggle_value.removeListener(this); } void BeaconDispatcherElem::restoreState(juce::XmlElement* saved_state) { if (saved_state->hasTagName("BEACON")) { juce::String name = saved_state->getStringAttribute("name"); int tab_idx = saved_state->getIntAttribute("value_tab_idx"); if(name.isNotEmpty()) { m_beacon_name_editor.setText(name); } m_message_tab.setCurrentTabIndex(tab_idx); } } void BeaconDispatcherElem::saveState(juce::XmlElement* saved_state) { if(saved_state->hasTagName("BEACON")) { saved_state->setAttribute("name", m_beacon_name_editor.getText()); saved_state->setAttribute("value_tab_idx", m_message_tab.getCurrentTabIndex()); } } void BeaconDispatcherElem::setBackgroundColor(juce::Colour const& color) { m_bgcolor = color; m_beacon_name_editor.setColour(juce::TextEditor::backgroundColourId, juce::Colours::black.withAlpha(0.1f)); repaint(); } void BeaconDispatcherElem::paint(juce::Graphics& g) { g.fillAll(m_bgcolor); } void BeaconDispatcherElem::resized() { int padding = 4; int texteditor_height = 24; int margin_top = 6; int margin_bottom = 6; auto bounds = getLocalBounds().reduced(padding); bounds.removeFromTop(margin_top); auto texteditor_bounds = bounds.removeFromTop(texteditor_height); texteditor_bounds.reduce(padding, 0); m_beacon_name_editor.setBounds(texteditor_bounds); bounds.removeFromTop(margin_bottom); bounds.reduce(padding, 0); m_message_tab.setBounds(bounds.removeFromTop(50)); } void BeaconDispatcherElem::buttonClicked(juce::Button* btn) { if(btn == &m_toggle_value) { std::string name = m_beacon_name_editor.getText().toStdString(); send(name, {m_toggle_value.getToggleState()}); } } void BeaconDispatcherElem::sliderValueChanged(juce::Slider* slider) { if(slider == &m_message_slider) { std::string name = m_beacon_name_editor.getText().toStdString(); send(name, {m_message_slider.getValue()}); } } void BeaconDispatcherElem::sendValue(std::vector<tool::Atom> const& args) const { send(m_beacon_name_editor.getText().toStdString(), args); } void BeaconDispatcherElem::send(std::string const& name, std::vector<tool::Atom> const& args) const { if(!name.empty() && !args.empty()) { tool::Beacon& beacon = m_instance.getBeacon(name); beacon.dispatch(args); } } // ================================================================================ // // CONSOLE TOOLBAR // // ================================================================================ // BeaconDispatcherToolbarFactory::BeaconDispatcherToolbarFactory() { } void BeaconDispatcherToolbarFactory::getAllToolbarItemIds(juce::Array<int>& ids) { ids.add(addItem); ids.add(removeItem); ids.add(separatorBarId); ids.add(spacerId); ids.add(flexibleSpacerId); } void BeaconDispatcherToolbarFactory::getDefaultItemSet(juce::Array<int>& ids) { ids.add(flexibleSpacerId); ids.add(addItem); ids.add(removeItem); } juce::ToolbarItemComponent* BeaconDispatcherToolbarFactory::createItem(int itemId) { juce::ToolbarItemComponent* btn = nullptr; if(itemId == addItem) { btn = new juce::ToolbarButton(itemId, "Add item", juce::Drawable::createFromImageData(binary_data::images::plus_png, binary_data::images::plus_png_size), nullptr); btn->setCommandToTrigger(&KiwiApp::getCommandManager(), CommandIDs::addBeaconDispatcher, true); } else if(itemId == removeItem) { btn = new juce::ToolbarButton(itemId, "Remove item", juce::Drawable::createFromImageData(binary_data::images::minus_png, binary_data::images::minus_png_size), nullptr); btn->setCommandToTrigger(&KiwiApp::getCommandManager(), CommandIDs::removeBeaconDispatcher, true); } return btn; } // ================================================================================ // // BEACON DISPATCHER // // ================================================================================ // BeaconDispatcher::BeaconDispatcher(engine::Instance& instance) : m_instance(instance), m_toolbar() { m_toolbar.setVertical(false); m_toolbar.setStyle(juce::Toolbar::ToolbarItemStyle::iconsOnly); m_toolbar.setColour(juce::Toolbar::ColourIds::backgroundColourId, juce::Colours::transparentBlack); addAndMakeVisible(m_toolbar); m_toolbar.addDefaultItems(m_toolbar_factory); KiwiApp::bindToCommandManager(this); if(!restoreState()) { addElem(); } updateLayout(); } BeaconDispatcher::~BeaconDispatcher() { saveState(); } void BeaconDispatcher::addElem() { auto it = m_components.emplace(m_components.end(), std::make_unique<BeaconDispatcherElem>(m_instance)); addAndMakeVisible(it->get()); updateLayout(); } void BeaconDispatcher::removeElem() { if(m_components.size() > 1) { const auto it = m_components.end() - 1; removeChildComponent(it->get()); m_components.erase(it); updateLayout(); } } void BeaconDispatcher::resized() { auto bounds = getLocalBounds(); m_toolbar.setBounds(bounds.removeFromTop(24)); for(auto& elem : m_components) { elem->setSize(getWidth(), m_elem_height); } } void BeaconDispatcher::updateLayout() { const auto nelems = m_components.size(); juce::Rectangle<int> bounds(0, 0, getWidth(), m_elem_height * nelems + m_toolbar.getHeight() + (nelems - 1) * 2); setBounds(bounds); bounds.removeFromTop(m_toolbar.getHeight()); auto& lf = KiwiApp::useLookAndFeel(); const auto bgcolor = lf.getCurrentColourScheme().getUIColour(juce::LookAndFeel_V4::ColourScheme::UIColour::windowBackground).contrasting(0.2); for(size_t i = 0; i < nelems; ++i) { if(i > 0) { bounds.removeFromTop(2); } auto& elem = *m_components[i]; elem.setBounds(bounds.removeFromTop(m_elem_height)); elem.setBackgroundColor(bgcolor); } } bool BeaconDispatcher::restoreState() { bool success = false; m_components.clear(); std::unique_ptr<juce::XmlElement> saved_state(getGlobalProperties() .getXmlValue("beacon_dispatcher_state")); if(saved_state) { if (saved_state->hasTagName("BEACONS")) { int count = 0; forEachXmlChildElement(*saved_state, e) { addElem(); m_components[count++]->restoreState(e); success = true; } } } return success; } void BeaconDispatcher::saveState() { auto saved_state = std::make_unique<juce::XmlElement>("BEACONS"); for(auto& elem : m_components) { auto* child_state = saved_state->createNewChildElement("BEACON"); elem->saveState(child_state); } getGlobalProperties().setValue("beacon_dispatcher_state", saved_state.get()); } // ================================================================================ // // APPLICATION COMMAND TARGET // // ================================================================================ // juce::ApplicationCommandTarget* BeaconDispatcher::getNextCommandTarget() { return findFirstTargetParentComponent(); } void BeaconDispatcher::getAllCommands(juce::Array<juce::CommandID>& commands) { commands.add(CommandIDs::addBeaconDispatcher); commands.add(CommandIDs::removeBeaconDispatcher); } void BeaconDispatcher::getCommandInfo(const juce::CommandID commandID, juce::ApplicationCommandInfo& result) { switch (commandID) { case CommandIDs::addBeaconDispatcher: { result.setInfo(TRANS("Add a new beacon dispatcher"), TRANS("Add a new beacon dispatcher"), CommandCategories::editing, 0); result.setActive(m_components.size() <= 5); break; } case CommandIDs::removeBeaconDispatcher: result.setInfo(TRANS("Remove a beacon dispatcher"), TRANS("Remove a beacon dispatcher"), CommandCategories::windows, 0); result.setActive(m_components.size() > 1); break; default: break; } } bool BeaconDispatcher::perform(InvocationInfo const& info) { switch (info.commandID) { case CommandIDs::addBeaconDispatcher: addElem(); break; case CommandIDs::removeBeaconDispatcher: removeElem(); break; default: return false; } return true; } }
14,713
C++
.cpp
345
32.605797
180
0.57581
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,342
KiwiApp_Console.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Application/KiwiApp_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 : [email protected] ============================================================================== */ #include "KiwiApp_Console.h" #include "../KiwiApp.h" #include "../KiwiApp_General/KiwiApp_StoredSettings.h" #include "../KiwiApp_Resources/KiwiApp_BinaryData.h" #include "../KiwiApp_General/KiwiApp_CommandIDs.h" namespace kiwi { // ================================================================================ // // CONSOLE COMPONENT // // ================================================================================ // ConsoleContent::ConsoleContent(sConsoleHistory history) : m_history(history), m_font(16.f) { assert(history); history->addListener(*this); setSize(300, 500); juce::TableHeaderComponent* header = new juce::TableHeaderComponent(); header->addColumn(juce::String("Message"), Column::Message, 100, 40, 10000, juce::TableHeaderComponent::defaultFlags, -1); header->setStretchToFitActive(false); header->setColumnVisible(1, true); header->addListener(this); m_table.setWantsKeyboardFocus(true); m_table.setMultipleSelectionEnabled(true); m_table.setMouseMoveSelectsRows(false); m_table.setHeaderHeight(m_font.getHeight() + 15); m_table.setRowHeight(m_font.getHeight() + 5); m_table.setColour(juce::ListBox::ColourIds::backgroundColourId, juce::Colours::transparentWhite); m_table.getViewport()->setScrollBarsShown(true, false, true, false); m_table.setModel(this); m_table.setHeader(header); addAndMakeVisible(m_table); } ConsoleContent::~ConsoleContent() { sConsoleHistory history = getHistory(); if(history) { history->removeListener(*this); } } sConsoleHistory ConsoleContent::getHistory() { return m_history.lock(); } // ================================================================================ // // COMMAND // // ================================================================================ // void ConsoleContent::copy() { sConsoleHistory history = getHistory(); if(history) { juce::String text; juce::SparseSet<int> selection = m_table.getSelectedRows(); for(size_t i = 0; i < selection.size(); i++) { auto msg = history->get(selection[i]).first; if(msg && !msg->text.empty()) { text += juce::String(msg->text + "\n"); } } juce::SystemClipboard::copyTextToClipboard(text); } } void ConsoleContent::erase() { sConsoleHistory history = getHistory(); if(history) { juce::SparseSet<int> selection = m_table.getSelectedRows(); std::vector<size_t> select; for(size_t i = 0; i < selection.size(); i++) { select.push_back(selection[i]); } history->erase(select); m_table.setVerticalPosition(0); } } // ================================================================================ // // HISTORY LISTENER // // ================================================================================ // void ConsoleContent::consoleHistoryChanged(ConsoleHistory const&) { tool::Scheduler<> &scheduler = KiwiApp::useScheduler(); scheduler.defer([this]() { m_table.updateContent(); m_table.repaint(); }); } // ================================================================================ // // COMPONENT // // ================================================================================ // void ConsoleContent::resized() { m_table.setBounds(getLocalBounds()); updateRighmostColumnWidth(&m_table.getHeader()); } void ConsoleContent::paint(juce::Graphics& g) { g.fillAll(juce::Colours::lightgrey); int width = m_table.getVisibleContentWidth(); int rowheight = m_table.getRowHeight(); g.setColour(juce::Colours::black.withAlpha(0.15f)); for(int i = m_table.getHeaderHeight() - 1; i < getHeight(); i+= rowheight) { g.drawHorizontalLine(i, 0, width); } } void ConsoleContent::scrollToTop() { m_table.scrollToEnsureRowIsOnscreen(0); } void ConsoleContent::scrollToBottom() { m_table.scrollToEnsureRowIsOnscreen(m_table.getNumRows()); } void ConsoleContent::clearAll() { m_table.selectRangeOfRows(0, m_table.getNumRows()); erase(); } // ================================================================================ // // FileDragAndDropTarget // // ================================================================================ // bool ConsoleContent::isInterestedInFileDrag(juce::StringArray const& files) { if(!files.isEmpty()) { juce::File file = files[0]; return file.hasFileExtension(".kiwi;.kiwihelp"); } return false; } void ConsoleContent::fileDragEnter(juce::StringArray const&, int, int) { m_is_dragging_over = true; repaint(); } void ConsoleContent::fileDragExit(juce::StringArray const&) { m_is_dragging_over = false; repaint(); } void ConsoleContent::filesDropped(juce::StringArray const& files, int x, int y) { if(!files.isEmpty()) { juce::File file = files[0]; KiwiApp::useInstance().openFile(file); m_is_dragging_over = false; repaint(); } } // ================================================================================ // // TABLE LIST BOX MODEL // // ================================================================================ // void ConsoleContent::selectedRowsChanged(int row) { KiwiApp::commandStatusChanged(); } void ConsoleContent::deleteKeyPressed(int lastRowSelected) { erase(); } void ConsoleContent::backgroundClicked(const juce::MouseEvent& mouse) { m_table.deselectAllRows(); } int ConsoleContent::getNumRows() { sConsoleHistory history = getHistory(); return history ? history->size() : 0; } int ConsoleContent::getNumSelectedRows() const { return m_table.getNumSelectedRows(); } void ConsoleContent::paintRowBackground(juce::Graphics& g, int rowNumber, int width, int height, bool selected) { sConsoleHistory history = getHistory(); if(!history) return; //abort const juce::Colour bgcolor(juce::Colours::lightgrey); auto msg = history->get(rowNumber).first; if(msg) { if(selected) { g.fillAll(juce::Colours::lightsteelblue); } else if(msg->type == engine::Console::Message::Type::Error) { g.fillAll(juce::Colours::lightpink); } else if(msg->type == engine::Console::Message::Type::Warning) { g.fillAll(juce::Colours::lightgoldenrodyellow); } else { g.fillAll(bgcolor); } } else { g.fillAll(bgcolor); } g.setColour(juce::Colours::black.withAlpha(0.15f)); g.drawHorizontalLine(height - 1, 0, width); } void ConsoleContent::paintOverChildren(juce::Graphics &g) { int numColumns = m_table.getHeader().getNumColumns(true); float left = 0, width = 0; for(int i = 0; i < numColumns - 1; i++) { width = m_table.getHeader().getColumnWidth(m_table.getHeader().getColumnIdOfIndex(i, true)); if(m_table.getVisibleContentWidth() >= width + left) { g.setColour(juce::Colours::black.withAlpha(0.15f)); g.drawVerticalLine(left + width - 0.5, m_table.getHeaderHeight(), getHeight()); } left += width; } if(m_is_dragging_over) { g.setColour(juce::Colours::blue.withAlpha(0.5f)); g.drawRect(getLocalBounds().withTop(m_table.getHeaderHeight()), 5); } } void ConsoleContent::paintCell(juce::Graphics& g, int rowNumber, int columnId, int width, int height, bool rowIsSelected) { sConsoleHistory history = getHistory(); if(!history) return; //abort auto pair = history->get(rowNumber); auto msg = pair.first; if(msg) { g.setColour(juce::Colours::black.brighter(0.4)); g.setFont(m_font); switch (columnId) { case Column::Message: { auto repeat_times = pair.second; if(repeat_times == 0) { g.drawText(msg->text, 2, 0, width - 4, height, juce::Justification::centredLeft, true); } else { g.drawText("[" + std::to_string(repeat_times) + "x] " + msg->text, 2, 0, width - 4, height, juce::Justification::centredLeft, true); } break; } default: break; } } } void ConsoleContent::sortOrderChanged(int newSortColumnId, bool isForwards) { sConsoleHistory history = getHistory(); if(!history) return; //abort history->sort(static_cast<ConsoleHistory::Sort>(newSortColumnId)); m_table.updateContent(); } void ConsoleContent::cellDoubleClicked(int rowNumber, int columnId, const juce::MouseEvent& mouse) { // TODO : hilight (if possible) object corresponding to the dblclicked row } juce::Component* ConsoleContent::refreshComponentForCell(int, int, bool, Component* existingComponentToUpdate) { // Just return 0, as we'll be painting these columns directly. jassert(existingComponentToUpdate == 0); return nullptr; } // This is overloaded from TableListBoxModel, and should choose the best width for the specified // column. int ConsoleContent::getColumnAutoSizeWidth(int columnId) { int widest = 32; sConsoleHistory history = getHistory(); if(history) { // find the widest bit of text in this column.. for(int i = getNumRows(); --i >= 0;) { if(auto msg = history->get(i).first) { widest = std::max(widest, m_font.getStringWidth(msg->text)); } } } return widest + 8; } void ConsoleContent::tableColumnsResized(juce::TableHeaderComponent* tableHeader) { if(tableHeader == &m_table.getHeader()) { updateRighmostColumnWidth(&m_table.getHeader()); } } void ConsoleContent::updateRighmostColumnWidth(juce::TableHeaderComponent* header) { int rightmostColumnId = 0; int rightmostColumnX = 0; for(int i = 0; i <= header->getNumColumns(false) - 1; i++) { if(header->isColumnVisible(i) && rightmostColumnId <= header->getIndexOfColumnId(i, true)) { rightmostColumnId = i; } } rightmostColumnId = header->getColumnIdOfIndex(header->getNumColumns(true)-1, true); rightmostColumnX = header->getTotalWidth() - header->getColumnWidth(rightmostColumnId); if(rightmostColumnX <= getWidth()) { m_table.getHeader().setColumnWidth(rightmostColumnId, getWidth() - rightmostColumnX); } } // ================================================================================ // // CONSOLE TOOLBAR // // ================================================================================ // ConsoleToolbarFactory::ConsoleToolbarFactory() { } void ConsoleToolbarFactory::getAllToolbarItemIds(juce::Array<int>& ids) { ids.add(clear); ids.add(scroll_to_top); ids.add(scroll_to_bottom); ids.add(separatorBarId); ids.add(spacerId); ids.add(flexibleSpacerId); } void ConsoleToolbarFactory::getDefaultItemSet(juce::Array<int>& ids) { ids.add(clear); ids.add(flexibleSpacerId); ids.add(scroll_to_top); ids.add(scroll_to_bottom); } juce::ToolbarItemComponent* ConsoleToolbarFactory::createItem(int itemId) { juce::ToolbarItemComponent* btn = nullptr; if(itemId == clear) { btn = new juce::ToolbarButton(itemId, "clear", juce::Drawable::createFromImageData(binary_data::images::trash_png, binary_data::images::trash_png_size), nullptr); btn->setCommandToTrigger(&KiwiApp::getCommandManager(), CommandIDs::clearAll, true); } else if(itemId == scroll_to_top) { btn = new juce::ToolbarButton(itemId, "top", juce::Drawable::createFromImageData(binary_data::images::arrow_up_png, binary_data::images::arrow_up_png_size), nullptr); btn->setCommandToTrigger(&KiwiApp::getCommandManager(), CommandIDs::scrollToTop, true); } else if(itemId == scroll_to_bottom) { btn = new juce::ToolbarButton(itemId, "bottom", juce::Drawable::createFromImageData(binary_data::images::arrow_down_png, binary_data::images::arrow_down_png_size), nullptr); btn->setCommandToTrigger(&KiwiApp::getCommandManager(), CommandIDs::scrollToBottom, true); } return btn; } // ================================================================================ // // CONSOLE COMPONENT // // ================================================================================ // Console::Console(sConsoleHistory history) : m_console(history) { addAndMakeVisible(m_console); KiwiApp::bindToCommandManager(this); KiwiApp::bindToKeyMapping(this); m_toolbar.setVertical(false); m_toolbar.setStyle(juce::Toolbar::ToolbarItemStyle::iconsOnly); m_toolbar.setColour(juce::Toolbar::ColourIds::backgroundColourId, juce::Colours::transparentBlack); addAndMakeVisible(m_toolbar); // And use our item factory to add a set of default icons to it... m_toolbar.addDefaultItems(m_toolbar_factory); } void Console::resized() { const int toolbar_size = 40; const int toolbar_limit = getHeight() - toolbar_size; m_console.setBounds(getLocalBounds().withBottom(toolbar_limit)); m_toolbar.setBounds(getLocalBounds().withTop(toolbar_limit).reduced(7)); } void Console::paint(juce::Graphics& g) { const int toolbar_size = 40; const auto header_bounds = getLocalBounds().withTop(getHeight() - toolbar_size); auto& lf = KiwiApp::useLookAndFeel(); g.setColour(lf.getCurrentColourScheme() .getUIColour(juce::LookAndFeel_V4::ColourScheme::UIColour::windowBackground)); g.fillRect(header_bounds); } // ================================================================================ // // APPLICATION COMMAND TARGET // // ================================================================================ // juce::ApplicationCommandTarget* Console::getNextCommandTarget() { return findFirstTargetParentComponent(); } void Console::getAllCommands(juce::Array<juce::CommandID>& commands) { commands.add(juce::StandardApplicationCommandIDs::copy); commands.add(CommandIDs::clearAll); commands.add(CommandIDs::scrollToTop); commands.add(CommandIDs::scrollToBottom); } void Console::getCommandInfo(const juce::CommandID commandID, juce::ApplicationCommandInfo& result) { switch (commandID) { case juce::StandardApplicationCommandIDs::copy: { result.setInfo(TRANS("Copy"), TRANS("Copy"), CommandCategories::editing, 0); result.addDefaultKeypress('c', juce::ModifierKeys::commandModifier); result.setActive(m_console.getNumSelectedRows() > 0); break; } case CommandIDs::clearAll: { result.setInfo(TRANS("Clear console history"), TRANS("Clear console history"), CommandCategories::editing, 0); //result.setActive(m_console.getNumRows() > 0); break; } case CommandIDs::scrollToTop: result.setInfo(TRANS("Scroll to the top"), TRANS("Scroll to the top"), CommandCategories::windows, 0); break; case CommandIDs::scrollToBottom: result.setInfo(TRANS("Scroll to the bottom"), TRANS("Scroll to the bottom"), CommandCategories::windows, 0); break; default: break; } } bool Console::perform(InvocationInfo const& info) { switch (info.commandID) { case juce::StandardApplicationCommandIDs::copy: m_console.copy(); break; case CommandIDs::clearAll: m_console.clearAll(); break; case CommandIDs::scrollToTop: m_console.scrollToTop(); break; case CommandIDs::scrollToBottom: m_console.scrollToBottom(); break; default: return false; } return true; } }
20,115
C++
.cpp
474
31.533755
185
0.515529
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,343
KiwiApp_Instance.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Application/KiwiApp_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 : [email protected] ============================================================================== */ #include <juce_audio_utils/juce_audio_utils.h> #include <KiwiModel/KiwiModel_DocumentManager.h> #include "KiwiApp_Instance.h" #include "KiwiApp_AboutWindow.h" #include "../KiwiApp.h" #include "../KiwiApp_Components/KiwiApp_Window.h" #include "../KiwiApp_Patcher/KiwiApp_PatcherView.h" #include "../KiwiApp_Patcher/KiwiApp_PatcherComponent.h" #include "../KiwiApp_General/KiwiApp_CommandIDs.h" namespace kiwi { // ================================================================================ // // INSTANCE // // ================================================================================ // size_t Instance::m_untitled_patcher_index(1); Instance::Instance() : m_instance(std::make_unique<DspDeviceManager>(), KiwiApp::useScheduler()) , m_browser("Offline", 1000) , m_console_history(std::make_shared<ConsoleHistory>(m_instance)) { // reserve space for singleton windows. m_windows.resize(std::size_t(WindowId::count)); showDocumentBrowserWindow(); showConsoleWindow(); } Instance::~Instance() { forceCloseAllPatcherWindows(); } uint64_t Instance::getUserId() const noexcept { const auto& user = KiwiApp::getCurrentUser(); return user.isLoggedIn() ? user.getIdAsInt() : flip::Ref::User::Offline; } void Instance::login() { if(getUserId() > flip::Ref::User::Offline) { m_browser.setDriveName(KiwiApp::getCurrentUser().getName()); m_windows[std::size_t(WindowId::DocumentBrowser)]->getContentComponent()->setEnabled(true); } else { showAuthWindow(AuthPanel::FormType::Login); } } void Instance::handleConnectionLost() { m_browser.setDriveName("Offline"); m_windows[std::size_t(WindowId::DocumentBrowser)]->getContentComponent()->setEnabled(false); } void Instance::tick() { static bool is_pulling = false; if(!is_pulling) { is_pulling = true; pullRemoteDocuments(); is_pulling = false; } } bool Instance::askUserToContinueEditingDocumentOffline(PatcherManager& manager, std::string const& reason) const { auto& first_window = manager.getFirstWindow(); auto message = std::string("Do you want to continue editing document \""); message += manager.getDocumentName() + "\" offline ?"; return first_window.showOkCancelBox(juce::AlertWindow::QuestionIcon, reason, message, "Yes", "No"); } void Instance::pullRemoteDocuments() { const bool user_logged_in = KiwiApp::getCurrentUser().isLoggedIn(); const bool is_connected_to_api = (KiwiApp::canConnectToServer() && user_logged_in); auto manager_it = m_patcher_managers.begin(); while(manager_it != m_patcher_managers.end()) { auto& manager = *(*manager_it); if (manager.isConnected()) { manager.pull(); // This is here we pull the flip document. const bool is_still_connected = manager.isConnected(); const bool connection_lost = !is_still_connected; if(connection_lost || (is_still_connected && (!is_connected_to_api || !user_logged_in))) { auto reason = user_logged_in ? "Connection lost" : "You are logged out"; bool keep_edit = askUserToContinueEditingDocumentOffline(manager, reason); if(!keep_edit) { // the user wants to close the document manager.forceCloseAllWindows(); manager_it = m_patcher_managers.erase(manager_it); continue; } else if(!is_connected_to_api) { manager.disconnect(); } } } ++manager_it; } } engine::Instance& Instance::useEngineInstance() { return m_instance; } engine::Instance const& Instance::useEngineInstance() const { return m_instance; } void Instance::newPatcher() { std::string patcher_name = "Untitled " + std::to_string(getNextUntitledNumberAndIncrement()); PatcherManager & manager = (*m_patcher_managers.emplace(m_patcher_managers.end(), new PatcherManager(*this, patcher_name))->get()); if(manager.getNumberOfView() == 0) { manager.newView(); } model::DocumentManager::commit(manager.getPatcher()); } bool Instance::openFile(juce::File const& file) { if(!file.hasFileExtension(".kiwi;.kiwihelp")) { KiwiApp::error("can't open file (bad file extension)"); return false; } { auto manager_it = getPatcherManagerForFile(file); // If a patcher already manages this file, just brings it to front if (manager_it != m_patcher_managers.end()) { (*manager_it)->bringsFirstViewToFront(); return true; } } // there is no manager for this file so lets create one std::unique_ptr<PatcherManager> temp_manager = nullptr; try { temp_manager = PatcherManager::createFromFile(*this, file); } catch (std::runtime_error const& err) { const std::string error = err.what(); const std::string filename = file.getFileName().toStdString(); KiwiApp::error("Can't open document \"" + filename + "\""); KiwiApp::error("error: " + error); KiwiApp::error("Please download latest Kiwi version."); return false; } if(temp_manager) { auto manager_it = m_patcher_managers.emplace(m_patcher_managers.end(), std::move(temp_manager)); auto& manager = *(manager_it->get()); if(manager.getNumberOfView() == 0) { manager.newView(); } return true; } return false; } void Instance::askUserToOpenPatcherDocument() { const auto dir = KiwiApp::getGlobalDirectoryFor(KiwiApp::FileLocations::Open); juce::FileChooser file_chooser("Open file", dir, "*.kiwi;*.kiwihelp"); if(file_chooser.browseForFileToOpen()) { juce::File selected_file = file_chooser.getResult(); const bool success = openFile(selected_file); if(success) { KiwiApp::setGlobalDirectoryFor(KiwiApp::FileLocations::Open, selected_file.getParentDirectory()); } } } void Instance::removePatcherWindow(PatcherViewWindow& patcher_window) { if (!m_patcher_managers.empty()) { PatcherManager& manager = patcher_window.getPatcherManager(); auto manager_it = getPatcherManager(manager); if (manager_it != m_patcher_managers.end()) { PatcherView& patcherview = patcher_window.getPatcherView(); manager.closePatcherViewWindow(patcherview); if(manager.getNumberOfView() == 0) { m_patcher_managers.erase(manager_it); } } } } void Instance::closeWindow(Window& window) { auto is_equal_fn = [&window](std::unique_ptr<Window> const& w) { return (w.get() == &window); }; auto found_window = std::find_if(m_windows.begin(), m_windows.end(), is_equal_fn); if(found_window != m_windows.end()) { // if it's a regular window, simply reset the ptr if(found_window < m_windows.begin() + std::size_t(WindowId::count)) { found_window->reset(); } else { m_windows.erase(found_window); } } #if ! JUCE_MAC auto is_main_window_fn = [](std::unique_ptr<Window> const& window) { return window && window->isMainWindow(); }; size_t main_windows = std::count_if(m_windows.begin(), m_windows.end(), is_main_window_fn); if (main_windows == 0) { KiwiApp::use().systemRequestedQuit(); } #endif } void Instance::closeWindowWithId(WindowId window_id) { auto& window_uptr = m_windows[std::size_t(window_id)]; if(!window_uptr) { closeWindow(*window_uptr); } } bool Instance::closeAllPatcherWindows() { bool success = true; if(!m_patcher_managers.empty()) { for(auto& manager_uptr : m_patcher_managers) { if(!manager_uptr->askAllWindowsToClose()) { success = false; break; } } } return success; } void Instance::forceCloseAllPatcherWindows() { for(auto& manager : m_patcher_managers) { manager->forceCloseAllWindows(); } m_patcher_managers.clear(); } void Instance::openRemotePatcher(DocumentBrowser::Drive::DocumentSession& session) { auto mng_it = getPatcherManagerForSession(session); if(mng_it != m_patcher_managers.end()) { PatcherManager& manager = *(mng_it->get()); manager.bringsFirstViewToFront(); } else { auto manager_uptr = std::make_unique<PatcherManager>(*this, session.getName()); NetworkSettings& network_settings = getAppSettings().network(); if (manager_uptr->connect(network_settings.getHost(), network_settings.getSessionPort(), session)) { auto manager_it = m_patcher_managers.emplace(m_patcher_managers.end(), std::move(manager_uptr)); PatcherManager& manager = *(manager_it->get()); if(manager.getNumberOfView() == 0) { manager.newView(); } } else { KiwiApp::error("Failed to connect to the document [" + session.getName() + "]"); } } } Instance::PatcherManagers::iterator Instance::getPatcherManager(PatcherManager const& manager) { const auto find_fn = [&manager](std::unique_ptr<PatcherManager> const& other) { return &manager == other.get(); }; return std::find_if(m_patcher_managers.begin(), m_patcher_managers.end(), find_fn); } Instance::PatcherManagers::iterator Instance::getPatcherManagerForFile(juce::File const& file) { const auto find_it = [&file](std::unique_ptr<PatcherManager> const& manager_uptr) { return (!manager_uptr->isConnected() && file == manager_uptr->getSelectedFile()); }; return std::find_if(m_patcher_managers.begin(), m_patcher_managers.end(), find_it); } Instance::PatcherManagers::iterator Instance::getPatcherManagerForSession(DocumentBrowser::Drive::DocumentSession& session) { const auto find_it = [session_id = session.getSessionId()](std::unique_ptr<PatcherManager> const& manager_uptr) { return (manager_uptr->isConnected() && session_id != 0 && session_id == manager_uptr->getSessionId()); return false; }; return std::find_if(m_patcher_managers.begin(), m_patcher_managers.end(), find_it); } void Instance::showConsoleWindow() { showWindowWithId(WindowId::Console, [&history = m_console_history](){ return std::make_unique<Window>("Kiwi Console", std::make_unique<Console>(history), true, true, "console_window", !KiwiApp::isMacOSX()); }); } void Instance::showAuthWindow(AuthPanel::FormType type) { showWindowWithId(WindowId::FormComponent, [type]() { auto window = std::make_unique<Window>("Kiwi", std::make_unique<AuthPanel>(type), false, false); window->centreWithSize(window->getWidth(), window->getHeight()); window->enterModalState(true); return window; }); } void Instance::showAboutKiwiWindow() { showWindowWithId(WindowId::AboutKiwi, [](){ return std::make_unique<AboutWindow>(); }); } void Instance::showDocumentBrowserWindow() { showWindowWithId(WindowId::DocumentBrowser, [&browser = m_browser](){ const bool can_connect = (KiwiApp::canConnectToServer() && KiwiApp::getCurrentUser().isLoggedIn()); return std::make_unique<Window>("Document Browser", std::make_unique<DocumentBrowserView>(browser, can_connect), true, false, "document_browser_window"); }); } void Instance::showBeaconDispatcherWindow() { showWindowWithId(WindowId::BeaconDispatcher, [&instance = m_instance](){ return std::make_unique<Window>("Beacon dispatcher", std::make_unique<BeaconDispatcher>(instance), false, true, "beacon_dispatcher_window"); }); } void Instance::showAppSettingsWindow() { showWindowWithId(WindowId::ApplicationSettings, [](){ return std::make_unique<Window>("Application settings", std::make_unique<SettingsPanel>(), false, true, "application_settings_window"); }); } void Instance::showAudioSettingsWindow() { showWindowWithId(WindowId::AudioSettings, [&instance = m_instance](){ auto& manager = dynamic_cast<DspDeviceManager&>(instance.getAudioControler()); auto device_selector = std::make_unique<juce::AudioDeviceSelectorComponent>(manager, 1, 20, 1, 20, false, false, false, false); device_selector->setSize(300, 300); return std::make_unique<Window>("Audio Settings", std::move(device_selector), true, false, "audio_settings_window"); }); } std::vector<uint8_t>& Instance::getPatcherClipboardData() { return m_patcher_clipboard; } size_t Instance::getNextUntitledNumberAndIncrement() { return m_untitled_patcher_index++; } void Instance::showWindowWithId(WindowId id, std::function<std::unique_ptr<Window>()> create_fn) { auto& window_uptr = m_windows[std::size_t(id)]; if(!window_uptr) { window_uptr = create_fn(); } window_uptr->setVisible(true); window_uptr->toFront(true); } }
17,931
C++
.cpp
415
28.708434
128
0.52352
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,344
KiwiApp_DocumentBrowserView.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Application/KiwiApp_DocumentBrowserView.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 : [email protected] ============================================================================== */ #include <flip/BackEndBinary.h> #include <flip/contrib/DataProviderFile.h> #include <flip/BackEndIR.h> #include <KiwiModel/KiwiModel_Def.h> #include <KiwiEngine/KiwiEngine_Console.h> #include "KiwiApp_DocumentBrowserView.h" #include "KiwiApp_Instance.h" #include "../KiwiApp_Resources/KiwiApp_BinaryData.h" #include "../KiwiApp_Utils/KiwiApp_SuggestList.h" #include "../KiwiApp.h" #include <juce_gui_basics/juce_gui_basics.h> namespace kiwi { // ================================================================================ // // DOCUMENT BROWSER // // ================================================================================ // DocumentBrowserView::DocumentBrowserView(DocumentBrowser& browser, bool enabled) : m_browser(browser) { setSize(300, 300); DocumentBrowser::Drive & drive = *m_browser.getDrive(); auto drive_view = std::make_unique<DriveView>(drive); drive_view->setSize(getWidth(), drive_view->getHeight()); addAndMakeVisible(drive_view.get()); m_drives.emplace_back(std::move(drive_view)); resized(); setEnabled(enabled); } DocumentBrowserView::~DocumentBrowserView() { } void DocumentBrowserView::resized() { const auto bounds = getLocalBounds(); int last_bottom = 0; for(auto const& drive_view_uptr : m_drives) { drive_view_uptr->setBounds(bounds); last_bottom = drive_view_uptr->getBottom(); } } void DocumentBrowserView::paint(juce::Graphics& g) { ; } void DocumentBrowserView::enablementChanged() { for(auto & drive : m_drives) { drive->setEnabled(isEnabled()); } } // ================================================================================ // // DOCUMENT SESSION VIEW // // ================================================================================ // DocumentBrowserView::DriveView::RowElem::RowElem(DriveView& drive_view, std::string const& name, std::string const& tooltip) : m_drive_view(drive_view) , m_name(name) , m_name_label("name", m_name) , m_open_btn("open", std::unique_ptr<juce::Drawable>(juce::Drawable::createFromImageData(binary_data::images::open_png, binary_data::images::open_png_size)), ImageButton::ButtonStyle::ImageFitted) , m_kiwi_filetype_img(juce::ImageCache::getFromMemory(binary_data::images::kiwi_filetype_png, binary_data::images::kiwi_filetype_png_size)) { setTooltip(tooltip); if(!m_drive_view.isShowingTrashedDocuments()) { m_open_btn.setCommand(std::bind(&DriveView::openDocument, &m_drive_view, m_row)); m_open_btn.setSize(40, 40); m_open_btn.setTooltip("open this patcher"); addChildComponent(m_open_btn); } // label setup m_name_label.setEditable(false, true, true); m_name_label.addListener(this); m_name_label.setColour(juce::Label::textColourId, juce::Colours::black.contrasting(0.2)); m_name_label.setColour(juce::Label::textWhenEditingColourId, juce::Colours::black); m_name_label.setInterceptsMouseClicks(false, false); addAndMakeVisible(m_name_label); } DocumentBrowserView::DriveView::RowElem::~RowElem() { removeMouseListener(this); } void DocumentBrowserView::DriveView::RowElem::update(std::string const& name, std::string const& tooltip, int row, bool now_selected) { setTooltip(tooltip); m_row = row; m_open_btn.setCommand(std::bind(&DriveView::openDocument, &m_drive_view, m_row)); m_name = name; m_name_label.setText(m_name, juce::NotificationType::dontSendNotification); m_selected = now_selected; m_open_btn.setVisible(m_selected && !m_drive_view.isShowingTrashedDocuments()); repaint(); } void DocumentBrowserView::DriveView::RowElem::paint(juce::Graphics& g) { const bool is_trash_row = m_drive_view.isShowingTrashedDocuments(); auto bounds = getLocalBounds(); const juce::Colour bg_color(is_trash_row ? 0xDDDDDDDD : 0xDDFFFFFF); const juce::Colour selected_color_color(juce::Colours::lightblue); g.fillAll(((!is_trash_row && m_selected) ? selected_color_color : (m_mouseover ? bg_color.darker(0.1f) : bg_color))); if(!is_trash_row) { // document status notifier (connected / disconnected / not-connected) g.setColour(juce::Colours::grey); g.fillRect(bounds.removeFromLeft(5)); } g.setColour(bg_color.darker(0.5f)); g.drawHorizontalLine(getBottom() - 1, 0., getWidth()); g.drawImage(m_kiwi_filetype_img, bounds.removeFromLeft(getHeight()).reduced(5).toFloat(), juce::RectanglePlacement::stretchToFit, false); } void DocumentBrowserView::DriveView::RowElem::resized() { auto bounds = getLocalBounds().reduced(5); bounds.removeFromLeft(getHeight()); // image if(!m_drive_view.isShowingTrashedDocuments()) { m_open_btn.setBounds(bounds.removeFromRight(bounds.getHeight())); } m_name_label.setBounds(bounds); } void DocumentBrowserView::DriveView::RowElem::mouseEnter(juce::MouseEvent const& e) { m_mouseover = true; repaint(); } void DocumentBrowserView::DriveView::RowElem::mouseExit(juce::MouseEvent const& e) { m_mouseover = false; repaint(); } void DocumentBrowserView::DriveView::RowElem::showPopup() { juce::PopupMenu m; enum Commands : int { None = 0, Rename, MoveToTrash, RestoreTrashed, Upload, Duplicate, Download, SortByName, SortByCreationTime, SortByLastOpenedTime }; if (!m_drive_view.isShowingTrashedDocuments()) { m.addItem(Commands::Rename, "Rename"); m.addItem(Commands::MoveToTrash, "Move to trash"); m.addItem(Commands::Upload, "Upload"); m.addItem(Commands::Duplicate, "Duplicate"); } else { m.addItem(Commands::RestoreTrashed, "Restore"); } m.addItem(Commands::Download, "Download"); DriveView::SortBy current_sort = m_drive_view.getSortType(); juce::PopupMenu sort_menu; sort_menu.addItem(Commands::SortByName, "Name", current_sort != DriveView::SortBy::name, current_sort == DriveView::SortBy::name); sort_menu.addItem(Commands::SortByCreationTime, "Creation date", current_sort != DriveView::SortBy::creationTime, current_sort == DriveView::SortBy::creationTime); sort_menu.addItem(Commands::SortByLastOpenedTime, "Last opened", current_sort != DriveView::SortBy::openedTime, current_sort == DriveView::SortBy::openedTime); m.addSubMenu("Sort by", sort_menu); int result = m.show(); switch(result) { case Commands::Rename: // rename { m_name_label.showEditor(); break; } case Commands::MoveToTrash: // delete { m_drive_view.deleteDocumentForRow(m_row); break; } case Commands::RestoreTrashed: // restore { m_drive_view.restoreDocumentForRow(m_row); break; } case Commands::Download: // download document { m_drive_view.downloadDocumentForRow(m_row); break; } case Commands::Upload: // upload document { m_drive_view.uploadDocument(); break; } case Commands::Duplicate: // duplicate document { m_drive_view.duplicateDocumentForRow(m_row); break; } case Commands::SortByName: // sort by name { m_drive_view.setSortType(DriveView::SortBy::name); break; } case Commands::SortByCreationTime: // sort by creation date { m_drive_view.setSortType(DriveView::SortBy::creationTime); break; } case Commands::SortByLastOpenedTime: { m_drive_view.setSortType(DriveView::SortBy::openedTime); break; } } } void DocumentBrowserView::DriveView::RowElem::mouseDown(juce::MouseEvent const& e) { m_drive_view.selectRow(m_row); if (e.mods.isPopupMenu()) { showPopup(); } } void DocumentBrowserView::DriveView::RowElem::mouseUp(juce::MouseEvent const& e) { } void DocumentBrowserView::DriveView::RowElem::mouseDoubleClick(juce::MouseEvent const& event) { m_drive_view.listBoxItemDoubleClicked(m_row, event); } void DocumentBrowserView::DriveView::RowElem::labelTextChanged(juce::Label* label) { if(label == &m_name_label) { m_drive_view.renameDocumentForRow(m_row, m_name_label.getText().toStdString()); m_name_label.setText(m_name, juce::NotificationType::dontSendNotification); } } void DocumentBrowserView::DriveView::RowElem::showEditor() { m_name_label.showEditor(); } // ================================================================================ // // BROWSER DRIVE VIEW HEADER // // ================================================================================ // DocumentBrowserView::DriveView::Header::Header(DocumentBrowserView::DriveView& drive_view) : m_drive_view(drive_view) , m_refresh_btn("refresh", std::unique_ptr<juce::Drawable> (juce::Drawable::createFromImageData(binary_data::images::refresh_png, binary_data::images::refresh_png_size))) , m_create_document_btn("create", std::unique_ptr<juce::Drawable> (juce::Drawable::createFromImageData(binary_data::images::plus_png, binary_data::images::plus_png_size))) , m_trash_btn("trash", std::unique_ptr<juce::Drawable> (juce::Drawable::createFromImageData(binary_data::images::trash_png, binary_data::images::trash_png_size))) , m_search_btn("search", std::unique_ptr<juce::Drawable> (juce::Drawable::createFromImageData(binary_data::images::search_png, binary_data::images::search_png_size))) , m_folder_bounds() , m_label("drive_name", m_drive_view.getDriveName()) , m_folder_img(juce::ImageCache::getFromMemory(binary_data::images::folder_png, binary_data::images::folder_png_size)) , m_disable_folder_img(m_folder_img) { m_folder_img.duplicateIfShared(); m_disable_folder_img.multiplyAllAlphas(0.5); m_label.setFont(m_label.getFont().withHeight(20)); m_label.setEditable(false); m_label.setColour(juce::Label::textColourId, juce::Colours::whitesmoke); addAndMakeVisible(m_label); m_create_document_btn.setCommand([this]() { if (!m_drive_view.isShowingTrashedDocuments()) m_drive_view.createDocument(); }); m_create_document_btn.setSize(40, 40); m_create_document_btn.setTooltip("Create a new hosted patcher"); addAndMakeVisible(m_create_document_btn); m_refresh_btn.setCommand([this](){ m_drive_view.refresh(); }); m_refresh_btn.setSize(40, 40); m_refresh_btn.setTooltip("Refresh list"); addAndMakeVisible(m_refresh_btn); m_trash_btn.setCommand([this]() { const bool was_in_trash_mode = m_drive_view.isShowingTrashedDocuments(); const bool is_in_trash_mode = !was_in_trash_mode; m_drive_view.setTrashMode(is_in_trash_mode); m_trash_btn.setTooltip(juce::String(is_in_trash_mode ? "Hide" : "Show") + " trashed documents"); m_create_document_btn.setEnabled(!is_in_trash_mode); m_trash_btn.setToggleState(is_in_trash_mode, juce::NotificationType::dontSendNotification); }); m_trash_btn.setToggleState(m_drive_view.isShowingTrashedDocuments(), juce::NotificationType::dontSendNotification); m_trash_btn.setSize(40, 40); m_trash_btn.setTooltip("Display trashed documents"); addAndMakeVisible(m_trash_btn); // searchbar m_searchbar.setMultiLine(false); m_searchbar.setFont(18); m_searchbar.setSize(100, m_searchbar.getFont().getHeight() + 10); m_searchbar.setTextToShowWhenEmpty("search...", m_searchbar.findColour(juce::TextEditor::ColourIds::textColourId) .contrasting(0.5)); m_searchbar.addListener(this); // search_btn m_search_btn.setCommand([this]() { showSearchBar(m_search_btn.getToggleState()); }); m_search_btn.setClickingTogglesState(true); m_search_btn.setSize(40, 40); m_search_btn.setTooltip("Search documents"); addAndMakeVisible(m_search_btn); } void DocumentBrowserView::DriveView::Header::enablementChanged() { const bool enabled = isEnabled(); m_create_document_btn.setEnabled(enabled); m_refresh_btn.setEnabled(enabled); m_trash_btn.setEnabled(enabled); } void DocumentBrowserView::DriveView::Header::resized() { auto bounds = getLocalBounds(); if(m_search_btn.getToggleState()) { m_searchbar.setBounds(bounds.removeFromBottom(m_searchbar.getFont().getHeight() + 10)); } m_folder_bounds = bounds.removeFromLeft(50).reduced(10); m_trash_btn.setTopRightPosition(getWidth(), 5); m_refresh_btn.setTopRightPosition(m_trash_btn.getX(), 5); m_search_btn.setTopRightPosition(m_refresh_btn.getX(), 5); m_create_document_btn.setTopRightPosition(m_search_btn.getX(), 5); int remaining_width = std::max(0, m_create_document_btn.getX() - m_folder_bounds.getRight()); m_label.setBounds(bounds.withX(m_folder_bounds.getRight() + 5).withWidth(remaining_width)); } void DocumentBrowserView::DriveView::Header::paint(juce::Graphics& g) { auto& lf = KiwiApp::useLookAndFeel(); const juce::Colour color = lf.getCurrentColourScheme().getUIColour(juce::LookAndFeel_V4::ColourScheme::UIColour::windowBackground); g.fillAll(color); if (isEnabled()) { g.drawImage(m_folder_img, m_folder_bounds.toFloat(), juce::RectanglePlacement::yMid, false); } else { g.drawImage(m_disable_folder_img, m_folder_bounds.toFloat(), juce::RectanglePlacement::yMid, false); } const auto bounds = getLocalBounds(); g.setColour(color.darker(0.3)); g.drawHorizontalLine(bounds.getBottom() - 1, 0, getWidth()); } void DocumentBrowserView::DriveView::Header::mouseDown(juce::MouseEvent const& e) { m_drive_view.getModel()->backgroundClicked(e); } void DocumentBrowserView::DriveView::Header::setText(std::string const& text) { m_label.setText(text, juce::NotificationType::dontSendNotification); repaint(); } void DocumentBrowserView::DriveView::Header::showSearchBar(bool show) { if(show) { addAndMakeVisible(m_searchbar); m_searchbar.grabKeyboardFocus(); setSize(getWidth(), m_toolbar_thickness + m_searchbar.getHeight()); m_drive_view.resized(); } else { m_drive_view.setFilter(""); m_searchbar.clear(); removeChildComponent(&m_searchbar); setSize(getWidth(), m_toolbar_thickness); m_drive_view.resized(); } } void DocumentBrowserView::DriveView::Header::textEditorTextChanged(juce::TextEditor& editor) { if(&editor == &m_searchbar) { const auto newtext = editor.getText().toStdString(); m_drive_view.setFilter(newtext); } } void DocumentBrowserView::DriveView::Header::textEditorEscapeKeyPressed (juce::TextEditor& editor) { if(&editor == &m_searchbar) { m_search_btn.setToggleState(false, juce::NotificationType::sendNotificationSync); } } // ================================================================================ // // BROWSER DRIVE VIEW // // ================================================================================ // DocumentBrowserView::DriveView::DriveView(DocumentBrowser::Drive& drive) : juce::ListBox("document list", this) , m_drive(drive) , m_trash_mode(false) , m_enabled(true) , m_sorter() { m_drive.addListener(*this); setMultipleSelectionEnabled(false); setRowSelectedOnMouseDown(false); setRowHeight(30); auto* header = new Header(*this); header->setSize(getWidth(), 50); setHeaderComponent(header); getViewport()->setScrollBarThickness(10); juce::ListBox::setColour(juce::ListBox::backgroundColourId, juce::Colour(0xFFD4D4D4)); restoreState(); update(); } DocumentBrowserView::DriveView::~DriveView() { saveState(); m_drive.removeListener(*this); } void DocumentBrowserView::DriveView::saveState() { const juce::String sort_str = [](SortBy sort) { switch (sort) { case SortBy::name: return "name"; case SortBy::author: return "author"; case SortBy::openedTime: return "openedTime"; case SortBy::creationTime: default: return "creationTime"; } }(getSortType()); getGlobalProperties().setValue("DocumentBrowser_sort_type", sort_str); } void DocumentBrowserView::DriveView::restoreState() { const SortBy sort = [](juce::String sort_str) { SortBy sort = SortBy::creationTime; if(sort_str == "name") { sort = SortBy::name; } else if(sort_str == "author") { sort = SortBy::author; } else if(sort_str == "openedTime") { sort = SortBy::openedTime; } else if(sort_str == "creationTime") { sort = SortBy::creationTime; } return sort; }(getGlobalProperties().getValue("DocumentBrowser_sort_type")); setSortType(sort); } bool DocumentBrowserView::DriveView::Comp::compare(DocumentBrowser::Drive::DocumentSession const& lhs, DocumentBrowser::Drive::DocumentSession const& rhs) const { bool type_ordered = false; switch(m_type) { case SortBy::name: { type_ordered = juce::String(lhs.getName()).compareNatural(rhs.getName()) < 0; break; } case SortBy::author: { type_ordered = juce::String(lhs.getAuthor()).compareNatural(rhs.getAuthor()) < 0; break; } case SortBy::creationTime: { type_ordered = lhs.getCreationTime() > rhs.getCreationTime(); break; } case SortBy::openedTime: { type_ordered = lhs.getOpenedTime() > rhs.getOpenedTime(); break; } default: break; } bool trash_order = (m_trashed_first && lhs.isTrashed() > rhs.isTrashed()) || (!m_trashed_first && lhs.isTrashed() < rhs.isTrashed()); return trash_order || (lhs.isTrashed() == rhs.isTrashed() && type_ordered); } void DocumentBrowserView::DriveView::enablementChanged() { getHeaderComponent()->setEnabled(isEnabled()); update(); } void DocumentBrowserView::DriveView::driveChanged() { update(); } std::vector<DocumentBrowser::Drive::DocumentSession*> DocumentBrowserView::DriveView::getDisplayedDocuments() { auto& all_documents = m_drive.getDocuments(); std::vector<DocumentBrowser::Drive::DocumentSession*> docs; docs.reserve(all_documents.size()); for(auto& doc_uptr : all_documents) { auto* doc = doc_uptr.get(); if(m_trash_mode ? doc->isTrashed() : !doc->isTrashed()) { docs.emplace_back(doc); } } std::string const& filter = m_sorter.m_filter; if(!filter.empty()) { struct ScoredEntry { ScoredEntry(DocumentBrowser::Drive::DocumentSession* _document, int _score) : document(_document), score(_score) {} bool operator<(ScoredEntry const& entry) const { return (score >= entry.score); } DocumentBrowser::Drive::DocumentSession* document = nullptr; int score = 0; }; std::set<ScoredEntry> scored_entries; for(auto* doc : docs) { const auto r = SuggestList::computeScore(filter.c_str(), doc->getName().c_str()); if(r.first) { scored_entries.insert({doc, r.second}); } } docs.clear(); for(auto const& scored_entry : scored_entries) { docs.emplace_back(scored_entry.document); } } return docs; } DocumentBrowser::Drive::DocumentSession* DocumentBrowserView::DriveView::getDocumentForRow(int row) { auto documents = getDisplayedDocuments(); if(row < documents.size()) { return documents.at(row); } return nullptr; } int DocumentBrowserView::DriveView::getNumRows() { int num_rows = 0; if (isEnabled()) { return getDisplayedDocuments().size(); } return num_rows; } void DocumentBrowserView::DriveView::paintListBoxItem(int rowNumber, juce::Graphics& g, int width, int height, bool selected) { // using custom components instead. } std::string const& DocumentBrowserView::DriveView::getDriveName() const { return m_drive.getName(); } void DocumentBrowserView::DriveView::refresh() { m_drive.refresh(); } void DocumentBrowserView::DriveView::createDocument() { juce::AlertWindow alert("Create a new hosted Patcher", "name:", juce::AlertWindow::AlertIconType::NoIcon); alert.addButton("Cancel", 0); alert.addButton("Ok", 1); alert.addTextEditor("title", "Untitled"); if(alert.runModalLoop()) { auto& text_editor = *alert.getTextEditor("title"); auto text = text_editor.getText(); m_drive.createNewDocument(text.toStdString()); } } void DocumentBrowserView::DriveView::setTrashMode(bool trash_mode) { m_trash_mode = trash_mode; m_sorter.m_trashed_first = m_trash_mode; m_drive.setSort([sorter = m_sorter](DocumentBrowser::Drive::DocumentSession const& l_hs, DocumentBrowser::Drive::DocumentSession const& r_hs) { return sorter.compare(l_hs, r_hs); }); } DocumentBrowserView::DriveView::SortBy DocumentBrowserView::DriveView::getSortType() const { return m_sorter.m_type; } void DocumentBrowserView::DriveView::setSortType(SortBy sort_type) { m_sorter.m_type = sort_type; m_drive.setSort([sorter = m_sorter](DocumentBrowser::Drive::DocumentSession const& lhs, DocumentBrowser::Drive::DocumentSession const& rhs) { return sorter.compare(lhs, rhs); }); } void DocumentBrowserView::DriveView::setFilter(std::string const& text) { m_sorter.m_filter = text; update(); } bool DocumentBrowserView::DriveView::isShowingTrashedDocuments() const { return m_trash_mode; } void DocumentBrowserView::DriveView::update() { dynamic_cast<Header*>(getHeaderComponent())->setText(getDriveName()); updateContent(); repaint(); } std::string DocumentBrowserView::DriveView::createDocumentToolTip(DocumentBrowser::Drive::DocumentSession const& doc) { std::string tooltip = "name: " + doc.getName() + "\n" + "created by: " + doc.getAuthor() + " (" + doc.getCreationDate() + ")\n" + "last opened by: " + doc.getOpenedUser() + " (" + doc.getOpenedDate() + ")"; if (doc.isTrashed()) { tooltip += "\ntrashed at: " + doc.getTrashedDate(); } return tooltip; } juce::Component* DocumentBrowserView::DriveView::refreshComponentForRow(int row, bool selected, juce::Component* c) { auto documents = getDisplayedDocuments(); if(row >= documents.size()) { if(c != nullptr) { delete c; c = nullptr; } } else { const auto& doc = *documents[row]; const auto name = doc.getName(); if(c == nullptr) { c = new RowElem(*this, name, createDocumentToolTip(doc)); } static_cast<RowElem*>(c)->update(name, createDocumentToolTip(doc), row, selected); } return c; } void DocumentBrowserView::DriveView::backgroundClicked(juce::MouseEvent const&) { deselectAllRows(); } void DocumentBrowserView::DriveView::returnKeyPressed(int last_row_selected) { if(getNumSelectedRows() > 0) { auto* c = getComponentForRowNumber(last_row_selected); if(c) { static_cast<RowElem*>(c)->showEditor(); } } } void DocumentBrowserView::DriveView::openDocument(int row) { if(auto* doc = getDocumentForRow(row)) { doc->open(); } } void DocumentBrowserView::DriveView::restoreDocumentForRow(int row) { if(auto* doc = getDocumentForRow(row)) { doc->untrash(); } } void DocumentBrowserView::DriveView::deleteDocumentForRow(int row) { if(auto* doc = getDocumentForRow(row)) { doc->trash(); } } void DocumentBrowserView::DriveView::renameDocumentForRow(int row, std::string const& new_name) { if(auto* doc = getDocumentForRow(row)) { doc->rename(new_name); } } void DocumentBrowserView::DriveView::duplicateDocumentForRow(int row) { if(auto* doc = getDocumentForRow(row)) { doc->duplicate(); } } void DocumentBrowserView::DriveView::uploadDocument() { const auto dir = KiwiApp::getGlobalDirectoryFor(KiwiApp::FileLocations::Upload); juce::FileChooser file_chooser("Upload file", dir, "*.kiwi"); if(file_chooser.browseForFileToOpen()) { juce::File result = file_chooser.getResult(); const auto new_dir = result.getParentDirectory(); if(new_dir.exists()) { KiwiApp::setGlobalDirectoryFor(KiwiApp::FileLocations::Upload, new_dir); } // Test that document is a valid kiwi document. flip::DataProviderFile provider(result.getFullPathName().toStdString().c_str()); flip::BackEndIR back_end; back_end.register_backend<flip::BackEndBinary>(); std::string current_version(KIWI_MODEL_VERSION_STRING); if (back_end.read(provider) && current_version.compare(back_end.version) == 0) { juce::MemoryBlock buffer; result.loadFileAsData(buffer); std::string data((char *) buffer.getData(), buffer.getSize() / sizeof(char)); m_drive.uploadDocument(result.getFileNameWithoutExtension().toStdString(), data); } else { KiwiApp::error("Not a valid Kiwi file"); } } } void DocumentBrowserView::DriveView::downloadDocumentForRow(int row) { auto* document = getDocumentForRow(row); if(document == nullptr) return; // abort const auto dir = KiwiApp::getGlobalDirectoryFor(KiwiApp::FileLocations::Download); const auto kiwi_extension = ".kiwi"; auto document_name = document->getName(); if(! dir.getChildFile(document_name).hasFileExtension(kiwi_extension)) { document_name += kiwi_extension; } const auto suggest_file = dir.getChildFile(document_name); juce::FileChooser saveFileChooser("Download file", suggest_file, "*.kiwi"); if (saveFileChooser.browseForFileToSave(true)) { juce::File result = saveFileChooser.getResult(); const auto new_dir = result.getParentDirectory(); if(new_dir.exists()) { KiwiApp::setGlobalDirectoryFor(KiwiApp::FileLocations::Download, new_dir); } document->download([result](std::string const& content) { if(result.create().wasOk()) { result.replaceWithData(content.data(), content.size() * sizeof(char)); } }); } } void DocumentBrowserView::DriveView::listBoxItemDoubleClicked(int row, juce::MouseEvent const& e) { openDocument(row); } }
33,951
C++
.cpp
814
29.185504
200
0.554337
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,345
KiwiApp_AboutWindow.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Application/KiwiApp_AboutWindow.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 : [email protected] ============================================================================== */ #include "KiwiApp_AboutWindow.h" #include <KiwiModel/KiwiModel_DataModel.h> #include "../KiwiApp.h" #include "../KiwiApp_Resources/KiwiApp_BinaryData.h" namespace kiwi { // ================================================================================ // // ABOUT WINDOW // // ================================================================================ // AboutWindow::AboutWindow() : Window("About Kiwi", std::make_unique<Content>(), false, false, "about_kiwi_window") { setTitleBarButtonsRequired(juce::DocumentWindow::closeButton, true); // force fixed size getContentComponent()->setSize(400, 380); } // ================================================================================ // // LINK LIST // // ================================================================================ // LinkList::LinkList(juce::String header, std::vector<Link> links) : m_header("header", std::move(header)) , m_links(std::move(links)) { addAndMakeVisible(m_header); m_header.setColour(juce::Label::ColourIds::textColourId, juce::Colours::black); for(auto& link: m_links) { addAndMakeVisible(link.link); link.link.setColour(juce::HyperlinkButton::ColourIds::textColourId, juce::Colours::black.withAlpha(0.8f)); addAndMakeVisible(link.description); link.description.setColour(juce::Label::ColourIds::textColourId, juce::Colours::black); } } void LinkList::resized() { auto bounds = getLocalBounds(); m_header.setBounds(bounds.removeFromTop(22)); bounds.reduce(10, 0); for(auto& link: m_links) { const auto link_bounds = bounds.removeFromTop(20); link.link.setBounds(link_bounds); link.link.changeWidthToFitText(); link.description.setBounds(link_bounds.withLeft(link.link.getRight())); } } // ================================================================================ // // ABOUT WINDOW CONTENT // // ================================================================================ // AboutWindow::Content::Content() : m_kiwi_app_image(juce::ImageCache::getFromMemory(binary_data::images::kiwi_icon_png, binary_data::images::kiwi_icon_png_size)) , m_authors_links("Developers:", { {"Eliott Paris", juce::URL("https://github.com/eliottparis")}, {"Pierre Guillot", juce::URL("https://github.com/pierreguillot")}, {"Jean Millot", juce::URL("https://github.com/jean-millot")}, }) , m_credits_links("Credits: ", { {"Juce", juce::URL("https://github.com/WeAreROLI/JUCE"), juce::CharPointer_UTF8("- © Roli")}, {"Flip", juce::URL("http://developer.irisate.com/"), juce::CharPointer_UTF8("- © irisate")}, {"Beast", juce::URL("https://github.com/boostorg/Beast/"), juce::CharPointer_UTF8("- boost")}, {"concurrentqueue", juce::URL("https://github.com/cameron314/concurrentqueue"), juce::CharPointer_UTF8("- Cameron Desrochers")}, {"json", juce::URL("https://github.com/nlohmann/json"), juce::CharPointer_UTF8("- Niels Lohmann")}, {"Faust", juce::URL("https://github.com/grame-cncm/faust"), juce::CharPointer_UTF8("- GRAME")}, {"Icons", juce::URL("https://www.flaticon.com/"), juce::CharPointer_UTF8("- by Freepik")} }) { addAndMakeVisible(m_authors_links); addAndMakeVisible(m_credits_links); setSize(400, 380); } void AboutWindow::Content::resized() { auto bounds = getLocalBounds().reduced(5, 0); bounds.removeFromTop(70); // header bounds.removeFromTop(30); // text m_authors_links.setBounds(bounds.removeFromTop(90)); m_credits_links.setBounds(bounds); } void AboutWindow::Content::paint(juce::Graphics& g) { auto bounds = getLocalBounds(); auto header_bounds = bounds.removeFromTop(70); g.setColour(juce::Colour::fromRGB(88, 88, 90)); g.fillRect(header_bounds); const auto padding = 10; header_bounds.reduce(padding, padding); g.drawImage(m_kiwi_app_image, header_bounds.removeFromRight(header_bounds.getHeight()).toFloat(), juce::RectanglePlacement::centred, false); g.setColour(juce::Colours::lightgrey); g.fillRect(bounds); #if JUCE_DEBUG const auto app_version = KiwiApp::use().getApplicationVersion() + " (debug)"; #else const auto app_version = KiwiApp::use().getApplicationVersion(); #endif const auto model_version = model::DataModel::use().version(); const auto compilation_date = juce::Time::getCompilationDate().toString(true, false); g.setColour(juce::Colours::whitesmoke); const auto header = "App version: " + app_version + '\n' + "model version: " + model_version + '\n' + "Build date: " + compilation_date; g.drawFittedText(header, header_bounds, juce::Justification::centredLeft, 5); g.setColour(juce::Colours::black); g.drawFittedText(juce::CharPointer_UTF8 ("Kiwi © CICM ANR MUSICOLL - 2016-2018.\n\n"), bounds.reduced(padding), juce::Justification::topLeft, 1); } }
6,824
C++
.cpp
125
43.96
137
0.531105
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,346
KiwiApp_ConsoleHistory.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Application/KiwiApp_ConsoleHistory.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 : [email protected] ============================================================================== */ #include "../KiwiApp.h" #include "KiwiApp_ConsoleHistory.h" namespace kiwi { // ================================================================================ // // CONSOLE HISTORY // // ================================================================================ // ConsoleHistory::ConsoleHistory(engine::Instance& instance) : m_instance(instance), m_sort(ConsoleHistory::ByIndex) { m_instance.addConsoleListener(*this); } ConsoleHistory::~ConsoleHistory() { m_instance.removeConsoleListener(*this); m_messages.clear(); } void ConsoleHistory::newConsoleMessage(engine::Console::Message const& message) { if(!message.text.empty()) { bool changed = false; { std::lock_guard<std::mutex> guard(m_message_mutex); if(!m_messages.empty()) { auto& last = m_messages.back(); auto& last_message = last.m_message; if(last_message.text == message.text && last_message.type == message.type) { last.m_repeat_times++; changed = true; } } if(!changed) { m_messages.push_back({message, m_messages.size() + 1}); changed = true; } } if(changed) { m_listeners.call(&Listener::consoleHistoryChanged, *this); } } } void ConsoleHistory::clear() { { std::lock_guard<std::mutex> guard(m_message_mutex); m_messages.clear(); } m_listeners.call(&Listener::consoleHistoryChanged, *this); } size_t ConsoleHistory::size() { return m_messages.size(); } std::pair<engine::Console::Message const*, size_t> ConsoleHistory::get(size_t index) { std::lock_guard<std::mutex> guard(m_message_mutex); if(index < m_messages.size()) { auto const& msg = m_messages[index]; return {&msg.m_message, msg.m_repeat_times}; } return {}; } void ConsoleHistory::erase(size_t index) { if(index < m_messages.size()) { { std::lock_guard<std::mutex> guard(m_message_mutex); m_messages.erase(m_messages.begin() + index); std::sort(m_messages.begin(), m_messages.end(), compareIndex); for(size_t i = 0; i < m_messages.size(); i++) { m_messages[i-1].m_index = i; } this->sort(m_sort); } m_listeners.call(&Listener::consoleHistoryChanged, *this); } } void ConsoleHistory::erase(size_t begin, size_t last) { if(begin < last && last < m_messages.size()) { { std::lock_guard<std::mutex> guard(m_message_mutex); m_messages.erase(m_messages.begin() + begin, m_messages.begin() + last); std::sort(m_messages.begin(), m_messages.end(), compareIndex); for(size_t i = 0; i < m_messages.size(); i++) { m_messages[i].m_index = i+1; } sort(m_sort); } m_listeners.call(&Listener::consoleHistoryChanged, *this); } } void ConsoleHistory::erase(std::vector<size_t>& indices) { size_t max = m_messages.size(); std::sort(indices.begin(), indices.end()); std::reverse(indices.begin(), indices.end()); for(size_t i = 0; i < indices.size(); i++) { if(indices[i] < max) { std::lock_guard<std::mutex> guard(m_message_mutex); m_messages.erase(m_messages.begin() + indices[i]); --max; } } { std::lock_guard<std::mutex> guard(m_message_mutex); std::sort(m_messages.begin(), m_messages.end(), compareIndex); for(size_t i = 0; i < m_messages.size(); i++) { m_messages[i].m_index = i+1; } sort(m_sort); } m_listeners.call(&Listener::consoleHistoryChanged, *this); } bool ConsoleHistory::compareIndex(MessageHolder const& i, MessageHolder const& j) { return i.m_index < j.m_index; } bool ConsoleHistory::compareText(MessageHolder const& i, MessageHolder const& j) { std::string first = i.m_message.text; std::string second = j.m_message.text; return first.compare(second); } bool ConsoleHistory::compareType(MessageHolder const& i, MessageHolder const& j) { engine::Console::Message::Type first = i.m_message.type; engine::Console::Message::Type second = j.m_message.type; return first < second; } void ConsoleHistory::sort(Sort type) { m_sort = type; switch(m_sort) { case ByIndex: { std::sort(m_messages.begin(), m_messages.end(), compareIndex); break; } case ByType: { std::sort(m_messages.begin(), m_messages.end(), compareType); break; } case ByText: { std::sort(m_messages.begin(), m_messages.end(), compareText); break; } } } void ConsoleHistory::addListener(ConsoleHistory::Listener& listener) { m_listeners.add(listener); } void ConsoleHistory::removeListener(ConsoleHistory::Listener& listener) { m_listeners.remove(listener); } }
6,965
C++
.cpp
181
26.950276
90
0.506487
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,347
KiwiApp_SettingsPanel.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Application/KiwiApp_SettingsPanel.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 : [email protected] ============================================================================== */ #include <KiwiApp_Application/KiwiApp_SettingsPanel.h> #include <KiwiApp_General/KiwiApp_IDs.h> #include <KiwiApp.h> #include <KiwiApp_General/KiwiApp_StoredSettings.h> namespace kiwi { // ================================================================================ // // SETTINGS PANEL // // ================================================================================ // SettingsPanel::SettingsPanel(): m_settings(getAppSettings().network().getServerAddress()), m_pannel("Application settings"), m_apply_button("Apply"), m_reset_button("Reset") { juce::Array<juce::PropertyComponent*> props { new juce::TextPropertyComponent(m_settings .getPropertyAsValue(Ids::host, nullptr),"Host", 20,false), new juce::TextPropertyComponent(m_settings .getPropertyAsValue(Ids::api_port, nullptr), "API Port", 5, false), new juce::TextPropertyComponent(m_settings .getPropertyAsValue(Ids::session_port, nullptr), "Session Port", 5, false) }; m_pannel.addSection("Network config", props, true, 0); m_apply_button.addListener(this); m_reset_button.addListener(this); setSize(400, m_pannel.getTotalContentHeight() + 50); addAndMakeVisible(m_pannel); addAndMakeVisible(m_apply_button); addAndMakeVisible(m_reset_button); } SettingsPanel::~SettingsPanel() { m_pannel.clear(); } void SettingsPanel::resized() { juce::Rectangle<int> bounds = getLocalBounds(); m_pannel.setBounds(bounds.withHeight(m_pannel.getTotalContentHeight())); m_apply_button.setBounds(bounds .withPosition(m_pannel.getX() + 10, m_pannel.getBottom() + 10) .withHeight(30)); m_apply_button.changeWidthToFitText(); m_reset_button.setBounds(m_apply_button.getBounds().withLeft(m_apply_button.getRight() + 10)); m_reset_button.changeWidthToFitText(); } void SettingsPanel::buttonClicked(juce::Button* button) { if (button == &m_apply_button) { getAppSettings().network().setServerAddress(m_settings[Ids::host].toString().toStdString(), m_settings[Ids::api_port].operator int(), m_settings[Ids::session_port].operator int()); } else if(button == &m_reset_button) { NetworkSettings & network = getAppSettings().network(); network.resetToDefault(); m_settings.copyPropertiesFrom(network.getServerAddress(), nullptr); } } }
3,960
C++
.cpp
76
39.5
119
0.539253
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,348
KiwiApp_FormComponent.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Components/KiwiApp_FormComponent.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 : [email protected] ============================================================================== */ #include "KiwiApp_FormComponent.h" #include "../KiwiApp.h" #include "../KiwiApp_Resources/KiwiApp_BinaryData.h" namespace kiwi { // ================================================================================ // // ALERT BOX // // ================================================================================ // AlertBox::AlertBox(std::string const& message, AlertBox::Type type, bool can_cancel, std::function<void(void)> on_close) : m_message(message) , m_type(type) , m_close_fn(on_close) { if(can_cancel) { m_close_btn.reset(new juce::TextButton("X", "Close")); m_close_btn->setColour(juce::TextButton::buttonColourId, juce::Colours::transparentBlack); addAndMakeVisible(*m_close_btn); m_close_btn->addListener(this); } } AlertBox::~AlertBox() { if(m_close_btn) { m_close_btn->removeListener(this); } } void AlertBox::paint(juce::Graphics& g) { const auto bgcolor = [](Type const& type) { switch (type) { case Type::Success: return juce::Colour::fromRGB(72, 175, 95); case Type::Error: return juce::Colour::fromRGB(252, 99, 93); default: return juce::Colours::grey; } }(m_type).withAlpha(1.f); g.setColour(bgcolor); g.fillRoundedRectangle(getLocalBounds().reduced(1).toFloat(), 0.f); g.setFont(16.f); g.setColour(bgcolor.contrasting(0.9)); g.drawText(m_message, getLocalBounds().reduced(10), juce::Justification::verticallyCentred); } void AlertBox::resized() { if(m_close_btn) { const int margin = 5; const auto bounds = getLocalBounds(); m_close_btn->setSize(20, 20); m_close_btn->setTopRightPosition(bounds.getWidth() - margin, margin); } } void AlertBox::buttonClicked(juce::Button* b) { if(b == m_close_btn.get()) { if(m_close_fn) { m_close_fn(); } else { // close alert box } } } // ================================================================================ // // SPINNER // // ================================================================================ // struct Spinner : public juce::Component, private juce::Timer { Spinner() { startTimer(1000 / 50); } void timerCallback() override { repaint(); } void paint(juce::Graphics& g) override { getLookAndFeel().drawSpinningWaitAnimation(g, juce::Colours::whitesmoke, 0, 0, getWidth(), getHeight()); } }; // ================================================================================ // // FORM COMPONENT OVERLAY // // ================================================================================ // class FormComponent::OverlayComp : public juce::Component { public: // methods OverlayComp(juce::String message) : m_message(message) , m_show_success(false) { addAndMakeVisible(spinner); } ~OverlayComp() = default; void paint(juce::Graphics& g) override { auto& lf = KiwiApp::useLookAndFeel(); const auto bgcolor = lf.getCurrentColourScheme().getUIColour(juce::LookAndFeel_V4::ColourScheme::UIColour::windowBackground); g.fillAll(bgcolor.withAlpha(0.97f)); g.setColour(juce::Colours::whitesmoke); g.setFont(22.0f); g.drawFittedText(m_message, getLocalBounds().reduced(20, 0) .removeFromTop(proportionOfHeight(0.6f)), juce::Justification::centred, 5); } void resized() override { const int spinnerSize = 40; spinner.setBounds((getWidth() - spinnerSize) / 2, proportionOfHeight(0.5f), spinnerSize, spinnerSize); } void showSuccess(juce::String message) { m_show_success = true; m_message = message; spinner.setVisible(false); repaint(); } private: // variables Spinner spinner; juce::String m_message; bool m_show_success = false; JUCE_LEAK_DETECTOR(LoginForm::OverlayComp); }; static juce::juce_wchar getDefaultPasswordChar() noexcept { #if JUCE_LINUX return 0x2022; #else return 0x25cf; #endif } // ================================================================================ // // FORM COMPONENT FIELD // // ================================================================================ // FormComponent::Field::Field(std::string name) : juce::Component(name) , m_name(name) { ; } std::string const& FormComponent::Field::getName() const { return m_name; } int FormComponent::Field::getPreferedHeight() { return 32; } // ================================================================================ // // SINGLE LINE FIELD // // ================================================================================ // FormComponent::Field::SingleLineText::SingleLineText(std::string name, std::string text, std::string placeholder_text) : Field(name) , m_text_editor() { //(force use of a default system font to make sure it has the password blob character) static juce::Font font(juce::Font::getDefaultTypefaceForFont(juce::Font(juce::Font::getDefaultSansSerifFontName(), juce::Font::getDefaultStyle(), 5.0f))); m_text_editor.setFont(font.withHeight(22)); m_text_editor.setInputRestrictions(512); m_text_editor.setText(text, false); m_text_editor.setEscapeAndReturnKeysConsumed(false); juce::Colour labelCol(findColour(juce::TextEditor::backgroundColourId).contrasting(0.5f)); m_text_editor.setTextToShowWhenEmpty(placeholder_text, labelCol); addAndMakeVisible(m_text_editor); } juce::Value& FormComponent::Field::SingleLineText::getValue() { return m_text_editor.getTextValue(); } void FormComponent::Field::SingleLineText::resized() { m_text_editor.setBounds(getLocalBounds()); } // ================================================================================ // // PASWWORD FIELD // // ================================================================================ // FormComponent::Field::Password::Password(std::string name, std::string text, std::string placeholder_text) : SingleLineText(name, text, placeholder_text) { m_text_editor.setPasswordCharacter(getDefaultPasswordChar()); m_text_editor.setInputRestrictions(64); } // ================================================================================ // // TOGGLE BUTTON FIELD // // ================================================================================ // FormComponent::Field::ToggleButton::ToggleButton(std::string name, std::string text, bool _default) : Field(name) , m_button(text) { m_button.setToggleState(_default, juce::NotificationType::dontSendNotification); addAndMakeVisible(m_button); } juce::Value& FormComponent::Field::ToggleButton::getValue() { return m_button.getToggleStateValue(); } void FormComponent::Field::ToggleButton::resized() { m_button.setBounds(getLocalBounds()); } int FormComponent::Field::ToggleButton::getPreferedHeight() { return 20; } // ================================================================================ // // FIELD TEXT BUTTON // // ================================================================================ // FormComponent::Field::TextButton::TextButton(std::string const& name, std::string const& button_text, std::function<void()> call_back): Field(name), m_button(button_text), m_value(), m_call_back(call_back) { m_button.addListener(this); addAndMakeVisible(m_button); } FormComponent::Field::TextButton::~TextButton() { m_button.removeListener(this); } void FormComponent::Field::TextButton::resized() { m_button.changeWidthToFitText(getHeight()); } juce::Value& FormComponent::Field::TextButton::getValue() { return m_value; } int FormComponent::Field::TextButton::getPreferedHeight() { return 30; } void FormComponent::Field::TextButton::buttonClicked(juce::Button *) { m_call_back(); } // ================================================================================ // // KIWI LOGO FIELD // // ================================================================================ // FormComponent::Field::KiwiLogo::KiwiLogo() : Field("KiwiLogo") , m_kiwi_app_image(juce::ImageCache::getFromMemory(binary_data::images::kiwi_icon_png, binary_data::images::kiwi_icon_png_size)) { ; } void FormComponent::Field::KiwiLogo::paint(juce::Graphics& g) { int padding = 0; auto bounds = getLocalBounds(); g.drawImage(m_kiwi_app_image, bounds.reduced(padding).toFloat(), juce::RectanglePlacement::xMid, false); } juce::Value& FormComponent::Field::KiwiLogo::getValue() { return m_useless_value; } int FormComponent::Field::KiwiLogo::getPreferedHeight() { return 100; } // ================================================================================ // // FORM COMPONENT // // ================================================================================ // FormComponent::FormComponent(std::string const& submit_button_text, std::string const& overlay_text) : m_overlay_text(overlay_text) , m_submit_btn(submit_button_text) , m_cancel_btn(TRANS("Cancel")) , m_alert_height(50) { addAndMakeVisible(m_submit_btn); addAndMakeVisible(m_cancel_btn); m_submit_btn.addShortcut(juce::KeyPress(juce::KeyPress::returnKey)); m_submit_btn.addListener(this); m_cancel_btn.addListener(this); } FormComponent::~FormComponent() { m_overlay.deleteAndZero(); } void FormComponent::paint(juce::Graphics& g) { auto& lf = KiwiApp::useLookAndFeel(); const auto bgcolor = lf.getCurrentColourScheme().getUIColour(juce::LookAndFeel_V4::ColourScheme::UIColour::windowBackground); g.fillAll(bgcolor); auto bounds = getLocalBounds(); bounds.removeFromTop((m_alert_box != nullptr) ? m_alert_box->getHeight() : 0); g.setColour(bgcolor.contrasting(0.05)); g.fillRect(getButtonArea()); } void FormComponent::resized() { const auto bounds(getLocalBounds()); auto r(bounds); if(m_alert_box) { m_alert_box->setBounds(r.removeFromTop(m_alert_height)); } r.reduce(10, 10); for(auto& field : m_fields) { field->setBounds(r.removeFromTop(field->getPreferedHeight())); r.removeFromTop(20); } const int button_height = 30; m_submit_btn.changeWidthToFitText(button_height); m_cancel_btn.changeWidthToFitText(button_height); const int gap = 15; const int sep = 5; auto buttonArea = getButtonArea().reduced(gap); auto submit_bounds = buttonArea.removeFromLeft(buttonArea.getWidth()*0.5); m_submit_btn.setTopRightPosition(submit_bounds.getRight() - sep, submit_bounds.getY()); m_cancel_btn.setTopLeftPosition(buttonArea.getX() + sep, buttonArea.getY()); if(m_overlay != nullptr) { m_overlay->setBounds(bounds); } } juce::Rectangle<int> FormComponent::getButtonArea() const { const int button_height = 30; return {getLocalBounds().removeFromBottom(button_height*2)}; } void FormComponent::showOverlay() { if(m_overlay == nullptr) { addAndMakeVisible(m_overlay = new OverlayComp(m_overlay_text)); resized(); } } void FormComponent::showSuccessOverlay(juce::String const& message) { showOverlay(); m_overlay->showSuccess(message); } void FormComponent::hideOverlay() { if(m_overlay) { removeChildComponent(m_overlay); m_overlay.deleteAndZero(); } } void FormComponent::setSubmitText(std::string const& submit_text) { m_submit_btn.setButtonText(submit_text); repaint(); } bool FormComponent::hasOverlay() { return (m_overlay != nullptr); } void FormComponent::showAlert(std::string const& message, AlertBox::Type type) { const bool was_showing = (m_alert_box != nullptr); if(was_showing) { removeChildComponent(m_alert_box.get()); } m_alert_box.reset(new AlertBox(message, type, true, [this](){ removeChildComponent(m_alert_box.get()); m_alert_box.reset(); setBounds(getBounds().withHeight(getHeight() - m_alert_height)); })); addAndMakeVisible(*m_alert_box); if(!was_showing) { setBounds(getBounds().withHeight(getHeight() + m_alert_height)); } else { resized(); } } void FormComponent::buttonClicked(juce::Button* b) { if(b == &m_submit_btn) { if(!hasOverlay()) { onUserSubmit(); } } else if(b == &m_cancel_btn) { onUserCancelled(); } } void FormComponent::onUserCancelled() { dismiss(); } void FormComponent::dismiss() { if(Window* parent_window = findParentComponentOfClass<Window>()) { parent_window->close(); } } void FormComponent::clearFields() { for(auto field = m_fields.begin(); field != m_fields.end();) { removeChildComponent((*field).get()); field = m_fields.erase(field); } repaint(); } void FormComponent::removeField(std::string const& name) { for(auto field = m_fields.begin(); field != m_fields.end();) { if ((*field)->getName() == name) { removeChildComponent((*field).get()); field = m_fields.erase(field); } else { ++field; } } repaint(); } juce::Value FormComponent::getFieldValue(std::string const& name) { for(auto& field : m_fields) { if(field->getName() == name) { return field->getValue(); } } return {}; } int FormComponent::getFieldsHeight() { int total = 0; for(auto& field : m_fields) { total += field->getPreferedHeight(); } return total; } int FormComponent::getBestHeight() { // TODO: add margin concept in Field to replace this messy hard typed height computation... int best_height = 0; best_height += (m_alert_box != nullptr) ? m_alert_box->getHeight() : 0; best_height += 10; best_height += getFieldsHeight(); // field margin bottom best_height += (m_fields.size() * 20); best_height += 10; best_height += getButtonArea().getHeight(); best_height += 20; return best_height; } }
18,850
C++
.cpp
489
28.059305
137
0.482367
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,349
KiwiApp_ImageButton.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Components/KiwiApp_ImageButton.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 : [email protected] ============================================================================== */ #include "KiwiApp_ImageButton.h" namespace kiwi { // ================================================================================ // // IMAGE BUTTON // // ================================================================================ // ImageButton::ImageButton(juce::String const& name, std::unique_ptr<juce::Drawable> drawable, ButtonStyle style) : juce::Button(name), m_style(style), m_current_image(nullptr), m_edge_indent(3) { setImages(drawable.get()); const auto transparent = juce::Colours::transparentWhite; setColour(ImageButton::ColourIds::backgroundColourId, transparent); setColour(ImageButton::ColourIds::backgroundOnColourId, transparent); setColour(ImageButton::ColourIds::textColourId, juce::Colours::whitesmoke); } ImageButton::~ImageButton() { } //============================================================================== static std::unique_ptr<juce::Drawable> copyDrawableIfNotNull(juce::Drawable const* const d) { return d != nullptr ? std::unique_ptr<juce::Drawable>(d->createCopy()) : nullptr; } void ImageButton::setImages(juce::Drawable const* normal, juce::Drawable const* over, juce::Drawable const* down, juce::Drawable const* disabled, juce::Drawable const* normalOn, juce::Drawable const* overOn, juce::Drawable const* downOn, juce::Drawable const* disabledOn) { jassert(normal != nullptr); // you really need to give it at least a normal image.. m_normal_image = copyDrawableIfNotNull(normal); m_over_image = copyDrawableIfNotNull(over); m_down_image = copyDrawableIfNotNull(down); m_disabled_image = copyDrawableIfNotNull(disabled); m_normal_image_on = copyDrawableIfNotNull(normalOn); m_over_image_on = copyDrawableIfNotNull(overOn); m_down_image_on = copyDrawableIfNotNull(downOn); m_disabled_image_on = copyDrawableIfNotNull(disabledOn); m_current_image = nullptr; buttonStateChanged(); } void ImageButton::setCommand(std::function<void(void)> fn) { m_command = fn; } void ImageButton::clicked(juce::ModifierKeys const& modifiers) { if(m_command) { m_command(); } } //============================================================================== ImageButton::ButtonStyle ImageButton::getStyle() const noexcept { return m_style; } void ImageButton::setButtonStyle(const ImageButton::ButtonStyle new_style) { if(m_style != new_style) { m_style = new_style; buttonStateChanged(); } } void ImageButton::setEdgeIndent(const int num_pixels_indent) { m_edge_indent = num_pixels_indent; repaint(); resized(); } juce::Rectangle<float> ImageButton::getImageBounds() const { juce::Rectangle<int> r(getLocalBounds()); if(m_style != ButtonStyle::ImageStretched) { int indentX = juce::jmin(m_edge_indent, proportionOfWidth(0.3f)); int indentY = juce::jmin(m_edge_indent, proportionOfHeight(0.3f)); if(m_style == ButtonStyle::ImageOnButtonBackground) { indentX = juce::jmax(getWidth() / 4, indentX); indentY = juce::jmax(getHeight() / 4, indentY); } else if(m_style == ButtonStyle::ImageAboveTextLabel) { r = r.withTrimmedBottom(juce::jmin(16, proportionOfHeight(0.25f))); } r = r.reduced(indentX, indentY); } return r.toFloat(); } void ImageButton::resized() { Button::resized(); } void ImageButton::buttonStateChanged() { repaint(); } void ImageButton::enablementChanged() { Button::enablementChanged(); buttonStateChanged(); } void ImageButton::colourChanged() { repaint(); } void ImageButton::paintButton(juce::Graphics& g, const bool mouse_is_over, const bool mouse_is_down) { juce::LookAndFeel& lf = getLookAndFeel(); float btn_opacity = isOver() ? 1.f : 0.9f; juce::Drawable* image = nullptr; if(isEnabled()) { image = getCurrentImage(); } else { image = getToggleState() ? m_disabled_image_on.get() : m_disabled_image.get(); if(image == nullptr) { btn_opacity = 0.4f; image = getNormalImage(); } } if(m_style == ButtonStyle::ImageRaw) { image->drawAt(g, 0.f, 0.f, btn_opacity); } else { const auto bounds = getImageBounds(); image->drawWithin(g, isDown() ? bounds.reduced(1.) : getImageBounds(), m_style == ButtonStyle::ImageStretched ? juce::RectanglePlacement::stretchToFit : juce::RectanglePlacement::centred, btn_opacity); } if(m_style == ButtonStyle::ImageOnButtonBackground) lf.drawButtonBackground(g, *this, findColour(getToggleState() ? juce::TextButton::buttonOnColourId : juce::TextButton::buttonColourId), mouse_is_over, mouse_is_down); else { const bool toggleState = getToggleState(); g.fillAll(findColour(toggleState ? ImageButton::ColourIds::backgroundOnColourId : ImageButton::ColourIds::backgroundColourId)); const int textH = (getStyle() == ButtonStyle::ImageAboveTextLabel) ? juce::jmin(16, proportionOfHeight(0.25f)) : 0; if(textH > 0) { g.setFont((float) textH); g.setColour(findColour(toggleState ? ImageButton::ColourIds::textColourOnId : ImageButton::ColourIds::textColourId) .withMultipliedAlpha(isEnabled() ? 1.0f : 0.4f)); g.drawFittedText(getButtonText(), 2, getHeight() - textH - 1, getWidth() - 4, textH, juce::Justification::centred, 1); } } } //============================================================================== juce::Drawable* ImageButton::getCurrentImage() const noexcept { return isDown() ? getDownImage() : isOver() ? getOverImage() : getNormalImage(); } juce::Drawable* ImageButton::getNormalImage() const noexcept { return(getToggleState() && m_normal_image_on != nullptr) ? m_normal_image_on.get() : m_normal_image.get(); } juce::Drawable* ImageButton::getOverImage() const noexcept { if(getToggleState()) { if(m_over_image_on != nullptr) return m_over_image_on.get(); if(m_normal_image_on != nullptr) return m_normal_image_on.get(); } return m_over_image != nullptr ? m_over_image.get() : m_normal_image.get(); } juce::Drawable* ImageButton::getDownImage() const noexcept { if(juce::Drawable* const d = getToggleState() ? m_down_image_on.get() : m_down_image.get()) return d; return getOverImage(); } }
9,250
C++
.cpp
207
31.570048
161
0.514474
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,350
KiwiApp_SuggestEditor.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Components/KiwiApp_SuggestEditor.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 : [email protected] ============================================================================== */ #include <KiwiApp_Components/KiwiApp_SuggestEditor.h> #include <KiwiApp.h> namespace kiwi { // ================================================================================ // // SUGGEST EDITOR MENU // // ================================================================================ // SuggestEditor::Menu::Menu(SuggestList& list, SuggestEditor & creator) : m_suggest_list(list), m_suggest_list_box(), m_creator(creator), m_constrainer(), m_resizable_corner(this, &m_constrainer), m_validated_action(), m_selected_action() { setAlwaysOnTop(true); setOpaque(true); setSize(200, 150); m_suggest_list_box.setModel(this); m_suggest_list_box.setSize(getWidth(), getHeight()); m_suggest_list_box.setRowHeight(18); m_suggest_list_box.setMultipleSelectionEnabled(false); m_suggest_list_box.setColour(juce::ListBox::ColourIds::backgroundColourId, juce::Colours::transparentBlack); setWantsKeyboardFocus(false); setMouseClickGrabsKeyboardFocus(false); m_suggest_list_box.setMouseClickGrabsKeyboardFocus(false); m_suggest_list_box.setWantsKeyboardFocus(false); addAndMakeVisible(m_suggest_list_box); m_constrainer.setMinimumSize(200, 150); m_resizable_corner.setAlwaysOnTop(true); addAndMakeVisible(m_resizable_corner); const juce::String popup_size(getGlobalProperties().getValue("suggest_popup_size")); if(!popup_size.isEmpty()) { juce::StringArray tokens; tokens.addTokens(popup_size, false); tokens.removeEmptyStrings(); tokens.trim(); if(tokens.size() == 2) { setSize(tokens[0].getIntValue(), tokens[1].getIntValue()); } } } SuggestEditor::Menu::~Menu() { const juce::Point<int> size(getWidth(), getHeight()); getGlobalProperties().setValue("suggest_popup_size", size.toString()); } void SuggestEditor::Menu::paint(juce::Graphics & g) { g.fillAll(juce::Colours::white); } void SuggestEditor::Menu::resized() { m_suggest_list_box.setBounds(getLocalBounds()); const int resizer_size = 18; m_resizable_corner.setBounds(getWidth() - resizer_size, getHeight() - resizer_size, resizer_size, resizer_size); } void SuggestEditor::Menu::selectRow(int row) { m_suggest_list_box.selectRow(row); } void SuggestEditor::Menu::selectFirstRow() { m_suggest_list_box.selectRow(0); } void SuggestEditor::Menu::unselectRow() { m_suggest_list_box.selectRow(-1); } void SuggestEditor::Menu::selectPreviousRow() { const auto rows = getNumRows(); const auto row_sel = m_suggest_list_box.getSelectedRow(); const auto new_row_sel = (row_sel == -1) ? rows - 1 : ((row_sel <= 0) ? - 1 : row_sel - 1); m_suggest_list_box.selectRow(new_row_sel); } void SuggestEditor::Menu::selectNextRow() { const auto rows = getNumRows(); const auto row_sel = m_suggest_list_box.getSelectedRow(); const auto new_row_sel = (row_sel == -1) ? 0 : ((row_sel >= rows) ? -1 : row_sel + 1); m_suggest_list_box.selectRow(new_row_sel); } void SuggestEditor::Menu::update() { m_suggest_list_box.updateContent(); } void SuggestEditor::Menu::setItemValidatedAction(action_method_t function) { m_validated_action = function; } void SuggestEditor::Menu::setSelectedItemAction(action_method_t function) { m_selected_action = function; } void SuggestEditor::Menu::setUnselectedItemAction(std::function<void(void)> function) { m_unselected_action = function; } int SuggestEditor::Menu::getSelectedRow() const { return m_suggest_list_box.getSelectedRow(); } bool SuggestEditor::Menu::canModalEventBeSentToComponent(juce::Component const* target_component) { return target_component == &m_creator; } void SuggestEditor::Menu::inputAttemptWhenModal() { if (juce::Desktop::getInstance().getMainMouseSource().getComponentUnderMouse() != &m_creator) { exitModalState(0); m_creator.closeMenu(); } else { m_creator.setCaretVisible(true); } } // ================================================================================ // // SUGGEST LISTBOX MODEL // // ================================================================================ // int SuggestEditor::Menu::getNumRows() { return m_suggest_list.size(); } void SuggestEditor::Menu::paintListBoxItem(int row_number, juce::Graphics& g, int width, int height, bool selected) { const bool is_odd = (row_number % 2) == 0; g.fillAll(selected ? juce::Colours::lightgrey : juce::Colours::white.darker(is_odd ? 0 : 0.05)); if(row_number < m_suggest_list.size()) { g.setFont(12); std::string const& str = *(m_suggest_list.begin() + row_number); g.drawSingleLineText(str, 10, height - g.getCurrentFont().getHeight()*0.5, juce::Justification::left); } } void SuggestEditor::Menu::listBoxItemClicked(int row, juce::MouseEvent const& e) { if(m_selected_action && (row < m_suggest_list.size())) { std::string const& str = *(m_suggest_list.begin() + row); m_selected_action(str); } } void SuggestEditor::Menu::validateSelectedRow() { int selected_row = m_suggest_list_box.getSelectedRow(); if (selected_row != -1 && m_validated_action) { std::string const& str = *(m_suggest_list.begin() + selected_row); m_validated_action(str); } } void SuggestEditor::Menu::listBoxItemDoubleClicked(int row, juce::MouseEvent const& e) { if (row < m_suggest_list.size()) { selectRow(row); validateSelectedRow(); } } void SuggestEditor::Menu::selectedRowsChanged(int last_row_selected) { if (last_row_selected == -1 && m_unselected_action) { m_unselected_action(); } else if((last_row_selected < m_suggest_list.size()) && m_selected_action) { std::string const& suggestion = *(m_suggest_list.begin() + last_row_selected);; m_selected_action(suggestion); } } // ================================================================================ // // SUGGEST EDITOR // // ================================================================================ // SuggestEditor::SuggestEditor(SuggestList::entries_t entries) : m_suggest_list(std::move(entries)), m_split_text(), m_menu(), m_update_enabled(true) { setReturnKeyStartsNewLine(false); setTabKeyUsedAsCharacter(false); setPopupMenuEnabled(false); juce::TextEditor::addListener(this); } SuggestEditor::~SuggestEditor() { closeMenu(); } void SuggestEditor::showMenu() { m_menu.reset(new Menu(m_suggest_list, *this)); using namespace std::placeholders; // for _1, _2 etc. m_menu->setSelectedItemAction(std::bind(&SuggestEditor::menuItemSelected, this, _1)); m_menu->setItemValidatedAction(std::bind(&SuggestEditor::menuItemValidated, this, _1)); m_menu->setUnselectedItemAction(std::bind(&SuggestEditor::menuItemUnselected, this)); m_menu->addToDesktop(juce::ComponentPeer::windowIsTemporary | juce::ComponentPeer::windowHasDropShadow | juce::ComponentPeer::windowIgnoresKeyPresses); m_menu->enterModalState(false); const auto sb = getScreenBounds(); m_menu->setTopLeftPosition(sb.getX() - 2, sb.getBottom() + 2); m_menu->setVisible(true); } bool SuggestEditor::isMenuOpened() const noexcept { return static_cast<bool>(m_menu); } void SuggestEditor::closeMenu() { if(isMenuOpened()) { m_menu.reset(); } } void SuggestEditor::disableUpdate() { m_update_enabled = false; } void SuggestEditor::enableUpdate() { m_update_enabled = true; } void SuggestEditor::textEditorFocusLost(juce::TextEditor & editor) { if(isMenuOpened()) { m_menu->exitModalState(0); closeMenu(); } } void SuggestEditor::textEditorTextChanged(juce::TextEditor&) { if (m_update_enabled) { setCaretVisible(true); m_split_text.clear(); m_split_text.addTokens(getText(), " "); if (m_split_text.size() == 1) { m_suggest_list.applyFilter(m_split_text[0].toStdString()); if(isMenuOpened() && m_suggest_list.empty()) { closeMenu(); } else if(!m_suggest_list.empty()) { if(isMenuOpened()) { if (m_menu->getSelectedRow() != -1) { m_menu->unselectRow(); } m_menu->update(); } else { showMenu(); } } } else if (isMenuOpened()) { closeMenu(); } } } void SuggestEditor::menuItemSelected(juce::String const& text) { juce::String editor_text = getText(); int last_word_pos = editor_text.lastIndexOf(" ") + 1; juce::String replace_text = editor_text.replaceSection(last_word_pos, editor_text.length() - last_word_pos, text); disableUpdate(); setText(replace_text); int highlight_start = std::min(last_word_pos + m_split_text[m_split_text.size() - 1].length(), replace_text.length()); int highlight_end = replace_text.length(); setHighlightedRegion({highlight_start, highlight_end}); setCaretVisible(false); } void SuggestEditor::menuItemUnselected() { juce::String editor_text = getText(); juce::String replace_text = editor_text.replaceSection(editor_text.lastIndexOf(" ") + 1, editor_text.length() - editor_text.lastIndexOf(" ") - 1, m_split_text[m_split_text.size() - 1]); disableUpdate(); setText(replace_text); } void SuggestEditor::menuItemValidated(juce::String const& text) { juce::String editor_text = getText(); juce::String replace_text = editor_text.replaceSection(editor_text.lastIndexOf(" ") + 1, editor_text.length() - editor_text.lastIndexOf(" ") - 1, text); setText(replace_text); closeMenu(); moveCaretToEnd(); setCaretVisible(true); } bool SuggestEditor::keyStateChanged(bool isKeyDown) { enableUpdate(); return TextEditor::keyStateChanged(isKeyDown); } bool SuggestEditor::keyPressed(juce::KeyPress const& key) { setCaretVisible(true); bool result = false; if(key == juce::KeyPress::downKey && isMenuOpened()) { m_menu->selectNextRow(); result = true; } else if(key == juce::KeyPress::upKey && isMenuOpened()) { m_menu->selectPreviousRow(); result = true; } else if(key == juce::KeyPress::escapeKey) { if (isMenuOpened()) { if (m_menu->getSelectedRow() != -1) { m_menu->unselectRow(); } closeMenu(); } else { m_split_text.clear(); m_split_text.addTokens(getText(), " "); if (m_split_text.size() <= 1) { m_suggest_list.applyFilter(m_split_text[0].toStdString()); if (m_suggest_list.size() > 0) { showMenu(); } } } result = true; } if(!result) { result = juce::TextEditor::keyPressed(key); } return result; } }
15,298
C++
.cpp
377
27.411141
120
0.504645
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,351
KiwiApp_CustomToolbarButton.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Components/KiwiApp_CustomToolbarButton.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 : [email protected] ============================================================================== */ #include "KiwiApp_CustomToolbarButton.h" namespace kiwi { CustomToolbarButton::CustomToolbarButton(const int iid, const juce::String& buttonText, const juce::Colour bgcolor, juce::Drawable* const normalIm, juce::Drawable* const toggledOnIm) : ToolbarItemComponent(iid, buttonText, true), normalImage(normalIm), toggledOnImage(toggledOnIm), currentImage(nullptr), m_bgcolor(bgcolor) { jassert(normalImage != nullptr); } CustomToolbarButton::~CustomToolbarButton() { } //============================================================================== bool CustomToolbarButton::getToolbarItemSizes(int toolbarDepth, bool /*isToolbarVertical*/, int& preferredSize, int& minSize, int& maxSize) { preferredSize = minSize = maxSize = toolbarDepth; return true; } void CustomToolbarButton::paintButtonArea(juce::Graphics& g, int width, int height, bool mouse_over, bool mouse_down) { const auto bounds = g.getClipBounds().reduced(1.).toFloat(); const bool over_or_down = (mouse_over || mouse_down); g.setColour(m_bgcolor.contrasting(over_or_down ? 0.f : 0.1f).withAlpha(isEnabled() ? 1.0f : 0.8f)); g.fillEllipse(bounds.reduced(mouse_down ? 1. : 0.)); } void CustomToolbarButton::contentAreaChanged(const juce::Rectangle<int>&) { buttonStateChanged(); } void CustomToolbarButton::setCurrentImage(juce::Drawable* const newImage) { if(newImage != currentImage) { removeChildComponent(currentImage); currentImage = newImage; if(currentImage != nullptr) { enablementChanged(); addAndMakeVisible(currentImage); updateDrawable(); } } } void CustomToolbarButton::updateDrawable() { if(currentImage != nullptr) { currentImage->setInterceptsMouseClicks(false, false); currentImage->setTransformToFit(getContentArea().reduced(6).toFloat(), juce::RectanglePlacement::centred); currentImage->setAlpha(isEnabled() ? 1.0f : 0.5f); } } void CustomToolbarButton::resized() { ToolbarItemComponent::resized(); updateDrawable(); } void CustomToolbarButton::enablementChanged() { ToolbarItemComponent::enablementChanged(); updateDrawable(); } juce::Drawable* CustomToolbarButton::getImageToUse() const { if(getStyle() == juce::Toolbar::textOnly) return nullptr; if(getToggleState() && toggledOnImage != nullptr) return toggledOnImage; return normalImage; } void CustomToolbarButton::buttonStateChanged() { setCurrentImage(getImageToUse()); } }
4,221
C++
.cpp
99
30.828283
144
0.553266
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,352
KiwiApp_Window.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Components/KiwiApp_Window.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 : [email protected] ============================================================================== */ #include <juce_gui_basics/juce_gui_basics.h> #include "../KiwiApp.h" #include "KiwiApp_Window.h" #include "../KiwiApp_General/KiwiApp_CommandIDs.h" namespace kiwi { // ================================================================================ // // WINDOW // // ================================================================================ // Window::Window(std::string const& name, std::unique_ptr<juce::Component> content, bool resizable, bool is_main_window, juce::String settings_name, bool add_menubar) : DocumentWindow(name, KiwiApp::useLookAndFeel().getCurrentColourScheme() .getUIColour(juce::LookAndFeel_V4::ColourScheme::windowBackground), allButtons, true), m_settings_name(settings_name), m_is_main_window(is_main_window) { setUsingNativeTitleBar(true); if(!resizable) { setTitleBarButtonsRequired(juce::DocumentWindow::minimiseButton | juce::DocumentWindow::closeButton, true); } if(content) { int width = content->getWidth() > 0 ? content->getWidth() : 300; int height = content->getHeight() > 0 ? content->getHeight() : 300; content->setSize(width, height); setContentOwned(content.release(), true); } KiwiApp::bindToCommandManager(this); KiwiApp::bindToKeyMapping(this); if(add_menubar) { setMenuBar(KiwiApp::getMenuBarModel()); } setResizable(resizable, false); restoreWindowState(); } Window::~Window() { saveWindowState(); } void Window::restoreWindowState() { if(m_settings_name.isNotEmpty()) { juce::String window_state(getGlobalProperties().getValue(m_settings_name)); if(window_state.isNotEmpty()) { auto last_bounds = getBounds(); restoreWindowStateFromString(window_state); if(!isResizable()) { setSize(last_bounds.getWidth(), last_bounds.getHeight()); } } } // fix: https://forum.juce.com/t/native-titlebar-window-position/8239/3 getConstrainer()->checkComponentBounds(this); } void Window::saveWindowState() { if(m_settings_name.isNotEmpty()) { getGlobalProperties().setValue(m_settings_name, getWindowStateAsString()); } } bool Window::isMainWindow() const { return m_is_main_window; } void Window::close() { KiwiApp::use().closeWindow(*this); } void Window::closeButtonPressed() { close(); } // ================================================================================ // // APPLICATION COMMAND TARGET // // ================================================================================ // juce::ApplicationCommandTarget* Window::getNextCommandTarget() { return findFirstTargetParentComponent(); } void Window::getAllCommands(juce::Array<juce::CommandID>& commands) { commands.add(CommandIDs::closeWindow); commands.add(CommandIDs::minimizeWindow); commands.add(CommandIDs::maximizeWindow); } void Window::getCommandInfo(const juce::CommandID commandID, juce::ApplicationCommandInfo& result) { switch (commandID) { case CommandIDs::closeWindow: { result.setInfo(TRANS("Close"), TRANS("Close Window"), CommandCategories::windows, 0); result.addDefaultKeypress('w', juce::ModifierKeys::commandModifier); result.setActive(getDesktopWindowStyleFlags() & allButtons || getDesktopWindowStyleFlags() & closeButton); break; } case CommandIDs::minimizeWindow: result.setInfo(TRANS("Minimize"), TRANS("Minimize Window"), CommandCategories::windows, 0); result.setActive(getDesktopWindowStyleFlags() & allButtons || getDesktopWindowStyleFlags() & minimiseButton); break; case CommandIDs::maximizeWindow: result.setInfo(TRANS("Maximize"), TRANS("Maximize Window"), CommandCategories::windows, 0); result.setActive(getDesktopWindowStyleFlags() & allButtons || getDesktopWindowStyleFlags() & maximiseButton); break; default: break; } } bool Window::perform(const InvocationInfo& info) { switch (info.commandID) { case CommandIDs::minimizeWindow: minimiseButtonPressed(); break; case CommandIDs::maximizeWindow: maximiseButtonPressed(); break; case CommandIDs::closeWindow: closeButtonPressed(); break; default: return false; } return true; } }
6,391
C++
.cpp
145
32.427586
126
0.530126
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,353
KiwiApp_TooltipWindow.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Components/KiwiApp_TooltipWindow.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 : [email protected] ============================================================================== */ #include "KiwiApp_TooltipWindow.h" #include "../KiwiApp_General/KiwiApp_LookAndFeel.h" namespace kiwi { // ================================================================================ // // CUSTOM TOOLTIP CLIENT // // ================================================================================ // bool CustomTooltipClient::drawTooltip(juce::Graphics& g, juce::String const& text, int width, int height) { return false; } // ================================================================================ // // CUSTOM TOOLTIP WINDOW // // ================================================================================ // TooltipWindow::TooltipWindow(Component* const parent_comp, const int delay_ms) : Component("tooltip") , m_milliseconds_before_tip_appears(delay_ms) , m_mouse_clicks(0), m_mouse_wheel_moves(0) , m_last_comp_change_time(0), m_last_hide_time(0) , m_reentrant(false) { if(juce::Desktop::getInstance().getMainMouseSource().canHover()) { startTimer(123); } setAlwaysOnTop(true); setOpaque(false); if(parent_comp != nullptr) { parent_comp->addChildComponent(this); } } TooltipWindow::~TooltipWindow() { hideTip(); } void TooltipWindow::setMillisecondsBeforeTipAppears(const int new_delay_ms) noexcept { m_milliseconds_before_tip_appears = new_delay_ms; } void TooltipWindow::paint(juce::Graphics& g) { if(!m_custom_client || (m_custom_client && !m_custom_client->drawTooltip(g, m_tip_showing, getWidth(), getHeight()))) { getLookAndFeel().drawTooltip(g, m_tip_showing, getWidth(), getHeight()); } } void TooltipWindow::mouseEnter(juce::MouseEvent const&) { hideTip(); } void TooltipWindow::updatePosition(juce::String const& tip, juce::Point<int> pos, juce::Rectangle<int> parentArea) { const juce::TextLayout tl(LookAndFeel::layoutTooltipText(tip)); const int w = (int)(tl.getWidth() + 14.0f); const int h = (int)(tl.getHeight() + 6.0f); if(m_custom_client != nullptr) { setBounds(m_custom_client->getTooltipBounds(tip, pos, parentArea, w, h)); } else { setBounds(juce::Rectangle<int>(pos.x > parentArea.getCentreX() ? pos.x - (w + 12) : pos.x + 24, pos.y > parentArea.getCentreY() ? pos.y - (h + 6) : pos.y + 6, w, h).constrainedWithin(parentArea)); } setVisible(true); } void TooltipWindow::displayTip(juce::Point<int> screenPos, const juce::String& tip) { jassert(tip.isNotEmpty()); if(! m_reentrant) { juce::ScopedValueSetter<bool> setter(m_reentrant, true, false); if(m_tip_showing != tip) { m_tip_showing = tip; repaint(); } if(auto* parent = getParentComponent()) { updatePosition(tip, parent->getLocalPoint(nullptr, screenPos), parent->getLocalBounds()); } else { updatePosition(tip, screenPos, juce::Desktop::getInstance().getDisplays() .getDisplayContaining(screenPos).userArea); addToDesktop( juce::ComponentPeer::windowHasDropShadow | juce::ComponentPeer::windowIsTemporary | juce::ComponentPeer::windowIgnoresKeyPresses | juce::ComponentPeer::windowIgnoresMouseClicks); } toFront(false); } } void TooltipWindow::setCustomTooltipClient(CustomTooltipClient& client) { m_custom_client = &client; } void TooltipWindow::unsetCustomTooltipClient(CustomTooltipClient& client) { if(m_custom_client == &client) { m_custom_client = nullptr; } } void TooltipWindow::hideTip() { if(! m_reentrant) { m_tip_showing.clear(); removeFromDesktop(); setVisible(false); m_custom_client = nullptr; } } void TooltipWindow::timerCallback() { juce::Desktop& desktop = juce::Desktop::getInstance(); const juce::MouseInputSource mouseSource(desktop.getMainMouseSource()); const unsigned int now = juce::Time::getApproximateMillisecondCounter(); const bool has_custom_tooltip = (m_custom_client != nullptr); Component* const new_comp = ! mouseSource.isTouch() ? mouseSource.getComponentUnderMouse() : nullptr; juce::String new_tip; if(juce::Process::isForegroundProcess()) { if(has_custom_tooltip) { new_tip = m_custom_client->getTooltip(); } else if(new_comp && !juce::ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()) { if(juce::TooltipClient* const ttc = dynamic_cast<juce::TooltipClient*>(new_comp)) if(! new_comp->isCurrentlyBlockedByAnotherModalComponent()) new_tip = ttc->getTooltip(); } } const bool tip_changed = (new_tip != m_last_tip_under_mouse || m_custom_client != m_last_custom_client || new_comp != m_last_component_under_mouse); m_last_custom_client = m_custom_client; m_last_component_under_mouse = new_comp; m_last_tip_under_mouse = new_tip; const int click_count = desktop.getMouseButtonClickCounter(); const int wheel_count = desktop.getMouseWheelMoveCounter(); const bool mouse_was_clicked = (click_count > m_mouse_clicks || wheel_count > m_mouse_wheel_moves); m_mouse_clicks = click_count; m_mouse_wheel_moves = wheel_count; const juce::Point<float> mousePos(mouseSource.getScreenPosition()); const bool mouse_moved_quickly = !has_custom_tooltip ? mousePos.getDistanceFrom(m_last_mouse_pos) > 12 : false; m_last_mouse_pos = mousePos; if(tip_changed || mouse_was_clicked || mouse_moved_quickly) m_last_comp_change_time = now; if(isVisible() || now < m_last_hide_time + 500) { // if a tip is currently visible(or has just disappeared), update to a new one // immediately if needed.. if((!has_custom_tooltip && (new_comp == nullptr || mouse_was_clicked || new_tip.isEmpty())) || (has_custom_tooltip && (mouse_was_clicked || new_tip.isEmpty()))) { if(isVisible()) { m_last_hide_time = now; hideTip(); } } else if(tip_changed) { displayTip(mousePos.roundToInt(), new_tip); } } else { // if there isn't currently a tip, but one is needed, only let it // appear after a timeout.. if(new_tip.isNotEmpty() && new_tip != m_tip_showing && now > m_last_comp_change_time + (unsigned int) m_milliseconds_before_tip_appears) { displayTip(mousePos.roundToInt(), new_tip); } } } }
9,236
C++
.cpp
207
31.193237
110
0.505454
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,354
KiwiApp_PatcherViewHitTester.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Patcher/KiwiApp_PatcherViewHitTester.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 : [email protected] ============================================================================== */ #include <KiwiApp_Patcher/KiwiApp_Objects/KiwiApp_ObjectFrame.h> #include "KiwiApp_PatcherViewHitTester.h" #include "KiwiApp_PatcherView.h" #include "KiwiApp_LinkView.h" namespace kiwi { // ================================================================================ // // HITTESTER // // ================================================================================ // HitTester::HitTester(PatcherView const& patcher) : m_patcher(patcher), m_object(nullptr), m_link(nullptr), m_target(Target::Nothing), m_zone(Zone::Outside), m_border(None), m_index(0) { ; } HitTester::~HitTester() { ; } void HitTester::reset() { m_object = nullptr; m_link = nullptr; m_target = Target::Nothing; m_zone = Zone::Outside; m_border = None; m_index = 0; } void HitTester::test(juce::Point<int> const& point) noexcept { reset(); const bool hit_object = testObjects(point); if(!hit_object) { const bool hit_link = testLinks(point); if(!hit_link) { m_target = Target::Patcher; m_zone = Zone::Inside; } } } bool HitTester::testObjects(juce::Point<int> const& point) noexcept { reset(); const auto& objects = m_patcher.getObjects(); for(auto it = objects.rbegin(); it != objects.rend(); ++it) { auto& box_uptr = *it; if(box_uptr) { const auto box_bounds = box_uptr->getBounds(); if(box_bounds.contains(point.x, point.y)) { const auto relative_point = point - box_bounds.getPosition(); if(box_uptr->hitTest(relative_point, *this)) { m_object = box_uptr.get(); m_target = Target::Box; return true; } } } } return false; } bool HitTester::testLinks(juce::Point<int> const& point) noexcept { reset(); const auto& links = m_patcher.getLinks(); for(auto it = links.rbegin(); it != links.rend(); ++it) { auto& link_uptr = *it; if(link_uptr) { const auto link_bounds = link_uptr->getBounds(); if(link_bounds.contains(point.x, point.y)) { const auto relative_point = point - link_bounds.getPosition(); if(link_uptr->hitTest(relative_point, *this)) { m_zone = HitTester::Zone::Inside; m_link = link_uptr.get(); m_target = Target::Link; m_index = 0; return true; } } } } return false; } void HitTester::test(juce::Rectangle<int> const& rect, std::vector<ObjectFrame*>& objects, std::vector<LinkView*>& links) { testObjects(rect, objects); testLinks(rect, links); } void HitTester::testObjects(juce::Rectangle<int> const& rect, std::vector<ObjectFrame*>& objects) { objects.clear(); for(auto& box_uptr : m_patcher.getObjects()) { if(box_uptr && box_uptr->hitTest(rect)) { objects.push_back(box_uptr.get()); } } } void HitTester::testLinks(juce::Rectangle<int> const& rect, std::vector<LinkView*>& links) { links.clear(); for(auto& link_uptr : m_patcher.getLinks()) { if(link_uptr && link_uptr->hitTest(rect.toFloat())) { links.push_back(link_uptr.get()); } } } PatcherView const& HitTester::getPatcher() const noexcept { return m_patcher; } ObjectFrame* HitTester::getObject() const noexcept { if(m_target == Target::Box) { return m_object; } return nullptr; } LinkView* HitTester::getLink() const noexcept { if(m_target == Target::Link) { return m_link; } return nullptr; } HitTester::Zone HitTester::getZone() const noexcept { if(m_target == Target::Box) { return m_zone; } else if(m_target == Target::Link) { return std::max<Zone>(Zone::Outside, std::min<Zone>(m_zone, Zone::Outlet)); } else if(m_target == Target::Patcher) { return std::max<Zone>(Zone::Outside, std::min<Zone>(m_zone, Zone::Inside)); } return Zone::Outside; } int HitTester::getBorder() const noexcept { if(m_target == Target::Box) { return m_border; } return None; } size_t HitTester::getIndex() const noexcept { if(m_target == Target::Box) { return m_index; } return 0; } }
6,336
C++
.cpp
192
22.703125
101
0.481936
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,355
KiwiApp_Factory.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Patcher/KiwiApp_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 : [email protected] ============================================================================== */ #include <functional> #include <KiwiApp_Patcher/KiwiApp_Factory.h> #include <KiwiApp_Patcher/KiwiApp_Objects/KiwiApp_ClassicView.h> namespace kiwi { std::map<std::string, Factory::ctor_fn_t> Factory::m_creators; std::unique_ptr<ObjectView> Factory::createObjectView(model::Object & object_model) { std::string object_name = object_model.getName(); if (m_creators.find(object_name) != m_creators.end()) { return m_creators[object_name](object_model); } else { return std::make_unique<ClassicView>(object_model); } return std::unique_ptr<ObjectView>(); } }
1,575
C++
.cpp
34
39.911765
91
0.584605
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,356
KiwiApp_PatcherViewMouseHandler.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Patcher/KiwiApp_PatcherViewMouseHandler.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 : [email protected] ============================================================================== */ #include <algorithm> #include <KiwiModel/KiwiModel_Object.h> #include <KiwiModel/KiwiModel_DocumentManager.h> #include <KiwiApp.h> #include <KiwiApp_Patcher/KiwiApp_PatcherView.h> #include <KiwiApp_Patcher/KiwiApp_LinkView.h> #include <KiwiApp_Patcher/KiwiApp_Objects/KiwiApp_ObjectFrame.h> #include <KiwiApp_Patcher/KiwiApp_PatcherViewHitTester.h> namespace kiwi { // ================================================================================ // // HITTESTER // // ================================================================================ // MouseHandler::MouseHandler(PatcherView & patcher_view) : m_patcher_view(patcher_view) {} MouseHandler::~MouseHandler() {} MouseHandler::Action MouseHandler::getCurrentAction() { return m_current_action; } void MouseHandler::startAction(Action action, juce::MouseEvent const& e) { m_current_action = action; HitTester& hit_tester = m_patcher_view.m_hittester; switch (m_current_action) { case Action::CopyOnDrag: { if(auto* object = hit_tester.getObject()) { if (!m_patcher_view.isSelected(*object)) { m_patcher_view.selectObjectOnly(*object); } } break; } case Action::ForwardToObject: { if(auto* object = hit_tester.getObject()) { object->mouseDown(e.getEventRelativeTo(object)); } break; } case Action::CreateLink: { if(auto* object = hit_tester.getObject()) { m_patcher_view.unselectAll(); const bool is_sender = hit_tester.getZone() == HitTester::Zone::Outlet; m_patcher_view.m_link_creator.reset(new LinkViewCreator(*object, hit_tester.getIndex(), is_sender, e.getPosition())); m_patcher_view.addAndMakeVisible(*m_patcher_view.m_link_creator); } break; } case Action::Lasso: { m_patcher_view.m_lasso.begin(e.getPosition(), e.mods.isShiftDown()); break; } case Action::MoveObjects: { KiwiApp::commandStatusChanged(); model::DocumentManager::startCommitGesture(m_patcher_view.m_patcher_model); break; } case Action::PopupMenu: { if(hit_tester.objectTouched() && hit_tester.getZone() == HitTester::Zone::Inside) { auto& object = *hit_tester.getObject(); const auto pos = e.getPosition() - m_patcher_view.useViewport().getOriginPosition(); m_patcher_view.showObjectPopupMenu(object, pos); } else if (hit_tester.linkTouched() && hit_tester.getZone() == HitTester::Zone::Inside) { auto& link_view = *hit_tester.getLink(); const auto pos = e.getPosition() - m_patcher_view.useViewport().getOriginPosition(); m_patcher_view.showLinkPopupMenu(link_view, pos); } else if (hit_tester.patcherTouched()) { m_patcher_view.showPatcherPopupMenu(e.getPosition() - m_patcher_view.useViewport().getOriginPosition()); } break; } case Action::SwitchSelection: { if (hit_tester.objectTouched()) { ObjectFrame & object = *hit_tester.getObject(); if (m_patcher_view.isSelected(object)) { m_patcher_view.unselectObject(object); } else { m_patcher_view.selectObject(object); } } else if (hit_tester.linkTouched()) { LinkView & link = *hit_tester.getLink(); if (m_patcher_view.isSelected(link)) { m_patcher_view.unselectLink(link); } else { m_patcher_view.selectLink(link); } } break; } case Action::Selection: { if (hit_tester.objectTouched()) { m_patcher_view.selectObjectOnly(*hit_tester.getObject()); } else if (hit_tester.linkTouched()) { m_patcher_view.selectLinkOnly(*hit_tester.getLink()); } break; } case Action::ResizeObjects: { m_direction = getResizeDirection(hit_tester); auto& document = m_patcher_view.m_patcher_model.entity().use<model::DocumentManager>(); for (flip::Ref const& ref : m_patcher_view.getSelectedObjects()) { model::Object const& object = *document.get<model::Object>(ref); m_mousedown_bounds[ref] = juce::Rectangle<int>(object.getX(), object.getY(), object.getWidth(), object.getHeight()); } model::DocumentManager::startCommitGesture(m_patcher_view.m_patcher_model); break; } default: break; } } void MouseHandler::continueAction(juce::MouseEvent const& e) { HitTester& hit_tester = m_patcher_view.m_hittester; switch (m_current_action) { case Action::CopyOnDrag: { if (e.getMouseDownPosition() != e.getPosition()) { m_patcher_view.copySelectionToClipboard(); m_patcher_view.pasteFromClipboard({0, 0}); startAction(Action::MoveObjects, e); } break; } case Action::ForwardToObject: { if(auto* box = hit_tester.getObject()) { box->mouseDrag(e.getEventRelativeTo(box)); } break; } case Action::CreateLink: { auto nearest_ending_iolet = m_patcher_view.getLinkCreatorNearestEndingIolet(); if(auto* box = nearest_ending_iolet.first) { const auto index = nearest_ending_iolet.second; if(m_patcher_view.m_link_creator->isBindedToSender()) { m_patcher_view.m_io_highlighter.highlightInlet(*box, index); } else { m_patcher_view.m_io_highlighter.highlightOutlet(*box, index); } } else { m_patcher_view.m_io_highlighter.hide(); } if (hit_tester.getZone() == HitTester::Zone::Outlet || hit_tester.getZone() == HitTester::Zone::Inlet) { m_patcher_view.m_link_creator->setEndPosition(e.getPosition()); } break; } case Action::Lasso: { if(m_patcher_view.m_lasso.isPerforming()) { m_patcher_view.m_lasso.perform(e.getPosition(), true, e.mods.isAltDown(), e.mods.isShiftDown()); } break; } case Action::MoveObjects: { if (m_patcher_view.isAnyObjectSelected()) { m_patcher_view.moveSelectedObjects(e.getPosition() - m_last_drag, true, true); if(!m_patcher_view.useViewport().getRelativeViewArea().contains(e.getPosition())) { m_patcher_view.beginDragAutoRepeat(50); const juce::MouseEvent e2(e.getEventRelativeTo(&m_patcher_view.useViewport())); m_patcher_view.useViewport().autoScroll(e2.x, e2.y, 5, 5); } } break; } case Action::EditObject: { if (hit_tester.objectTouched() && e.getMouseDownPosition() != e.getPosition()) { startAction(Action::MoveObjects, e); } break; } case Action::SwitchSelection: { if (hit_tester.objectTouched() && e.getMouseDownPosition() != e.getPosition()) { startAction(Action::MoveObjects, e); } break; } case Action::Selection: { if (hit_tester.objectTouched() && e.getMouseDownPosition() != e.getPosition()) { startAction(Action::MoveObjects, e); } break; } case Action::ResizeObjects: { const auto delta = e.getPosition() - e.getMouseDownPosition(); auto& patcher_model = m_patcher_view.m_patcher_model; for (auto bounds_it : m_mousedown_bounds) { auto& document = patcher_model.entity().use<model::DocumentManager>(); const auto object_ref = bounds_it.first; if(auto model = document.get<model::Object>(object_ref)) { if(auto* box = m_patcher_view.getObject(*model)) { resizeModelObjectBounds(*model, *box, bounds_it.second, delta, e.mods.isShiftDown()); } } } std::string commit_msg = "Resize object"; commit_msg += (m_mousedown_bounds.size() > 1 ? "s" : ""); model::DocumentManager::commitGesture(patcher_model, commit_msg); break; } default: { break; } } } void MouseHandler::endAction(juce::MouseEvent const& e) { HitTester& hit_tester = m_patcher_view.m_hittester; switch (m_current_action) { case Action::ForwardToObject: { ObjectFrame & object = *hit_tester.getObject(); object.mouseUp(e.getEventRelativeTo(&object)); break; } case Action::CreateLink: { m_patcher_view.m_io_highlighter.hide(); auto end_pair = m_patcher_view.getLinkCreatorNearestEndingIolet(); if(end_pair.first != nullptr) { LinkViewCreator& link_creator = *m_patcher_view.m_link_creator; const bool sender = link_creator.isBindedToSender(); model::Object const& binded_object = link_creator.getBindedObject().getModel(); model::Object const& ending_object = end_pair.first->getModel(); model::Object const& from = sender ? binded_object : ending_object; model::Object const& to = sender ? ending_object : binded_object; const size_t outlet = sender ? link_creator.getBindedIndex() : end_pair.second; const size_t inlet = sender ? end_pair.second : link_creator.getBindedIndex(); model::Link* link = m_patcher_view.m_patcher_model.addLink(from, outlet, to, inlet); if(link != nullptr) { m_patcher_view.m_view_model.selectLink(*link); model::DocumentManager::commit(m_patcher_view.m_patcher_model, "Add link"); } } m_patcher_view.removeChildComponent(m_patcher_view.m_link_creator.get()); m_patcher_view.m_link_creator.reset(); break; } case Action::Lasso: { if(m_patcher_view.m_lasso.isPerforming()) { m_patcher_view.m_lasso.end(); } break; } case Action::MoveObjects: { model::DocumentManager::endCommitGesture(m_patcher_view.m_patcher_model); m_patcher_view.useViewport().updatePatcherArea(true); m_patcher_view.useViewport().jumpViewToObject(*hit_tester.getObject()); KiwiApp::commandStatusChanged(); break; } case Action::EditObject: { if(auto* object = hit_tester.getObject()) { m_patcher_view.editObject(*object); } break; } case Action::ResizeObjects: { model::DocumentManager::endCommitGesture(m_patcher_view.m_patcher_model); m_direction = Direction::None; m_mousedown_bounds.clear(); m_patcher_view.useViewport().updatePatcherArea(true); KiwiApp::commandStatusChanged(); break; } case Action::SwitchLock: { m_patcher_view.setLock(!m_patcher_view.isLocked()); break; } case Action::OpenObjectHelp: { m_patcher_view.openObjectHelp(); break; } default: break; } m_current_action = Action::None; } void MouseHandler::handleMouseDown(juce::MouseEvent const& e) { HitTester& hit_tester = m_patcher_view.m_hittester; hit_tester.test(e.getPosition()); if(!m_patcher_view.isLocked()) { if(hit_tester.objectTouched()) { if(hit_tester.getZone() == HitTester::Zone::Inside) { if (e.mods.isCommandDown()) { startAction(Action::ForwardToObject, e); } else { auto& object = *hit_tester.getObject(); const bool was_selected = m_patcher_view.isSelected(object); if (e.mods.isShiftDown()) { startAction(Action::SwitchSelection, e); } else if(!was_selected) { startAction(Action::Selection, e); } if(e.mods.isAltDown()) { startAction(Action::None, e); } else if(e.mods.isPopupMenu()) { startAction(Action::PopupMenu, e); } else if(was_selected && !e.mods.isShiftDown()) { startAction(Action::EditObject, e); } else { startAction(Action::None, e); } } } else if(hit_tester.getZone() == HitTester::Zone::Outlet || hit_tester.getZone() == HitTester::Zone::Inlet) { startAction(Action::CreateLink, e); } else if (hit_tester.getZone() == HitTester::Zone::Border) { startAction(Action::ResizeObjects, e); } } else if(hit_tester.linkTouched()) { if(hit_tester.getZone() == HitTester::Zone::Inside) { if(e.mods.isPopupMenu()) { startAction(Action::PopupMenu, e); } else { if (e.mods.isShiftDown()) { startAction(Action::SwitchSelection, e); } else { startAction(Action::Selection, e); } } } } else if(hit_tester.patcherTouched()) { if(e.mods.isPopupMenu()) { startAction(Action::PopupMenu, e); } else if (e.mods.isCommandDown()) { startAction(Action::SwitchLock, e); } else { startAction(Action::Lasso, e); } } } else if (e.mods.isCommandDown() && hit_tester.patcherTouched()) { startAction(Action::SwitchLock, e); } else if(e.mods.isPopupMenu()) { startAction(Action::PopupMenu, e); } m_last_drag = e.getPosition(); } void MouseHandler::handleMouseDrag(juce::MouseEvent const& e) { if(m_current_action == Action::None && e.mouseWasDraggedSinceMouseDown() && e.mods.isAltDown()) { startAction(Action::CopyOnDrag, e); } else if(m_current_action == Action::None && !m_patcher_view.isLocked() && e.mouseWasDraggedSinceMouseDown()) { startAction(Action::MoveObjects, e); } else if(m_current_action != Action::None) { continueAction(e); } m_last_drag = e.getPosition(); } void MouseHandler::handleMouseUp(juce::MouseEvent const& e) { if(m_current_action == Action::None && e.mods.isAltDown()) { startAction(Action::OpenObjectHelp, e); } endAction(e); } void MouseHandler::handleMouseDoubleClick(juce::MouseEvent const& e) { if(!m_patcher_view.isLocked()) { HitTester& hit_tester = m_patcher_view.m_hittester; hit_tester.test(e.getPosition()); if(e.mods.isCommandDown() && hit_tester.objectTouched()) { if(auto* object = hit_tester.getObject()) { object->mouseDoubleClick(e.getEventRelativeTo(object)); } } else if(hit_tester.patcherTouched()) { m_patcher_view.createObjectModel("", true); } } } int MouseHandler::getResizeDirection(HitTester const& hit_tester) const { int border = hit_tester.getBorder(); int direction = Direction::None; int resize_flags = HitTester::Border::None; if(auto* box = hit_tester.getObject()) { resize_flags = box->getResizingFlags(); } const bool grow_x = ((resize_flags & HitTester::Border::Left) || resize_flags & HitTester::Border::Right); const bool grow_y = ((resize_flags & HitTester::Border::Top) || resize_flags & HitTester::Border::Bottom); if(grow_x) { if (border & HitTester::Border::Right) { direction |= Direction::Right; } if (border & HitTester::Border::Left) { direction |= Direction::Left; } } if(grow_y) { if (border & HitTester::Border::Top) { direction |= Direction::Up; } if ((border & HitTester::Border::Bottom)) { direction |= Direction::Down; } } return direction; } juce::MouseCursor::StandardCursorType MouseHandler::getMouseCursorForBorder(HitTester const& hit_tester) const { juce::MouseCursor::StandardCursorType mc = juce::MouseCursor::NormalCursor; int direction = getResizeDirection(hit_tester); int resize_flags = HitTester::Border::None; if(auto* box = hit_tester.getObject()) { resize_flags = box->getResizingFlags(); } const bool grow_y = ((resize_flags & HitTester::Border::Top) || resize_flags & HitTester::Border::Bottom); if(!grow_y && (direction == Direction::Left || direction == Direction::Right)) { return juce::MouseCursor::LeftRightResizeCursor; } switch(direction) { case (Direction::Up) : { mc = juce::MouseCursor::TopEdgeResizeCursor; break; } case (Direction::Left): { mc = juce::MouseCursor::LeftEdgeResizeCursor; break; } case (Direction::Right): { mc = juce::MouseCursor::RightEdgeResizeCursor; break; } case (Direction::Down): { mc = juce::MouseCursor::BottomEdgeResizeCursor; break; } case (Direction::Up | Direction::Left): { mc = juce::MouseCursor::TopLeftCornerResizeCursor; break; } case (Direction::Up | Direction::Right): { mc = juce::MouseCursor::TopRightCornerResizeCursor; break; } case (Direction::Down | Direction::Left): { mc = juce::MouseCursor::BottomLeftCornerResizeCursor; break; } case (Direction::Down | Direction::Right): { mc = juce::MouseCursor::BottomRightCornerResizeCursor; break; } default: break; } return mc; } void MouseHandler::handleMouseMove(juce::MouseEvent const& e) { juce::MouseCursor::StandardCursorType mc = juce::MouseCursor::NormalCursor; HitTester& hit_tester = m_patcher_view.m_hittester; hit_tester.test(e.getPosition()); if (hit_tester.getZone() != HitTester::Zone::Outlet && hit_tester.getZone() != HitTester::Zone::Inlet) { m_patcher_view.m_io_highlighter.hide(); } if(!m_patcher_view.isLocked()) { if(hit_tester.objectTouched()) { if(hit_tester.getZone() == HitTester::Zone::Border) { mc = getMouseCursorForBorder(hit_tester); } else if(hit_tester.getZone() == HitTester::Zone::Outlet || hit_tester.getZone() == HitTester::Zone::Inlet) { if(hit_tester.getZone() == HitTester::Zone::Inlet) { m_patcher_view.m_io_highlighter.highlightInlet(*hit_tester.getObject(), hit_tester.getIndex()); } else { m_patcher_view.m_io_highlighter.highlightOutlet(*hit_tester.getObject(), hit_tester.getIndex()); } mc = juce::MouseCursor::PointingHandCursor; } } } m_patcher_view.setMouseCursor(mc); } void MouseHandler::resizeModelObjectBounds(model::Object& model, ObjectFrame& box, juce::Rectangle<int> prev_bounds, juce::Point<int> delta, bool fixed_ratio) { auto new_bounds = prev_bounds; double ratio = 0.; const bool stretching_top = m_direction & Direction::Up; const bool stretching_left = m_direction & Direction::Left; const bool stretching_bottom = m_direction & Direction::Down; const bool stretching_right = m_direction & Direction::Right; if (fixed_ratio && new_bounds.getWidth() != 0) { ratio = (static_cast<double>(new_bounds.getWidth()) / static_cast<double>(new_bounds.getHeight())); } if (stretching_left) { new_bounds.setLeft(std::min(new_bounds.getX() + delta.getX(), new_bounds.getRight())); } if (stretching_top) { new_bounds.setTop(std::min(new_bounds.getY() + delta.getY(), new_bounds.getBottom())); } if (stretching_right) { new_bounds.setRight(std::max(new_bounds.getRight() + delta.getX(), new_bounds.getX())); } if (stretching_bottom) { new_bounds.setBottom(std::max(new_bounds.getBottom() + delta.getY(), new_bounds.getY())); } const juce::Rectangle<int> limits {}; auto target_bounds = new_bounds; auto* box_constrainer = box.getBoundsConstrainer(); const auto box_ratio = box_constrainer->getFixedAspectRatio(); // impose ratio if not set box_constrainer->setFixedAspectRatio(box_ratio == 0 ? ratio : box_ratio); box_constrainer->checkBounds(target_bounds, prev_bounds, limits, stretching_top, stretching_left, stretching_bottom, stretching_right); // restore ratio box_constrainer->setFixedAspectRatio(box_ratio); model.setPosition(target_bounds.getX(), target_bounds.getY()); model.setWidth(target_bounds.getWidth()); model.setHeight(target_bounds.getHeight()); } }
29,424
C++
.cpp
707
23.970297
124
0.461025
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,357
KiwiApp_PatcherViewLasso.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Patcher/KiwiApp_PatcherViewLasso.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 : [email protected] ============================================================================== */ #include <KiwiApp_Patcher/KiwiApp_Objects/KiwiApp_ObjectFrame.h> #include "KiwiApp_PatcherViewLasso.h" #include "KiwiApp_PatcherView.h" #include "KiwiApp_LinkView.h" #include "../KiwiApp.h" namespace kiwi { // ================================================================================ // // LASSO // // ================================================================================ // Lasso::Lasso(PatcherView& patcher) : m_patcher(patcher), m_dragging(false) { setInterceptsMouseClicks(false, false); setWantsKeyboardFocus(false); setAlwaysOnTop(true); setVisible(false); setBounds(0, 0, 1, 1); } Lasso::~Lasso() { ; } bool Lasso::isPerforming() const noexcept { return m_dragging; } void Lasso::paint(juce::Graphics& g) { const juce::Rectangle<int> bounds = getLocalBounds(); const juce::Colour color = juce::Colour::fromFloatRGBA(0.96, 0.96, 0.96, 1.); g.setColour(color.withAlpha(0.5f)); g.fillAll(); g.setColour(color); g.drawRect(bounds, 1.); } void Lasso::begin(juce::Point<int> const& point, const bool preserve_selection) { assert(!m_dragging); if(!preserve_selection) { m_patcher.unselectAll(); } else { m_objects = m_patcher.getSelectedObjects(); m_links = m_patcher.getSelectedLinks(); } m_start = point; m_dragging = true; } void Lasso::perform(juce::Point<int> const& point, bool include_objects, bool include_links, const bool preserve) { bool selection_changed = false; juce::Rectangle<int> bounds = juce::Rectangle<int>(m_start, point); if(bounds.getWidth() == 0) { bounds.setWidth(1); } if(bounds.getHeight() == 0) { bounds.setHeight(1); } setBounds(bounds); m_dragging = true; setVisible(true); toFront(false); if(preserve) { if(include_objects) { PatcherView::ObjectFrames const& objects = m_patcher.getObjects(); HitTester hit(m_patcher); std::vector<ObjectFrame*> lasso_objects; hit.testObjects(bounds, lasso_objects); for(auto& object_frame_uptr : objects) { if(object_frame_uptr) { ObjectFrame& object = *object_frame_uptr.get(); const bool is_selected = object.isSelected(); const bool was_selected = m_objects.find(object.getModel().ref()) != m_objects.end(); const bool in_lasso = std::find(lasso_objects.begin(), lasso_objects.end(), &object) != lasso_objects.end(); if (!is_selected && (was_selected != in_lasso)) { m_patcher.selectObject(object); selection_changed = true; } else if(is_selected && (was_selected == in_lasso)) { m_patcher.unselectObject(object); selection_changed = true; } } } } if(include_links) { PatcherView::LinkViews const& links = m_patcher.getLinks(); HitTester hit(m_patcher); std::vector<LinkView*> lasso_links; hit.testLinks(bounds, lasso_links); for(auto& link_view_uptr : links) { if(link_view_uptr) { LinkView& link = *link_view_uptr.get(); const bool is_selected = link.isSelected(); const bool was_selected = m_links.find(link.getModel().ref()) != m_links.end(); const bool in_lasso = std::find(lasso_links.begin(), lasso_links.end(), &link) != lasso_links.end(); if (!is_selected && (was_selected != in_lasso)) { m_patcher.selectLink(link); selection_changed = true; } else if(is_selected && (was_selected == in_lasso)) { m_patcher.unselectLink(link); selection_changed = true; } } } } if(selection_changed) { //ctrl->selectionChanged(); } } else { m_patcher.unselectAll(); HitTester hit(m_patcher); if(include_objects) { std::vector<ObjectFrame*> objects; hit.testObjects(bounds, objects); m_patcher.selectObjects(objects); } if(include_links) { std::vector<LinkView*> links; hit.testLinks(bounds, links); m_patcher.selectLinks(links); } } } void Lasso::end() { m_dragging = false; setVisible(false); m_objects.clear(); m_links.clear(); } }
6,791
C++
.cpp
168
25.761905
132
0.470824
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,358
KiwiApp_PatcherManager.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Patcher/KiwiApp_PatcherManager.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 : [email protected] ============================================================================== */ #include <chrono> #include <json.hpp> #include <flip/contrib/DataProviderFile.h> #include <flip/BackEndIR.h> #include <flip/BackEndBinary.h> #include <flip/contrib/DataConsumerFile.h> #include <KiwiModel/KiwiModel_DataModel.h> #include <KiwiModel/KiwiModel_Def.h> #include <KiwiModel/KiwiModel_Converters/KiwiModel_Converter.h> #include <KiwiEngine/KiwiEngine_Patcher.h> #include <KiwiEngine/KiwiEngine_Instance.h> #include <KiwiApp_Patcher/KiwiApp_PatcherManager.h> #include <KiwiApp.h> #include <KiwiApp_Application/KiwiApp_Instance.h> #include <KiwiModel/KiwiModel_DocumentManager.h> #include <KiwiApp_Patcher/KiwiApp_PatcherView.h> #include <KiwiApp_Patcher/KiwiApp_PatcherComponent.h> namespace kiwi { using json = nlohmann::json; // ================================================================================ // // PATCHER MANAGER // // ================================================================================ // PatcherManager::PatcherManager(Instance& instance, std::string const& name) : m_name(name) , m_instance(instance) , m_validator() , m_document(model::DataModel::use(), *this, m_validator, m_instance.getUserId(), 'cicm', 'kpat') , m_socket(m_document) , m_session(nullptr) , m_stack_overflow_detected_signal_cnx(m_document.root<model::Patcher>().signal_stack_overflow .connect([this](std::vector<flip::Ref> refs) { onStackOverflowDetected(std::move(refs)); })) , m_stack_overflow_cleared_signal_cnx(m_document.root<model::Patcher>().signal_stack_overflow_clear .connect([this]() { onStackOverflowCleared(); })) {} PatcherManager::~PatcherManager() { m_stack_overflow_cleared_signal_cnx.disconnect(); m_stack_overflow_detected_signal_cnx.disconnect(); disconnect(); } std::unique_ptr<PatcherManager> PatcherManager::createFromFile(Instance& instance, juce::File const& file) { auto filename = file.getFileNameWithoutExtension().toStdString(); auto manager = std::make_unique<PatcherManager>(instance, filename); if(manager && manager->loadFromFile(file)) { return manager; } return nullptr; } void PatcherManager::addListener(Listener& listener) { m_listeners.add(listener); } void PatcherManager::removeListener(Listener& listener) { m_listeners.remove(listener); } void PatcherManager::pull() { if (isConnected()) { m_socket.process(); } if (isConnected()) { model::DocumentManager::pull(getPatcher()); } } void PatcherManager::onStateTransition(flip::CarrierBase::Transition transition, flip::CarrierBase::Error error) { if (transition == flip::CarrierBase::Transition::Disconnected) { if(m_session) { m_session->useDrive().removeListener(*this); m_session = nullptr; } m_connected_users.clear(); m_listeners.call(&Listener::connectedUserChanged, *this); flip::Collection<model::Patcher::View> & views = getPatcher().useSelfUser().getViews(); for(auto & view : views) { view.entity().use<PatcherViewWindow>().removeUsersIcon(); } setNeedSaving(true); updateTitleBars(); } } bool PatcherManager::hasStackOverflow() const { return m_has_stack_overflow; } void PatcherManager::onStackOverflowDetected(std::vector<flip::Ref> refs) { KiwiApp::error("remove the culprits then click on the infinite loop icon to unlock messages"); m_has_stack_overflow = true; m_listeners.call(&Listener::stackOverflowDetected, *this, refs); } void PatcherManager::onStackOverflowCleared() { m_has_stack_overflow = false; m_listeners.call(&Listener::stackOverflowCleared, *this); } void PatcherManager::clearStackOverflow() { m_document.root<model::Patcher>().signal_stack_overflow_clear(); } void PatcherManager::disconnect() { if (isConnected()) { m_socket.disconnect(); } } bool PatcherManager::connect(std::string const& host, uint16_t port, DocumentBrowser::Drive::DocumentSession& session) { disconnect(); model::Patcher& patcher = getPatcher(); m_user_connected_signal_cnx = patcher.signal_user_connect.connect([this](uint64_t user_id){ if(m_connected_users.insert(user_id).second) { m_listeners.call(&Listener::connectedUserChanged, *this); } }); m_user_disconnected_signal_cnx = patcher.signal_user_disconnect.connect([this](uint64_t user_id){ const auto user_to_erase = m_connected_users.find(user_id); if(user_to_erase != m_connected_users.cend()) { m_connected_users.erase(user_id); m_listeners.call(&Listener::connectedUserChanged, *this); } }); m_receive_connected_users_signal_cnx = patcher.signal_receive_connected_users.connect([this](std::vector<uint64_t> users){ // Todo : make a diff of the changes and notify listeners only if the list really changed. m_connected_users.clear(); m_connected_users.insert(users.begin(), users.end()); m_listeners.call(&Listener::connectedUserChanged, *this); }); json j; j["model_version"] = KIWI_MODEL_VERSION_STRING; j["open_token"] = session.getOpenToken(); j["kiwi_version"] = KiwiApp::getApp()->getApplicationVersion().toStdString(); std::string metadata = j.dump(); m_socket.connect(host, port, session.getSessionId(), metadata); bool patcher_loaded = false; m_socket.listenTransferBackend([&patcher_loaded](size_t cur, size_t total) { patcher_loaded = cur == total; }); const auto init_time = std::chrono::steady_clock::now(); const std::chrono::duration<int> time_out(2); while(!m_socket.isConnected() && std::chrono::steady_clock::now() - init_time < time_out) { m_socket.process(); } while(!patcher_loaded && m_socket.isConnected()) { m_socket.process(); } if (m_socket.isConnected() && patcher_loaded) { m_session = &session; m_session->useDrive().addListener(*this); m_socket.listenStateTransition([this](flip::CarrierBase::Transition state, flip::CarrierBase::Error error) { onStateTransition(state, error); }); model::DocumentManager::pull(patcher); patcher.useSelfUser(); model::DocumentManager::commit(patcher); setName(session.getName()); setNeedSaving(false); updateTitleBars(); patcher.entity().use<engine::Patcher>().sendLoadbang(); } return m_socket.isConnected() && patcher_loaded; } bool PatcherManager::readBackEndBinary(flip::DataProviderBase& data_provider) { flip::BackEndIR binary_backend; binary_backend.register_backend<flip::BackEndBinary>(); //binary_backend.register_backend<flip::BackEndMl>(); if (binary_backend.read(data_provider)) { const auto current_version = model::Converter::getLatestVersion(); const auto backend_version = binary_backend.version; if(!model::Converter::canConvertToLatestFrom(backend_version)) { throw std::runtime_error("bad version: no conversion available from " + backend_version + " to " + current_version); return false; } if (model::Converter::process(binary_backend)) { try { m_document.read(binary_backend); } catch (...) { std::runtime_error("document failed to read"); return false; } } else { throw std::runtime_error("failed to convert document from " + backend_version + " to " + current_version); } } else { throw std::runtime_error("backend failed to read"); } return true; } bool PatcherManager::loadFromFile(juce::File const& file) { if(!file.hasFileExtension(".kiwi;.kiwihelp")) { throw std::runtime_error("bad extension"); return false; } std::string filepath = file.getFullPathName().toStdString(); // assuming that the file is in in a binary format flip::DataProviderFile provider(filepath.c_str()); if(readBackEndBinary(provider)) { model::Patcher& patcher = getPatcher(); patcher.useSelfUser(); try { model::DocumentManager::commit(patcher); } catch (...) { throw std::runtime_error("document failed to load"); return false; } m_file = file; setName(file.getFileNameWithoutExtension().toStdString()); setNeedSaving(false); updateTitleBars(); patcher.entity().use<engine::Patcher>().sendLoadbang(); } return true; } model::Patcher& PatcherManager::getPatcher() { return m_document.root<model::Patcher>(); } model::Patcher const& PatcherManager::getPatcher() const { return m_document.root<model::Patcher>(); } bool PatcherManager::isConnected() const noexcept { return m_socket.isConnected(); } uint64_t PatcherManager::getSessionId() const noexcept { return m_session ? m_session->getSessionId() : 0ull; } std::string PatcherManager::getDocumentName() const { return m_name; } void PatcherManager::newView() { auto& patcher = getPatcher(); if(!model::DocumentManager::isInCommitGesture(patcher)) { patcher.useSelfUser().addView(); model::DocumentManager::commit(patcher); } } size_t PatcherManager::getNumberOfUsers() { return m_connected_users.size(); } std::unordered_set<uint64_t> PatcherManager::getConnectedUsers() { return m_connected_users; } size_t PatcherManager::getNumberOfView() { auto& patcher = getPatcher(); auto& user = patcher.useSelfUser(); auto& views = user.getViews(); return std::count_if(views.begin(), views.end(), [](model::Patcher::View const& view){ return !view.removed(); }); } juce::File const& PatcherManager::getSelectedFile() const { return m_file; } bool PatcherManager::needsSaving() const noexcept { return m_need_saving_flag && !isConnected(); } void PatcherManager::writeDocument() { flip::BackEndIR back_end = m_document.write(); flip::DataConsumerFile consumer(m_file.getFullPathName().toStdString().c_str()); back_end.write<flip::BackEndBinary>(consumer); } bool PatcherManager::saveDocument(bool save_as) { bool saved = false; if(isConnected()) return false; if(save_as || !m_file.existsAsFile()) { const auto dir = KiwiApp::getGlobalDirectoryFor(KiwiApp::FileLocations::Save); juce::File suggest_file = dir.getChildFile(juce::String(m_name)).withFileExtension("kiwi"); juce::FileChooser saveFileChooser("Save file", suggest_file, "*.kiwi;*.kiwihelp"); if ((saved = saveFileChooser.browseForFileToSave(true))) { m_file = saveFileChooser.getResult(); KiwiApp::setGlobalDirectoryFor(KiwiApp::FileLocations::Save, m_file.getParentDirectory()); writeDocument(); setName(m_file.getFileNameWithoutExtension().toStdString()); } } if (!saved && m_file.existsAsFile()) { writeDocument(); saved = true; } if (saved) { setNeedSaving(false); updateTitleBars(); } return saved; } bool PatcherManager::saveIfNeededAndUserAgrees() { bool user_cancelled = false; if (needsSaving()) { const auto title = TRANS("Closing document..."); const auto message = TRANS("Do you want to save the changes to \"") + m_name + "\"?"; const int r = juce::AlertWindow::showYesNoCancelBox(juce::AlertWindow::QuestionIcon, title, message, TRANS("Save"), TRANS("Discard changes"), TRANS("Cancel"), &getFirstWindow()); if (r == 0) // cancel button { user_cancelled = true; } else if(r == 1) // save button { if (!saveDocument(false)) { user_cancelled = true; } } } return user_cancelled; } void PatcherManager::forceCloseAllWindows() { auto& patcher = getPatcher(); auto& user = patcher.useSelfUser(); auto& views = user.getViews(); for(auto it = views.begin(); it != views.end();) { it = user.removeView(*it); } model::DocumentManager::commit(patcher); } bool PatcherManager::askAllWindowsToClose() { auto& patcher = getPatcher(); auto& user = patcher.useSelfUser(); auto& views = user.getViews(); size_t number_of_views = std::count_if(views.begin(), views.end(), [](model::Patcher::View& view){ return !view.removed(); }); bool success = true; for(auto it = views.begin(); it != views.end();) { bool need_saving = m_need_saving_flag && (number_of_views <= 1); if(!need_saving || (need_saving && !saveIfNeededAndUserAgrees())) { it = user.removeView(*it); model::DocumentManager::commit(patcher); } else { return false; } number_of_views--; } return success; } void PatcherManager::closePatcherViewWindow(PatcherView& patcher_view) { auto& patcher = getPatcher(); auto& user = patcher.useSelfUser(); auto& patcher_view_m = patcher_view.getPatcherViewModel(); auto& views = user.getViews(); size_t number_of_views = std::count_if(views.begin(), views.end(), [](model::Patcher::View& view){ return !view.removed(); }); bool need_saving = m_need_saving_flag && (number_of_views <= 1); if (!need_saving || (need_saving && !saveIfNeededAndUserAgrees())) { user.removeView(patcher_view_m); model::DocumentManager::commit(patcher); } } PatcherViewWindow & PatcherManager::getFirstWindow() { auto first_view = getPatcher().useSelfUser().getViews().begin(); return (*first_view).entity().use<PatcherViewWindow>(); } void PatcherManager::bringsFirstViewToFront() { auto& patcher = getPatcher(); auto& user = patcher.useSelfUser(); auto& views = user.getViews(); auto view_it = views.begin(); if(view_it != views.end()) { model::Patcher::View& view = *view_it; if(view.entity().has<PatcherViewWindow>()) { view.entity().use<PatcherViewWindow>().toFront(true); } } } void PatcherManager::driveConnectionStatusChanged(bool is_online) { //! @todo drive refactoring if(m_session && !is_online) { m_session->useDrive().removeListener(*this); m_session = nullptr; } } void PatcherManager::documentAdded(DocumentBrowser::Drive::DocumentSession& doc) { ; } void PatcherManager::documentChanged(DocumentBrowser::Drive::DocumentSession& doc) { if(m_session && (m_session == &doc)) { setName(doc.getName()); updateTitleBars(); } } void PatcherManager::document_changed(model::Patcher& patcher) { if(patcher.added()) { std::unique_lock<std::mutex> lock(m_instance.useEngineInstance().getScheduler().lock()); patcher.entity().emplace<model::DocumentManager>(patcher.document()); patcher.entity().emplace<engine::Patcher>(m_instance.useEngineInstance(), patcher); } { patcher.entity().use<engine::Patcher>().modelChanged(patcher); } notifyPatcherViews(patcher); if(patcher.removed()) { std::unique_lock<std::mutex> lock(m_instance.useEngineInstance().getScheduler().lock()); patcher.entity().erase<engine::Patcher>(); patcher.entity().erase<model::DocumentManager>(); } if(patcher.resident() && (patcher.objectsChanged() || patcher.linksChanged())) { setNeedSaving(true); updateTitleBars(); } } void PatcherManager::notifyPatcherViews(model::Patcher& patcher) { bool changed = false; for(auto& user : patcher.getUsers()) { changed = (changed || user.added() || user.removed()); if(user.getId() == m_document.user()) { for(auto& view : user.getViews()) { if(view.added()) { createPatcherWindow(patcher, user, view); } if(view.lockChanged()) { updateTitleBar(view); } notifyPatcherView(patcher, user, view); if(view.removed()) { removePatcherWindow(patcher, user, view); } } } } } void PatcherManager::updateTitleBar(model::Patcher::View & view) { PatcherViewWindow & patcher_window = view.entity().use<PatcherViewWindow>(); bool is_locked = view.getLock(); std::string title = (isConnected() ? "[Remote] " : "") + m_name + (is_locked ? "" : " (edit)"); if(juce::ComponentPeer* peer = patcher_window.getPeer()) { if (!peer->setDocumentEditedStatus(needsSaving())) if (needsSaving()) title += " *"; peer->setRepresentedFile(getSelectedFile()); } patcher_window.setName(title); } void PatcherManager::updateTitleBars() { if (getPatcher().hasSelfUser()) { flip::Collection<model::Patcher::View> & views = getPatcher().useSelfUser().getViews(); for(auto & view : views) { updateTitleBar(view); } } } void PatcherManager::setNeedSaving(bool need_saving) { m_need_saving_flag = need_saving; } void PatcherManager::setName(std::string const& name) { m_name = name; } void PatcherManager::createPatcherWindow(model::Patcher& patcher, model::Patcher::User const& user, model::Patcher::View& view) { if(user.getId() == m_document.user()) { auto& patcherview = view.entity().emplace<PatcherView>(*this, m_instance, patcher, view); view.entity().emplace<PatcherViewWindow>(*this, patcherview); updateTitleBar(view); } } void PatcherManager::notifyPatcherView(model::Patcher& patcher, model::Patcher::User const& user, model::Patcher::View& view) { if(user.getId() == m_document.user()) { // Notify PatcherView auto& patcherview = view.entity().use<PatcherView>(); patcherview.patcherChanged(patcher, view); } } void PatcherManager::removePatcherWindow(model::Patcher& patcher, model::Patcher::User const& user, model::Patcher::View& view) { if(user.getId() == m_document.user()) { view.entity().erase<PatcherView>(); view.entity().erase<PatcherViewWindow>(); } } }
24,749
C++
.cpp
603
26.829187
131
0.531082
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,359
KiwiApp_PatcherViewIoletHighlighter.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Patcher/KiwiApp_PatcherViewIoletHighlighter.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 : [email protected] ============================================================================== */ #include <KiwiApp_Patcher/KiwiApp_Objects/KiwiApp_ObjectFrame.h> #include "KiwiApp_PatcherViewIoletHighlighter.h" #include "../KiwiApp.h" namespace kiwi { // ================================================================================ // // IOLET HILIGHTER // // ================================================================================ // IoletHighlighter::IoletHighlighter(): m_text(""), m_object_name(""), m_show_tooltip_on_left(false), m_last_index(), m_object_ref() { setInterceptsMouseClicks(false, false); setAlwaysOnTop(true); setVisible(false); setBounds(0, 0, 1, 1); } void IoletHighlighter::hide() { KiwiApp::useTooltipWindow().unsetCustomTooltipClient(*this); m_text.clear(); setVisible(false); } void IoletHighlighter::paint(juce::Graphics& g) { const juce::Colour bgcolor = m_is_inlet ? juce::Colour(0xFF17BEBB) : juce::Colour(0xFFCD5334); const juce::Colour bd_color(0xFF2E282A); const juce::Rectangle<float> bounds = getLocalBounds().reduced(1).toFloat(); g.setColour(bgcolor); g.fillRect(bounds); g.setColour(bd_color); g.drawRect(bounds); } void IoletHighlighter::highlightInlet(ObjectFrame const& object, const size_t index) { highlight(object, index, true); } void IoletHighlighter::highlightOutlet(ObjectFrame const& object, const size_t index) { highlight(object, index, false); } void IoletHighlighter::highlight(ObjectFrame const& object, const size_t index, bool is_inlet) { auto const& object_model = object.getModel(); //! Only hilight if either no pin is currently hilighted //! or hilighted pin is different. if(!isVisible() || (m_object_ref != object_model.ref() || m_is_inlet != is_inlet || m_last_index != index)) { auto pos = is_inlet ? object.getInletPatcherPosition(index) : object.getOutletPatcherPosition(index); m_text = object_model.getIODescription(is_inlet, index); m_object_name = object_model.getName(); m_is_inlet = is_inlet; m_object_ref = object_model.ref(); m_last_index = index; setBounds(juce::Rectangle<int>(pos, pos).expanded(5)); setVisible(true); m_show_tooltip_on_left = m_is_inlet ? index < object_model.getNumberOfInlets() * 0.5 : index < object_model.getNumberOfOutlets() * 0.5; KiwiApp::useTooltipWindow().setCustomTooltipClient(*this); } } juce::String IoletHighlighter::getTooltip() { return m_object_name + ": " + m_text; } juce::Rectangle<int> IoletHighlighter::getTooltipBounds(juce::String const& tip, juce::Point<int> /*pos*/, juce::Rectangle<int> parent_area, int w, int h) { h += 5; w += 5; const int margin = 12; const auto pos = getScreenBounds().getCentre(); const int on_left_pos = pos.x - w - margin; int x_pos = on_left_pos; if(!m_show_tooltip_on_left || (m_show_tooltip_on_left && on_left_pos < parent_area.getX())) { x_pos = pos.x + margin; } if(x_pos + w > parent_area.getRight()) { x_pos = on_left_pos; } return juce::Rectangle<int>(x_pos, m_is_inlet ? pos.y - h - margin : pos.y + margin, w, h) .constrainedWithin(parent_area); } bool IoletHighlighter::drawTooltip(juce::Graphics& g, juce::String const& text, int width, int height) { juce::Rectangle<int> bounds(width, height); const auto corner_size = 0.f; const juce::Colour bgcolor = m_is_inlet ? juce::Colour(0xFF17BEBB) : juce::Colour(0xFFCD5334); g.setColour(bgcolor); g.fillRoundedRectangle(bounds.toFloat(), 0); g.setColour(juce::Colours::whitesmoke); g.fillRoundedRectangle(bounds.toFloat().reduced(0.5f, 0.5f), corner_size); g.setColour(bgcolor); g.drawRoundedRectangle(bounds.toFloat().reduced(0.5f, 0.5f), corner_size, 1.f); LookAndFeel::layoutTooltipText(text, juce::Colours::black) .draw(g, juce::Rectangle<float>((float) width, (float) height)); return true; } }
5,587
C++
.cpp
119
36.97479
147
0.570006
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,360
KiwiApp_PatcherView.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Patcher/KiwiApp_PatcherView.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 : [email protected] ============================================================================== */ #include <KiwiModel/KiwiModel_DataModel.h> #include <KiwiModel/KiwiModel_Factory.h> #include "KiwiApp_PatcherView.h" #include <KiwiApp_Patcher/KiwiApp_Objects/KiwiApp_ObjectView.h> #include <KiwiApp_Patcher/KiwiApp_Objects/KiwiApp_Objects.h> #include <KiwiApp_Patcher/KiwiApp_Factory.h> #include "../KiwiApp.h" #include "../KiwiApp_General/KiwiApp_CommandIDs.h" #include <KiwiModel/KiwiModel_DocumentManager.h> #include "KiwiApp_LinkView.h" #include "KiwiApp_PatcherComponent.h" namespace kiwi { // ================================================================================ // // PATCHER VIEW // // ================================================================================ // PatcherView::PatcherView(PatcherManager& manager, Instance& instance, model::Patcher& patcher, model::Patcher::View& view) : m_manager(manager) , m_instance(instance) , m_patcher_model(patcher) , m_view_model(view) , m_viewport(nullptr) , m_hittester(*this) , m_mouse_handler(*this) , m_io_highlighter() , m_lasso(*this) , m_grid_size(20) { setSize(600, 400); // default size m_viewport = std::make_unique<PatcherViewport>(*this); KiwiApp::bindToCommandManager(this); KiwiApp::bindToKeyMapping(this); setWantsKeyboardFocus(true); addChildComponent(m_io_highlighter); addChildComponent(m_lasso); loadPatcher(); useViewport().updatePatcherArea(false); m_manager.addListener(*this); } PatcherView::~PatcherView() { m_manager.removeListener(*this); removeChildComponent(&m_io_highlighter); removeChildComponent(&m_lasso); m_local_objects_selection.clear(); m_local_links_selection.clear(); m_distant_objects_selection.clear(); m_distant_links_selection.clear(); m_links.clear(); m_objects.clear(); } PatcherManager& PatcherView::usePatcherManager() { return m_manager; } PatcherViewport& PatcherView::useViewport() { return *m_viewport; } PatcherViewport const& PatcherView::useViewport() const { return *m_viewport; } // ================================================================================ // // PAINT // // ================================================================================ // void PatcherView::paint(juce::Graphics & g) { const auto bgcolor = findColour((isLocked() ? PatcherView::ColourIds::BackgroundLocked : PatcherView::ColourIds::BackgroundUnlocked)); if(!isLocked()) { const int grid_size = m_grid_size; const juce::Point<int> origin = getOriginPosition(); const juce::Rectangle<int> bounds = getLocalBounds(); const juce::Rectangle<int> clip_bounds = g.getClipBounds(); const juce::Rectangle<int> origin_bounds = bounds.withPosition(origin); if(!origin.isOrigin()) { const juce::Colour off_bgcolor = bgcolor.darker(0.1); g.setColour(off_bgcolor); g.fillRect(bounds); // draw origin g.setColour(off_bgcolor.contrasting(0.5)); if(origin.getY() != 0) { g.drawLine(origin.getX(), origin.getY(), bounds.getWidth(), origin.getY()); } if(origin.getX() != 0) { g.drawLine(origin.getX(), origin.getY(), origin.getX(), bounds.getHeight()); } } g.setColour(bgcolor); g.fillRect(origin_bounds); g.setColour(bgcolor.contrasting(0.4)); for(int x = (origin.getX() % grid_size); x < clip_bounds.getRight(); x += grid_size) { for(int y = (origin.getY() % grid_size); y < clip_bounds.getBottom(); y += grid_size) { g.fillRect(x, y, 1, 1); } } } else { g.fillAll(bgcolor); } } // ================================================================================ // // MOUSE DOWN // // ================================================================================ // void PatcherView::mouseDown(juce::MouseEvent const& e) { m_mouse_handler.handleMouseDown(e); } // ================================================================================ // // MOUSE DRAG // // ================================================================================ // void PatcherView::mouseDrag(juce::MouseEvent const& e) { m_mouse_handler.handleMouseDrag(e); } // ================================================================================ // // MOUSE UP // // ================================================================================ // void PatcherView::mouseUp(juce::MouseEvent const& e) { m_mouse_handler.handleMouseUp(e); } // ================================================================================ // // MOUSE MOVE // // ================================================================================ // void PatcherView::mouseMove(juce::MouseEvent const& event) { m_mouse_handler.handleMouseMove(event); } // ================================================================================ // // MOUSE DOUBLE CLICK // // ================================================================================ // void PatcherView::mouseDoubleClick(const juce::MouseEvent& e) { m_mouse_handler.handleMouseDoubleClick(e); } void PatcherView::showPatcherPopupMenu(juce::Point<int> const& position) { juce::PopupMenu m; auto* cm = &KiwiApp::getCommandManager(); m.addCommandItem(cm, CommandIDs::editModeSwitch); m.addSeparator(); if(!isLocked()) { m.addCommandItem(cm, juce::StandardApplicationCommandIDs::paste); m.addSeparator(); m.addCommandItem(cm, juce::StandardApplicationCommandIDs::selectAll); m.addSeparator(); } m.show(); } void PatcherView::showObjectPopupMenu(ObjectFrame const& object, juce::Point<int> const& position) { if(!isLocked()) { juce::PopupMenu m; auto* cm = &KiwiApp::getCommandManager(); m.addCommandItem(cm, CommandIDs::openObjectHelp); m.addSeparator(); m.addCommandItem(cm, juce::StandardApplicationCommandIDs::cut); m.addCommandItem(cm, juce::StandardApplicationCommandIDs::copy); m.addCommandItem(cm, juce::StandardApplicationCommandIDs::paste); m.addSeparator(); m.addCommandItem(cm, CommandIDs::pasteReplace); m.addCommandItem(cm, juce::StandardApplicationCommandIDs::del); m.addSeparator(); m.addSeparator(); m.show(); } } void PatcherView::showLinkPopupMenu(LinkView const& link, juce::Point<int> const& position) { if(!isLocked()) { juce::PopupMenu m; auto* cm = &KiwiApp::getCommandManager(); m.addCommandItem(cm, juce::StandardApplicationCommandIDs::del); m.addSeparator(); m.show(); } } // ================================================================================ // // SELECTION // // ================================================================================ // void PatcherView::moveSelectedObjects(juce::Point<int> const& delta, bool commit, bool commit_gesture) { for(auto* object : m_view_model.getSelectedObjects()) { if(object && !object->removed()) { object->setPosition(object->getX() + delta.x, object->getY() + delta.y); } } if(commit) { if(commit_gesture) { model::DocumentManager::commitGesture(m_patcher_model, "Move selected objects"); } else { model::DocumentManager::commit(m_patcher_model, "Move selected objects"); } } } std::set<flip::Ref> const& PatcherView::getSelectedObjects() const { return m_local_objects_selection; } std::set<flip::Ref> const& PatcherView::getSelectedLinks() const { return m_local_links_selection; } void PatcherView::copySelectionToClipboard() { auto& document = m_patcher_model.entity().use<model::DocumentManager>(); auto& clipboard = m_instance.getPatcherClipboardData(); clipboard.clear(); flip::StreamBinOut sbo(clipboard); std::set<flip::Ref> const& selected_objects = getSelectedObjects(); sbo << static_cast<uint32_t>(selected_objects.size()); for(flip::Ref const& object_ref : selected_objects) { model::Object const* object_ptr = document.get<model::Object>(object_ref); if(object_ptr) { flip::Mold mold(model::DataModel::use(), sbo); model::Object const& object = *object_ptr; model::Factory::copy(object, mold); mold.cure(); // store object name to restore it later from the model::Factory. sbo << object.getName(); // store object ref to find links boundaries. sbo << object_ptr->ref(); } } uint32_t number_of_links = 0; for(model::Link& link : m_patcher_model.getLinks()) { if(!link.removed()) { flip::Ref const& sender_ref = link.getSenderObject().ref(); flip::Ref const& receiver_ref = link.getReceiverObject().ref(); bool sender_selected = m_local_objects_selection.find(sender_ref) != m_local_objects_selection.end(); bool receiver_selected = m_local_objects_selection.find(receiver_ref) != m_local_objects_selection.end(); if(sender_selected && receiver_selected) { number_of_links++; } } } // Store the number of links sbo << number_of_links; for(model::Link& link : m_patcher_model.getLinks()) { if(!link.removed()) { flip::Ref const& sender_ref = link.getSenderObject().ref(); flip::Ref const& receiver_ref = link.getReceiverObject().ref(); bool sender_selected = m_local_objects_selection.find(sender_ref) != m_local_objects_selection.end(); bool receiver_selected = m_local_objects_selection.find(receiver_ref) != m_local_objects_selection.end(); if(sender_selected && receiver_selected) { uint32_t sender_index = static_cast<uint32_t>(link.getSenderIndex()); uint32_t receiver_index = static_cast<uint32_t>(link.getReceiverIndex()); sbo << sender_ref; sbo << receiver_ref; sbo << sender_index; sbo << receiver_index; } } } KiwiApp::commandStatusChanged(); } void PatcherView::pasteFromClipboard(juce::Point<int> const& delta) { auto& clipboard = m_instance.getPatcherClipboardData(); if(!clipboard.empty()) { std::vector<uint8_t> data(clipboard.begin(), clipboard.end()); flip::StreamBinIn sbi(data); unselectAll(); std::map<flip::Ref, model::Object const*> molded_objects; // paste objects: uint32_t number_of_objects; sbi >> number_of_objects; for(uint32_t i = 0; i < number_of_objects; i++) { const flip::Mold mold(model::DataModel::use(), sbi); std::string object_name; sbi >> object_name; flip::Ref old_object_ref; sbi >> old_object_ref; model::Object& new_object = m_patcher_model.addObject(object_name, mold); new_object.setPosition(new_object.getX() + delta.x, new_object.getY() + delta.y); m_view_model.selectObject(new_object); molded_objects.insert({old_object_ref, &new_object}); } // paste links: uint32_t number_of_links; sbi >> number_of_links; for(uint32_t i = 0; i < number_of_links; i++) { flip::Ref old_sender_ref, old_receiver_ref; sbi >> old_sender_ref; sbi >> old_receiver_ref; uint32_t outlet, inlet; sbi >> outlet; sbi >> inlet; const auto from_it = molded_objects.find(old_sender_ref); const auto to_it = molded_objects.find(old_receiver_ref); model::Object const* from = (from_it != molded_objects.cend()) ? from_it->second : nullptr; model::Object const* to = (to_it != molded_objects.cend()) ? to_it->second : nullptr; if(from && to) { m_patcher_model.addLink(*from, outlet, *to, inlet); } } model::DocumentManager::commit(m_patcher_model, "paste objects"); } } void PatcherView::duplicateSelection() { copySelectionToClipboard(); pasteFromClipboard({m_grid_size, m_grid_size}); } void PatcherView::cut() { copySelectionToClipboard(); deleteSelection(); } model::Object& PatcherView::replaceObjectWith(model::Object& object_to_remove, model::Object& new_object) { new_object.setPosition(object_to_remove.getX(), object_to_remove.getY()); // re-link object const size_t new_inlets = new_object.getNumberOfInlets(); const size_t new_outlets = new_object.getNumberOfOutlets(); for(model::Link& link : m_patcher_model.getLinks()) { if(!link.removed()) { const model::Object& from = link.getSenderObject(); const size_t outlet_index = link.getSenderIndex(); const model::Object& to = link.getReceiverObject(); const size_t inlet_index = link.getReceiverIndex(); if(&from == &object_to_remove) { if(outlet_index < new_outlets) { m_patcher_model.addLink(new_object, outlet_index, to, inlet_index); } } if(&to == &object_to_remove) { if(inlet_index < new_inlets) { m_patcher_model.addLink(from, outlet_index, new_object, inlet_index); } } } } m_view_model.unselectObject(object_to_remove); m_patcher_model.removeObject(object_to_remove); m_view_model.selectObject(new_object); return new_object; } void PatcherView::pasteReplace() { if(isAnyObjectSelected()) { auto& clipboard = m_instance.getPatcherClipboardData(); if(!clipboard.empty()) { std::vector<uint8_t> data(clipboard.begin(), clipboard.end()); flip::StreamBinIn sbi(data); uint32_t number_of_objects_in_clipboard; sbi >> number_of_objects_in_clipboard; std::set<flip::Ref> const& selected_objects = getSelectedObjects(); if(number_of_objects_in_clipboard == 1) { flip::Mold mold(model::DataModel::use(), sbi); auto& document = m_patcher_model.entity().use<model::DocumentManager>(); std::string new_object_name; sbi >> new_object_name; flip::Ref old_object_ref; sbi >> old_object_ref; for(auto const& obj_ref : selected_objects) { model::Object* selected_object = document.get<model::Object>(obj_ref); if(selected_object != nullptr && !selected_object->removed()) { try { model::Object& new_object = m_patcher_model.addObject(new_object_name, mold); replaceObjectWith(*selected_object, new_object); } catch(...) { KiwiApp::error("replace object failed"); } } } model::DocumentManager::commit(m_patcher_model, "paste-replace objects"); } } } } bool PatcherView::isSelected(ObjectFrame const& object) const { return m_view_model.isSelected(object.getModel()); } std::set<uint64_t> PatcherView::getDistantSelection(ObjectFrame const& object) const { std::set<uint64_t> distant_selection; if (m_distant_objects_selection.find(object.getModel().ref()) != m_distant_objects_selection.end()) { distant_selection = m_distant_objects_selection.at(object.getModel().ref()); } return distant_selection; } bool PatcherView::isSelected(LinkView const& link) const { return m_view_model.isSelected(link.getModel()); } void PatcherView::addToSelectionBasedOnModifiers(ObjectFrame& object, bool select_only) { if(select_only) { selectObjectOnly(object); } else if(isSelected(object)) { unselectObject(object); } else { selectObject(object); } } void PatcherView::addToSelectionBasedOnModifiers(LinkView& link, bool select_only) { if(select_only) { selectLinkOnly(link); } else if(isSelected(link)) { unselectLink(link); } else { selectLink(link); } } bool PatcherView::selectOnMouseDown(ObjectFrame& object, bool select_only) { if(isSelected(object)) { return true; } addToSelectionBasedOnModifiers(object, select_only); return false; } bool PatcherView::selectOnMouseDown(LinkView& link, bool select_only) { if(isSelected(link)) { return true; } addToSelectionBasedOnModifiers(link, select_only); return false; } void PatcherView::selectOnMouseUp(ObjectFrame& object, bool select_only, const bool box_was_dragged, const bool result_of_mouse_down_select_method) { if(result_of_mouse_down_select_method && ! box_was_dragged) { addToSelectionBasedOnModifiers(object, select_only); } } void PatcherView::selectOnMouseUp(LinkView& link, bool select_only, const bool box_was_dragged, const bool result_of_mouse_down_select_method) { if(result_of_mouse_down_select_method && ! box_was_dragged) { addToSelectionBasedOnModifiers(link, select_only); } } void PatcherView::bringsLinksToFront() { for(auto& link_uptr : m_links) { link_uptr->toFront(false); } } void PatcherView::bringsObjectsToFront() { for(auto& object_uptr : m_objects) { object_uptr->toFront(false); } } bool PatcherView::keyPressed(const juce::KeyPress& key) { if(m_mouse_handler.getCurrentAction() == MouseHandler::Action::MoveObjects || m_mouse_handler.getCurrentAction() == MouseHandler::Action::ResizeObjects) return false; // abort if(key.isKeyCode(juce::KeyPress::deleteKey) || key.isKeyCode(juce::KeyPress::backspaceKey)) { deleteSelection(); return true; } else if(key.isKeyCode(juce::KeyPress::returnKey)) { if(m_local_objects_selection.size() == 1) { auto& doc = m_patcher_model.entity().use<model::DocumentManager>(); model::Object* object_m = doc.get<model::Object>(*m_local_objects_selection.begin()); if(object_m) { const auto it = findObject(*object_m); if(it != m_objects.cend()) { editObject(**it); return true; } } } } else { const bool snap = key.getModifiers().isShiftDown(); const int amount = snap ? m_grid_size : 1; if(key.isKeyCode(juce::KeyPress::rightKey)) { moveSelectedObjects({amount, 0}); return true; } else if(key.isKeyCode(juce::KeyPress::downKey)) { moveSelectedObjects({0, amount}); return true; } else if(key.isKeyCode(juce::KeyPress::leftKey)) { moveSelectedObjects({-amount, 0}); return true; } else if(key.isKeyCode(juce::KeyPress::upKey)) { moveSelectedObjects({0, -amount}); return true; } } return false; } void PatcherView::loadPatcher() { // create resident objects for(auto& object : m_patcher_model.getObjects()) { if(object.resident()) { addObjectView(object); } } // create resident links for(auto& link : m_patcher_model.getLinks()) { if(link.resident()) { addLinkView(link); } } useViewport().resetObjectsArea(); } void PatcherView::setScreenBounds(juce::Rectangle<int> bounds) { if (auto* window = findParentComponentOfClass<PatcherViewWindow>()) { const auto delta = getScreenPosition() - window->getPosition(); window->setBounds(bounds.getX() - delta.getX(), bounds.getY() - delta.getY(), bounds.getWidth() + delta.getX(), bounds.getHeight() + delta.getY()); } } void PatcherView::windowInitialized() { auto const& model_screen_bounds = m_view_model.getScreenBounds(); if(model_screen_bounds.getWidth() > 0 && model_screen_bounds.getHeight() > 0) { juce::Rectangle<double> bounds { model_screen_bounds.getX(), model_screen_bounds.getY(), model_screen_bounds.getWidth(), model_screen_bounds.getHeight() }; setScreenBounds(bounds.toNearestInt()); } else { setScreenBounds(getLocalBounds().withCentre(juce::Desktop::getInstance() .getDisplays().getMainDisplay().userArea .getCentre())); } auto const& view_position = m_view_model.getViewPosition(); const juce::Point<int> view_point { static_cast<int>(view_position.getX()), static_cast<int>(view_position.getY()) }; useViewport().setZoomFactor(m_view_model.getZoomFactor()); useViewport().setRelativeViewPosition(view_point); } void PatcherView::saveState() { if(m_view_model.document().is_observing()) return; // abort const auto screen_bounds = useViewport().getScreenBounds().toDouble(); m_view_model.setScreenBounds(screen_bounds.getX(), screen_bounds.getY(), screen_bounds.getWidth(), screen_bounds.getHeight()); const auto view_position = useViewport().getRelativeViewPosition().toDouble(); m_view_model.setViewPosition(view_position.getX(), view_position.getY()); model::DocumentManager::commit(m_patcher_model); } void PatcherView::setLock(bool locked) { if(locked) { m_view_model.unselectAll(); m_io_highlighter.hide(); grabKeyboardFocus(); } m_view_model.setLock(locked); model::DocumentManager::commit(m_patcher_model); } bool PatcherView::isLocked() const { return m_is_locked; } bool PatcherView::canConnect(model::Object const& from, const size_t outlet, model::Object const& to, const size_t inlet) const { if((from.getNumberOfOutlets() > outlet) && (to.getNumberOfInlets() > inlet)) { // Check if link does not exists. const auto find_link = [&from, &outlet, &to, &inlet](std::unique_ptr<LinkView> const& link_view_uptr) { model::Link& link_m = link_view_uptr->getModel(); return (link_m.getSenderObject().ref() == from.ref() && link_m.getReceiverObject().ref() == to.ref() && link_m.getSenderIndex() == outlet && link_m.getReceiverIndex() == inlet); }; // Check if inlets and outlets types are compatible if(std::find_if(m_links.begin(), m_links.end(), find_link) == m_links.cend()) { return to.getInlet(inlet).hasType(from.getOutlet(outlet).getType()); } } return false; } std::pair<ObjectFrame*, size_t> PatcherView::getLinkCreatorNearestEndingIolet() { ObjectFrame* result_object = nullptr; size_t result_index = 0; if(m_link_creator) { const ObjectFrame& binded_object = m_link_creator->getBindedObject(); const juce::Point<int> end_pos = m_link_creator->getEndPosition(); const int max_distance = 30; int min_distance = max_distance; for(auto& object_frame_uptr : m_objects) { if(object_frame_uptr.get() != &binded_object) { model::Object const& object_m = object_frame_uptr->getModel(); const bool sender = m_link_creator->isBindedToSender(); const size_t io_size = sender ? object_m.getNumberOfInlets() : object_m.getNumberOfOutlets(); for(size_t i = 0; i < io_size; ++i) { const juce::Point<int> io_pos = sender ? object_frame_uptr->getInletPatcherPosition(i) : object_frame_uptr->getOutletPatcherPosition(i); const int distance = end_pos.getDistanceFrom(io_pos); if(min_distance > distance) { model::Object const& binded_object_m = binded_object.getModel(); model::Object const& ending_object_m = object_m; model::Object const& from = sender ? binded_object_m : ending_object_m; model::Object const& to = sender ? ending_object_m : binded_object_m; const size_t outlet = sender ? m_link_creator->getBindedIndex() : i; const size_t inlet = sender ? i : m_link_creator->getBindedIndex(); //if(m_patcher_model.canConnect(from, outlet, to, inlet)) if(canConnect(from, outlet, to, inlet)) { min_distance = distance; result_object = object_frame_uptr.get(); result_index = i; } } } } } } return std::make_pair(result_object, result_index); } juce::Rectangle<int> PatcherView::getCurrentObjectsArea() { juce::Rectangle<int> area {}; for(auto& object_m : m_patcher_model.getObjects()) { if(! object_m.removed()) { juce::Rectangle<int> object_bounds(object_m.getX(), object_m.getY(), object_m.getWidth(), object_m.getHeight()); if(object_bounds.getX() <= area.getX()) { area.setLeft(object_bounds.getX()); } if(object_bounds.getY() <= area.getY()) { area.setTop(object_bounds.getY()); } if(object_bounds.getBottom() >= area.getBottom()) { area.setBottom(object_bounds.getBottom()); } if(object_bounds.getRight() >= area.getRight()) { area.setRight(object_bounds.getRight()); } } } return area; } juce::Rectangle<int> PatcherView::getSelectionBounds() { juce::Rectangle<int> area; int counter = 0; for(auto* object_m : m_view_model.getSelectedObjects()) { counter++; if(object_m && !object_m->removed()) { juce::Rectangle<int> object_bounds(object_m->getX(), object_m->getY(), object_m->getWidth(), object_m->getHeight()); if(counter == 1) { area = object_bounds; } else { if(object_bounds.getX() < area.getX()) { area.setLeft(object_bounds.getX()); } if(object_bounds.getY() < area.getY()) { area.setTop(object_bounds.getY()); } if(object_bounds.getBottom() > area.getBottom()) { area.setBottom(object_bounds.getBottom()); } if(object_bounds.getRight() > area.getRight()) { area.setRight(object_bounds.getRight()); } } } } return area; } juce::Point<int> PatcherView::getOriginPosition() const { return useViewport().getOriginPosition(); } void PatcherView::originPositionChanged() { for(auto& jbox_uptr : m_objects) { jbox_uptr->patcherViewOriginPositionChanged(); } repaint(); } void PatcherView::zoomIn() { m_view_model.setZoomFactor(m_view_model.getZoomFactor() + 0.25); model::DocumentManager::commit(m_patcher_model); if(isAnyObjectSelected()) { useViewport().bringRectToCentre(getSelectionBounds()); } } void PatcherView::zoomNormal() { m_view_model.setZoomFactor(1.); model::DocumentManager::commit(m_patcher_model); if(isAnyObjectSelected()) { useViewport().bringRectToCentre(getSelectionBounds()); } } void PatcherView::zoomOut() { const double zoom = m_view_model.getZoomFactor(); if(zoom > 0.25) { m_view_model.setZoomFactor(zoom - 0.25); model::DocumentManager::commit(m_patcher_model); if(isAnyObjectSelected()) { useViewport().bringRectToCentre(getSelectionBounds()); } } } void PatcherView::openObjectHelp() { if(!isLocked() && isAnyObjectSelected() && m_local_objects_selection.size() == 1) { auto& doc = m_patcher_model.entity().use<model::DocumentManager>(); if(auto const* obj = doc.get<model::Object>(*m_local_objects_selection.begin())) { auto const& obj_class = obj->getClass(); auto const& classname = obj_class.getName(); auto help_file = KiwiApp::use().findHelpFile(classname); if(help_file.existsAsFile()) { KiwiApp::useInstance().openFile(help_file); } else { KiwiApp::error("can't find " + classname + " help file"); } } } } void PatcherView::connectedUserChanged(PatcherManager& manager) { if(&m_manager == &manager) { auto& patcher = manager.getPatcher(); checkObjectsSelectionChanges(patcher); checkLinksSelectionChanges(patcher); } } // ================================================================================ // // OBSERVER // // ================================================================================ // void PatcherView::patcherChanged(model::Patcher& patcher, model::Patcher::View& view) { if(! patcher.changed()) return; // abort if(view.added()) {} // create ObjectView for each newly added objects int object_zorder = -1; for(auto& object : patcher.getObjects()) { object_zorder++; if(object.added()) { addObjectView(object, object_zorder); } } // create LinkView for each newly added links for(auto& link : patcher.getLinks()) { if(link.added()) { addLinkView(link); } } bool patcher_area_uptodate = false; // update parameters before updating bounds // (ie text objects adapt their sizes depending on the size) updateParameters(patcher); // send ObjectView change notification for(auto& object : patcher.getObjects()) { if(object.changed()) { if(object.boundsChanged() && !patcher_area_uptodate && !view.removed() && m_mouse_handler.getCurrentAction() != MouseHandler::Action::MoveObjects && m_mouse_handler.getCurrentAction() != MouseHandler::Action::ResizeObjects) { useViewport().updatePatcherArea(true); patcher_area_uptodate = true; } objectChanged(view, object); } } // send LinkView change notification for(auto& link : patcher.getLinks()) { if(link.changed()) { linkChanged(link); } // send to LinkView ObjectView change notification if(patcher.objectsChanged()) { for(auto& object : patcher.getObjects()) { if(object.changed()) { LinkView* link_view = getLink(link); if(link_view) { link_view->objectChanged(object); } } } } } if(!view.removed() && &view == &m_view_model) { checkViewInfos(view); checkObjectsSelectionChanges(patcher); checkLinksSelectionChanges(patcher); } // delete LinkView for each removed links for(auto& link : patcher.getLinks()) { if(link.removed()) { removeLinkView(link); } } // delete ObjectView for each removed objects for(auto& object : patcher.getObjects()) { if(object.removed()) { // remove link_creator if binded object has been removed. if(m_link_creator) { model::Object const& binded_object = m_link_creator->getBindedObject().getModel(); if(&binded_object == &object) { removeChildComponent(m_link_creator.get()); m_link_creator.reset(); m_io_highlighter.hide(); } } removeObjectView(object); } } checkViewInfos(view); if(view.removed()) {} } void PatcherView::updateParameters(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(); auto object_frame = findObject(object); for (std::string const& param_name : changed_params) { (*object_frame)->attributeChanged(param_name, object.getAttribute(param_name)); } } } } } void PatcherView::checkViewInfos(model::Patcher::View& view) { if(&view == &m_view_model && !view.removed()) { const bool was_locked = m_is_locked; m_is_locked = view.getLock(); if(was_locked != m_is_locked) { m_is_locked ? bringsObjectsToFront() : bringsLinksToFront(); for(auto& object : m_objects) { object->lockStatusChanged(); } if(m_is_locked) { useViewport().resetObjectsArea(); } repaint(); KiwiApp::commandStatusChanged(); } if(m_view_model.zoomFactorChanged()) { const double zoom = m_view_model.getZoomFactor(); useViewport().setZoomFactor(zoom); } } } void PatcherView::checkObjectsSelectionChanges(model::Patcher& patcher) { const auto connected_users = m_manager.getConnectedUsers(); std::set<flip::Ref> new_local_objects_selection; std::map<flip::Ref, std::set<uint64_t>> new_distant_objects_selection; for(auto& object_m : patcher.getObjects()) { if(!object_m.removed()) { std::set<uint64_t> selected_for_users; for(auto& user : patcher.getUsers()) { bool selected_for_local_view = false; bool selected_for_other_view = false; const uint64_t user_id = user.getId(); const bool is_distant_user = user_id != m_instance.getUserId(); const bool is_connected = (connected_users.find(user_id) != connected_users.end()); if(is_distant_user && !is_connected) { continue; } for(auto& view : user.getViews()) { const bool is_local_view = (&m_view_model == &view); const bool is_selected = view.isSelected(object_m); if(is_selected) { if(is_distant_user) { selected_for_other_view = true; // an object is considered selected for a given user // when it's selected in at least one of its patcher's views. break; } else if(is_local_view) { selected_for_local_view = true; } else { selected_for_other_view = true; } } } if(selected_for_local_view) { new_local_objects_selection.emplace(object_m.ref()); } if(selected_for_other_view) { selected_for_users.emplace(user_id); } } new_distant_objects_selection.insert({object_m.ref(), selected_for_users}); } } std::set<ObjectFrame*> updated_objects; // check diff between old and new distant selection // and notify objects if their selection state changed for(auto& local_object_uptr : m_objects) { model::Object const& local_object_m = local_object_uptr->getModel(); // local diff const bool old_local_selected_state = m_local_objects_selection.find(local_object_m.ref()) != m_local_objects_selection.end(); bool new_local_selected_state = new_local_objects_selection.find(local_object_m.ref()) != new_local_objects_selection.end(); if(old_local_selected_state != new_local_selected_state) { updated_objects.insert(local_object_uptr.get()); selectionChanged(); } // distant diff bool distant_selection_changed_for_object = false; for(auto distant_it : new_distant_objects_selection) { flip::Ref const& distant_object_lookup_ref = distant_it.first; if(distant_object_lookup_ref == local_object_uptr->getModel().ref()) { distant_selection_changed_for_object = m_distant_objects_selection[distant_object_lookup_ref] != distant_it.second; // notify object if(distant_selection_changed_for_object) { updated_objects.insert(local_object_uptr.get()); selectionChanged(); } } } } // cache new selection state std::swap(m_distant_objects_selection, new_distant_objects_selection); std::swap(m_local_objects_selection, new_local_objects_selection); // call objects reaction. for(auto object_frame : updated_objects) { object_frame->selectionChanged(); } } void PatcherView::checkLinksSelectionChanges(model::Patcher& patcher) { const auto connected_users = m_manager.getConnectedUsers(); std::set<flip::Ref> new_local_links_selection; std::map<flip::Ref, std::set<uint64_t>> new_distant_links_selection; for(auto& link_m : patcher.getLinks()) { if(link_m.removed()) break; std::set<uint64_t> selected_for_users; for(auto& user : patcher.getUsers()) { bool selected_for_local_view = false; bool selected_for_other_view = false; const uint64_t user_id = user.getId(); const bool is_distant_user = user_id != m_instance.getUserId(); const bool is_connected = (connected_users.find(user_id) != connected_users.end()); if(is_distant_user && !is_connected) { continue; } for(auto& view : user.getViews()) { const bool is_local_view = (&m_view_model == &view); const bool is_selected = view.isSelected(link_m); if(is_selected) { if(is_distant_user) { selected_for_other_view = true; // a link is considered selected for a given user // when it's selected in at least one of its patcher's views. break; } else if(is_local_view) { selected_for_local_view = true; } else { selected_for_other_view = true; } } } if(selected_for_local_view) { new_local_links_selection.emplace(link_m.ref()); } if(selected_for_other_view) { selected_for_users.emplace(user_id); } } new_distant_links_selection.insert({link_m.ref(), selected_for_users}); } // check diff between old and new distant selection // and notify links if their selection state changed for(auto& local_link_uptr : m_links) { model::Link const& local_link_m = local_link_uptr->getModel(); // local diff const bool old_local_selected_state = m_local_links_selection.find(local_link_m.ref()) != m_local_links_selection.end(); bool new_local_selected_state = new_local_links_selection.find(local_link_m.ref()) != new_local_links_selection.end(); if(old_local_selected_state != new_local_selected_state) { local_link_uptr->localSelectionChanged(new_local_selected_state); selectionChanged(); } // distant diff bool distant_selection_changed_for_link = false; for(auto distant_it : new_distant_links_selection) { flip::Ref const& distant_link_lookup_ref = distant_it.first; if(distant_link_lookup_ref == local_link_uptr->getModel().ref()) { distant_selection_changed_for_link = m_distant_links_selection[distant_link_lookup_ref] != distant_it.second; // notify link if(distant_selection_changed_for_link) { local_link_uptr->distantSelectionChanged(distant_it.second); selectionChanged(); } } } } // cache new selection state std::swap(m_distant_links_selection, new_distant_links_selection); std::swap(m_local_links_selection, new_local_links_selection); } void PatcherView::selectionChanged() { KiwiApp::commandStatusChanged(); } void PatcherView::addObjectView(model::Object& object, int zorder) { const auto it = findObject(object); if(it == m_objects.cend()) { const auto it = (zorder > 0) ? m_objects.begin() + zorder : m_objects.end(); auto of = std::make_unique<ObjectFrame>(*this, Factory::createObjectView(object)); auto& object_frame = **(m_objects.emplace(it, std::move(of))); addAndMakeVisible(object_frame, zorder); } } void PatcherView::objectChanged(model::Patcher::View& view, model::Object& object) { const auto it = findObject(object); if(it != m_objects.cend()) { ObjectFrame& object_view = *it->get(); object_view.objectChanged(view, object); } } void PatcherView::removeObjectView(model::Object& object) { const auto it = findObject(object); if(it != m_objects.cend()) { ObjectFrame* object_view = it->get(); if(m_hittester.getObject() == object_view) { // reset hittester to prevent functions like mouseUp() to get an invalid ptr. m_hittester.reset(); } juce::ComponentAnimator& animator = juce::Desktop::getInstance().getAnimator(); animator.animateComponent(object_view, object_view->getBounds(), 0., 200., true, 0.8, 1.); removeChildComponent(object_view); m_objects.erase(it); } } void PatcherView::addLinkView(model::Link& link) { const auto it = findLink(link); if(it == m_links.cend()) { auto result = m_links.emplace(m_links.end(), new LinkView(*this, link)); LinkView& link_view = *result->get(); addAndMakeVisible(link_view); } } void PatcherView::linkChanged(model::Link& link) { const auto it = findLink(link); if(it != m_links.cend()) { LinkView& link_view = *it->get(); link_view.linkChanged(link); } } void PatcherView::removeLinkView(model::Link& link) { const auto it = findLink(link); if(it != m_links.cend()) { removeChildComponent(it->get()); m_links.erase(it); } } PatcherView::ObjectFrames::iterator PatcherView::findObject(model::Object const& object) { const auto find_jobj = [&object](std::unique_ptr<ObjectFrame> const& jobj) { return (&object == &jobj->getModel()); }; return std::find_if(m_objects.begin(), m_objects.end(), find_jobj); } PatcherView::LinkViews::iterator PatcherView::findLink(model::Link const& link) { const auto find_link_view = [&link](std::unique_ptr<LinkView> const& link_view) { return (&link == &link_view->getModel()); }; return std::find_if(m_links.begin(), m_links.end(), find_link_view); } model::Patcher::View& PatcherView::getPatcherViewModel() { return m_view_model; } PatcherView::ObjectFrames const& PatcherView::getObjects() const { return m_objects; } PatcherView::LinkViews const& PatcherView::getLinks() const { return m_links; } ObjectFrame* PatcherView::getObject(model::Object const& object) { const auto it = findObject(object); return (it != m_objects.cend()) ? it->get() : nullptr; } LinkView* PatcherView::getLink(model::Link const& link) { const auto it = findLink(link); return (it != m_links.cend()) ? it->get() : nullptr; } // ================================================================================ // // COMMANDS ACTIONS // // ================================================================================ // bool PatcherView::isEditingObject() const { return m_box_being_edited != nullptr; } void PatcherView::editObject(ObjectFrame & object_frame) { assert(!isEditingObject() && "Editing two objects simultaneously"); object_frame.editObject(); } void PatcherView::objectEditorShown(ObjectFrame const& object_frame) { m_box_being_edited = &object_frame; KiwiApp::commandStatusChanged(); } void PatcherView::objectEditorHidden(ObjectFrame const& object_frame) { assert(m_box_being_edited == &object_frame && "Calling object editor shown outside text edition"); m_box_being_edited = nullptr; KiwiApp::commandStatusChanged(); } void PatcherView::objectTextChanged(ObjectFrame const& object_frame, std::string const& new_text) { model::Object & old_model = object_frame.getModel(); std::vector<tool::Atom> atoms = tool::AtomHelper::parse(new_text); auto object_model = model::Factory::create(atoms); auto origin = getOriginPosition(); auto box_bounds = object_frame.getObjectBounds(); object_model->setPosition(box_bounds.getX() - origin.x, box_bounds.getY() - origin.y); // handle error box case if(object_model->getName() == "errorbox") { model::ErrorBox& error_box = dynamic_cast<model::ErrorBox&>(*object_model); error_box.setInlets(old_model.getInlets()); error_box.setOutlets(old_model.getOutlets()); KiwiApp::error(error_box.getError()); } if (!object_model->hasFlag(model::ObjectClass::Flag::DefinedSize)) { // TODO: we should fetch these values dynamically : const int object_text_padding = 3; const juce::Font object_font = juce::Font(15); const int text_width = object_font.getStringWidth(new_text) + object_text_padding*2; const int max_io = std::max(object_model->getNumberOfInlets(), object_model->getNumberOfOutlets()) * 14; object_model->setWidth(std::max(text_width, max_io)); object_model->setHeight(box_bounds.getHeight()); } model::Object & new_object = m_patcher_model.replaceObject(old_model, std::move(object_model)); m_view_model.unselectObject(old_model); if(!isLocked()) { m_view_model.selectObject(new_object); } model::DocumentManager::commit(m_patcher_model, "Edit Object"); } void PatcherView::createObjectModel(std::string const& text, bool give_focus) { if(model::DocumentManager::isInCommitGesture(m_patcher_model)) return; std::unique_ptr<model::Object> new_object = model::Factory::create(tool::AtomHelper::parse(text)); juce::Point<int> pos = getMouseXYRelative() - getOriginPosition(); auto& doc = m_patcher_model.entity().use<model::DocumentManager>(); new_object->setPosition(pos.x, pos.y); auto& obj = m_patcher_model.addObject(std::move(new_object)); const bool linked_newbox = m_local_objects_selection.size() == 1; if(linked_newbox) { if(auto* selobj = doc.get<model::Object>(*m_local_objects_selection.begin())) { if(selobj->getNumberOfOutlets() >= 1) { obj.setPosition(selobj->getX(), selobj->getY() + selobj->getHeight() + m_grid_size); m_patcher_model.addLink(*selobj, 0, obj, 0); } } } m_view_model.unselectAll(); m_view_model.selectObject(obj); std::string commit_message = ("Insert \"" + obj.getName() + "\""); model::DocumentManager::commit(m_patcher_model, commit_message); if(give_focus && m_local_objects_selection.size() == 1) { model::Object* object_m = doc.get<model::Object>(*m_local_objects_selection.begin()); if(object_m) { const auto it = findObject(*object_m); if(it != m_objects.cend()) { editObject(**it); } } } } // ================================================================================ // // UNDO/REDO // // ================================================================================ // void PatcherView::undo() { auto& doc = m_patcher_model.entity().use<model::DocumentManager>(); if(doc.canUndo()) { doc.undo(); doc.commit(m_patcher_model); } } bool PatcherView::canUndo() { return m_patcher_model.entity().use<model::DocumentManager>().canUndo(); } std::string PatcherView::getUndoLabel() { auto& doc = m_patcher_model.entity().use<model::DocumentManager>(); return doc.canUndo() ? doc.getUndoLabel() : ""; } void PatcherView::redo() { auto& doc = m_patcher_model.entity().use<model::DocumentManager>(); if(doc.canRedo()) { doc.redo(); doc.commit(m_patcher_model); } } bool PatcherView::canRedo() { return m_patcher_model.entity().use<model::DocumentManager>().canRedo(); } std::string PatcherView::getRedoLabel() { auto& doc = m_patcher_model.entity().use<model::DocumentManager>(); return doc.canRedo() ? doc.getRedoLabel() : ""; } // ================================================================================ // // SELECTION // // ================================================================================ // bool PatcherView::isAnythingSelected() { return isAnyObjectSelected() || isAnyLinksSelected(); } bool PatcherView::isAnyObjectSelected() { return !m_local_objects_selection.empty(); } bool PatcherView::isAnyLinksSelected() { return !m_local_links_selection.empty(); } void PatcherView::selectObject(ObjectFrame& object) { m_view_model.selectObject(object.getModel()); model::DocumentManager::commit(m_patcher_model); } void PatcherView::selectObjects(std::vector<ObjectFrame*> const& objects) { bool should_commit = false; for(ObjectFrame* object : objects) { if(object != nullptr) { m_view_model.selectObject(object->getModel()); should_commit = true; } } if(should_commit) { model::DocumentManager::commit(m_patcher_model); } } void PatcherView::selectLink(LinkView& link) { m_view_model.selectLink(link.getModel()); model::DocumentManager::commit(m_patcher_model); } void PatcherView::selectLinks(std::vector<LinkView*> const& links) { bool should_commit = false; for(LinkView* link : links) { if(link != nullptr) { m_view_model.selectLink(link->getModel()); should_commit = true; } } if(should_commit) { model::DocumentManager::commit(m_patcher_model); } } void PatcherView::unselectObject(ObjectFrame& object) { m_view_model.unselectObject(object.getModel()); model::DocumentManager::commit(m_patcher_model); } void PatcherView::unselectLink(LinkView& link) { m_view_model.unselectLink(link.getModel()); model::DocumentManager::commit(m_patcher_model); } void PatcherView::selectObjectOnly(ObjectFrame& object) { unselectAll(); selectObject(object); model::DocumentManager::commit(m_patcher_model); } void PatcherView::selectLinkOnly(LinkView& link) { unselectAll(); selectLink(link); model::DocumentManager::commit(m_patcher_model); } void PatcherView::selectAllObjects() { m_view_model.selectAll(); model::DocumentManager::commit(m_patcher_model); } void PatcherView::unselectAll() { if(!model::DocumentManager::isInCommitGesture(m_patcher_model)) { m_view_model.unselectAll(); model::DocumentManager::commit(m_patcher_model); } } void PatcherView::deleteSelection() { for(model::Link* link : m_view_model.getSelectedLinks()) { if(link) { m_patcher_model.removeLink(*link, &m_view_model); } } for(model::Object* object : m_view_model.getSelectedObjects()) { if(object) { m_patcher_model.removeObject(*object, &m_view_model); } } model::DocumentManager::commit(m_patcher_model, "Delete objects and links"); useViewport().updatePatcherArea(false); } // ================================================================================ // // APPLICATION COMMAND TARGET // // ================================================================================ // juce::ApplicationCommandTarget* PatcherView::getNextCommandTarget() { return findFirstTargetParentComponent(); } void PatcherView::getAllCommands(juce::Array<juce::CommandID>& commands) { commands.add(CommandIDs::save); commands.add(CommandIDs::saveAs); commands.add(CommandIDs::newPatcherView); commands.add(juce::StandardApplicationCommandIDs::undo); commands.add(juce::StandardApplicationCommandIDs::redo); commands.add(juce::StandardApplicationCommandIDs::cut); commands.add(juce::StandardApplicationCommandIDs::copy); commands.add(juce::StandardApplicationCommandIDs::paste); commands.add(CommandIDs::pasteReplace); commands.add(CommandIDs::duplicate); commands.add(juce::StandardApplicationCommandIDs::del); commands.add(juce::StandardApplicationCommandIDs::selectAll); commands.add(CommandIDs::newBox); commands.add(CommandIDs::newBang); commands.add(CommandIDs::newToggle); commands.add(CommandIDs::newSlider); commands.add(CommandIDs::newMessage); commands.add(CommandIDs::newComment); commands.add(CommandIDs::newNumber); commands.add(CommandIDs::zoomIn); commands.add(CommandIDs::zoomOut); commands.add(CommandIDs::zoomNormal); commands.add(CommandIDs::editModeSwitch); commands.add(CommandIDs::openObjectHelp); } void PatcherView::getCommandInfo(const juce::CommandID commandID, juce::ApplicationCommandInfo& result) { const bool is_not_in_gesture = !model::DocumentManager::isInCommitGesture(m_patcher_model); switch(commandID) { case CommandIDs::save: { result.setInfo(TRANS("Save"), TRANS("Save"), CommandCategories::general, 0); result.addDefaultKeypress('s', juce::ModifierKeys::commandModifier); result.setActive(!m_manager.isConnected()); break; } case CommandIDs::saveAs: { result.setInfo(TRANS("Save As.."), TRANS("Save As.."), CommandCategories::general, 0); result.addDefaultKeypress('s', juce::ModifierKeys::commandModifier | juce::ModifierKeys::shiftModifier); result.setActive(!m_manager.isConnected()); break; } case CommandIDs::newPatcherView: { result.setInfo(TRANS("New View"), TRANS("New Patcher View"), CommandCategories::view, 0); result.addDefaultKeypress('n', juce::ModifierKeys::commandModifier | juce::ModifierKeys::shiftModifier); break; } case juce::StandardApplicationCommandIDs::undo: { juce::String label = TRANS("Undo"); const bool hasUndo = canUndo(); if(hasUndo) { label += juce::String(" ") + getUndoLabel(); } result.setInfo(label, TRANS("Undo last action"), CommandCategories::general, 0); result.addDefaultKeypress('z', juce::ModifierKeys::commandModifier); result.setActive(!isLocked() && hasUndo); break; } case juce::StandardApplicationCommandIDs::redo: { juce::String label = TRANS("Redo"); const bool hasRedo = canRedo(); if(hasRedo) { label += juce::String(" ") + getRedoLabel(); } result.setInfo(label, TRANS("Redo action"), CommandCategories::general, 0); result.addDefaultKeypress('z', juce::ModifierKeys::commandModifier | juce::ModifierKeys::shiftModifier); result.setActive(!isLocked() && hasRedo); break; } case juce::StandardApplicationCommandIDs::cut: { result.setInfo(TRANS("Cut"), TRANS("Cut"), CommandCategories::editing, 0); result.addDefaultKeypress('x', juce::ModifierKeys::commandModifier); result.setActive(!isLocked() && isAnyObjectSelected()); break; } case juce::StandardApplicationCommandIDs::copy: { result.setInfo(TRANS("Copy"), TRANS("Copy"), CommandCategories::editing, 0); result.addDefaultKeypress('c', juce::ModifierKeys::commandModifier); result.setActive(!isLocked() && isAnyObjectSelected()); break; } case juce::StandardApplicationCommandIDs::paste: { result.setInfo(TRANS("Paste"), TRANS("Paste"), CommandCategories::editing, 0); result.addDefaultKeypress('v', juce::ModifierKeys::commandModifier); result.setActive(!isLocked() && !m_instance.getPatcherClipboardData().empty()); break; } case CommandIDs::pasteReplace: { result.setInfo(TRANS("Paste replace"), TRANS("Replace selected objects with the object on the clipboard"), CommandCategories::editing, 0); result.addDefaultKeypress('v', juce::ModifierKeys::commandModifier | juce::ModifierKeys::altModifier); result.setActive(!isLocked() && isAnyObjectSelected() && !m_instance.getPatcherClipboardData().empty()); break; } case CommandIDs::duplicate: { result.setInfo(TRANS("Duplicate"), TRANS("Duplicate the selection"), CommandCategories::editing, 0); result.addDefaultKeypress('d', juce::ModifierKeys::commandModifier); result.setActive(!isLocked() && isAnyObjectSelected()); break; } case juce::StandardApplicationCommandIDs::del: { result.setInfo(TRANS("Delete"), TRANS("Delete all selected objects and links"), CommandCategories::editing, 0); result.addDefaultKeypress(juce::KeyPress::backspaceKey, juce::ModifierKeys::noModifiers); result.setActive(!isLocked() && isAnythingSelected()); break; } case juce::StandardApplicationCommandIDs::selectAll: { result.setInfo(TRANS("Select All"), TRANS("Select all boxes and links"), CommandCategories::editing, 0); result.addDefaultKeypress('a', juce::ModifierKeys::commandModifier); result.setActive(!isLocked()); break; } case CommandIDs::newBox: { result.setInfo(TRANS("New Object Box"), TRANS("Add a new object box"), CommandCategories::editing, 0); result.addDefaultKeypress('n', juce::ModifierKeys::noModifiers); result.setActive(!isLocked()); break; } case CommandIDs::newBang: { result.setInfo(TRANS("New Bang Box"), TRANS("Add a new bang"), CommandCategories::editing, 0); result.addDefaultKeypress('b', juce::ModifierKeys::noModifiers); result.setActive(!isLocked()); break; } case CommandIDs::newToggle: { result.setInfo(TRANS("New Toggle Box"), TRANS("Add a new toggle"), CommandCategories::editing, 0); result.addDefaultKeypress('t', juce::ModifierKeys::noModifiers); result.setActive(!isLocked()); break; } case CommandIDs::newSlider: { result.setInfo(TRANS("New Slider Box"), TRANS("Add a new slider"), CommandCategories::editing, 0); result.addDefaultKeypress('s', juce::ModifierKeys::noModifiers); result.setActive(!isLocked()); break; } case CommandIDs::newNumber: { result.setInfo(TRANS("New Number Box"), TRANS("Add a new number"), CommandCategories::editing, 0); result.addDefaultKeypress('f', juce::ModifierKeys::noModifiers); result.addDefaultKeypress('i', juce::ModifierKeys::noModifiers); result.setActive(!isLocked()); break; } case CommandIDs::newComment: { result.setInfo(TRANS("New Comment Box"), TRANS("Add a new comment"), CommandCategories::editing, 0); result.addDefaultKeypress('c', juce::ModifierKeys::noModifiers); result.setActive(!isLocked()); break; } case CommandIDs::newMessage: { result.setInfo(TRANS("New Message Box"), TRANS("Add a new message box"), CommandCategories::editing, 0); result.addDefaultKeypress('m', juce::ModifierKeys::noModifiers); result.setActive(!isLocked()); break; } case CommandIDs::zoomIn: { result.setInfo(TRANS("Zoom in"), TRANS("Zoom in"), CommandCategories::view, 0); result.addDefaultKeypress('=', juce::ModifierKeys::commandModifier); break; } case CommandIDs::zoomOut: { result.setInfo(TRANS("Zoom out"), TRANS("Zoom out"), CommandCategories::view, 0); result.addDefaultKeypress('-', juce::ModifierKeys::commandModifier); break; } case CommandIDs::zoomNormal: { result.setInfo(TRANS("Zoom at 100%"), TRANS("Zoom reset"), CommandCategories::view, 0); result.addDefaultKeypress('1', juce::ModifierKeys::commandModifier | juce::ModifierKeys::shiftModifier); break; } case CommandIDs::editModeSwitch: { result.setInfo(TRANS("Edit"), TRANS("Switch between edit and perform mode"), CommandCategories::view, 0); result.addDefaultKeypress ('e', juce::ModifierKeys::commandModifier); result.setTicked(!m_view_model.getLock()); break; } case CommandIDs::openObjectHelp: { const bool active = (!isLocked() && m_local_objects_selection.size() == 1 && KiwiApp::use().getKiwiObjectHelpDirectory().exists()); auto text = TRANS("Help"); if(active) { auto& doc = m_patcher_model.entity().use<model::DocumentManager>(); if(auto const* obj = doc.get<model::Object>(*m_local_objects_selection.begin())) { auto const& obj_class = obj->getClass(); text = "Open " + obj_class.getName() + " Help"; } } result.setInfo(text, TRANS("Open object help patch"), CommandCategories::view, 0); auto modifier = juce::ModifierKeys::commandModifier | juce::ModifierKeys::shiftModifier; result.addDefaultKeypress ('h', modifier); result.setActive(active); break; } default: { assert(true && "Command not handled !"); break; } } result.setActive(!(result.flags & juce::ApplicationCommandInfo::isDisabled) && is_not_in_gesture && !isEditingObject()); } bool PatcherView::perform(const InvocationInfo& info) { // most of the commands below generate conflicts when they are being executed // in a commit gesture or when a box is being edited, so simply not execute them. if(model::DocumentManager::isInCommitGesture(m_patcher_model) || isEditingObject()) { return true; } switch (info.commandID) { case CommandIDs::save: { m_manager.saveDocument(false); break; } case CommandIDs::saveAs: { m_manager.saveDocument(true); break; } case CommandIDs::newPatcherView: { m_manager.newView(); break; } case juce::StandardApplicationCommandIDs::undo: { undo(); break; } case juce::StandardApplicationCommandIDs::redo: { redo(); break; } case juce::StandardApplicationCommandIDs::cut: { cut(); break; } case juce::StandardApplicationCommandIDs::copy: { copySelectionToClipboard(); break; } case juce::StandardApplicationCommandIDs::paste: { pasteFromClipboard({m_grid_size , m_grid_size}); break; } case CommandIDs::pasteReplace: { pasteReplace(); break; } case CommandIDs::duplicate: { duplicateSelection(); break; } case juce::StandardApplicationCommandIDs::del: { deleteSelection(); break; } case juce::StandardApplicationCommandIDs::selectAll:{ selectAllObjects(); break; } case CommandIDs::newBox: { createObjectModel("", true); break; } case CommandIDs::newBang: { createObjectModel("bang", false); break; } case CommandIDs::newToggle: { createObjectModel("toggle", false); break; } case CommandIDs::newNumber: { createObjectModel("number", false); break; } case CommandIDs::newSlider: { createObjectModel("slider", false); break; } case CommandIDs::newComment: { createObjectModel("comment", true); break; } case CommandIDs::newMessage: { createObjectModel("message", true); break; } case CommandIDs::zoomIn: { zoomIn(); break; } case CommandIDs::zoomOut: { zoomOut(); break; } case CommandIDs::zoomNormal: { zoomNormal(); break; } case CommandIDs::editModeSwitch: { setLock(!isLocked()); break; } case CommandIDs::openObjectHelp: { openObjectHelp(); break; } default: return false; } return true; } }
84,120
C++
.cpp
1,840
29.433152
161
0.495256
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,361
KiwiApp_LinkView.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Patcher/KiwiApp_LinkView.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 : [email protected] ============================================================================== */ #include "../KiwiApp.h" #include "KiwiApp_LinkView.h" #include "KiwiApp_PatcherView.h" namespace kiwi { // ================================================================================ // // LINK VIEW BASE // // ================================================================================ // void LinkViewBase::updateBounds() { const auto inlet = m_last_inlet_pos; const auto outlet = m_last_outlet_pos; const juce::Rectangle<int> link_bounds(outlet, inlet); juce::Point<float> start = outlet.translated(0.f, 2.f).toFloat(); juce::Point<float> end = inlet.translated(0.f, -1.f).toFloat(); juce::Path path; if(link_bounds.getWidth() == 0) { path.startNewSubPath(start.x, start.y); path.lineTo(end.x, end.y); } else { const float width = link_bounds.getWidth(); const float height = link_bounds.getHeight(); const float min = std::min<float>(width, height); const float max = std::max<float>(width, height); const float max_shift_y = 20.f; const float max_shift_x = 20.f; const float shift_y = std::min<float>(max_shift_y, max * 0.5); const float shift_x = ((start.y >= end.y) ? std::min<float>(max_shift_x, min * 0.5) : 0.f) * ((start.x < end.x) ? -1. : 1.); const juce::Point<float> ctrl_pt1 { start.x - shift_x, start.y + shift_y }; const juce::Point<float> ctrl_pt2 { end.x + shift_x, end.y - shift_y }; path.startNewSubPath(start); path.cubicTo(ctrl_pt1, ctrl_pt2, end); } setBounds(path.getBounds().toNearestInt().expanded(2, 2)); path.applyTransform(juce::AffineTransform::translation(-1 * getX(), -1 * getY())); m_path = path; } // ================================================================================ // // LINK VIEW // // ================================================================================ // LinkView::LinkView(PatcherView& patcherview, model::Link& link_m) : m_patcherview(patcherview) , m_model(&link_m) { auto& sender_object_m = m_model->getSenderObject(); auto& receiver_object_m = m_model->getReceiverObject(); ObjectFrame* jbox_sender = m_patcherview.getObject(sender_object_m); ObjectFrame* jbox_receiver = m_patcherview.getObject(receiver_object_m); if(jbox_sender && jbox_receiver) { m_last_outlet_pos = jbox_sender->getOutletPatcherPosition(m_model->getSenderIndex()); m_last_inlet_pos = jbox_receiver->getInletPatcherPosition(m_model->getReceiverIndex()); jbox_sender->addComponentListener(this); jbox_receiver->addComponentListener(this); updateBounds(); } setInterceptsMouseClicks(false, false); } LinkView::~LinkView() { auto& sender_object_m = m_model->getSenderObject(); ObjectFrame* jbox_sender = m_patcherview.getObject(sender_object_m); if(jbox_sender) { jbox_sender->removeComponentListener(this); } auto& receiver_object_m = m_model->getReceiverObject(); ObjectFrame* jbox_receiver = m_patcherview.getObject(receiver_object_m); if(jbox_receiver) { jbox_receiver->removeComponentListener(this); } } model::Link& LinkView::getModel() const { return *m_model; } bool LinkView::isSelected() const noexcept { return m_selected.on_this_view; } void LinkView::linkChanged(model::Link& link) { ; } void LinkView::objectChanged(model::Object& object) { ; } void LinkView::localSelectionChanged(bool selected) { if(m_selected.on_this_view != selected) { m_selected.on_this_view = selected; repaint(); } } void LinkView::distantSelectionChanged(std::set<uint64_t> distant_user_id_selection) { const bool was_selected_in_another_view = m_selected.in_another_view; const bool was_selected_by_another_user = m_selected.by_another_user; bool should_repaint = false; if(distant_user_id_selection.empty()) { should_repaint = (was_selected_in_another_view || was_selected_by_another_user); m_selected.in_another_view = false; m_selected.by_another_user = false; } else { const auto user_id = KiwiApp::userID(); for(auto distant_user_id : distant_user_id_selection) { if(distant_user_id == user_id) { m_selected.in_another_view = true; } else { m_selected.by_another_user = true; } if(m_selected.in_another_view && m_selected.by_another_user) { break; } } should_repaint = ((was_selected_in_another_view != m_selected.in_another_view) || (was_selected_in_another_view != m_selected.by_another_user)); } if(should_repaint) { repaint(); } } void LinkView::componentMovedOrResized(Component& component, bool /*was_moved*/, bool /*was_resized*/) { if(auto* box = dynamic_cast<ObjectFrame*>(&component)) { if(&box->getModel() == &m_model->getSenderObject()) { m_last_outlet_pos = box->getOutletPatcherPosition(m_model->getSenderIndex()); updateBounds(); } else if(&box->getModel() == &m_model->getReceiverObject()) { m_last_inlet_pos = box->getInletPatcherPosition(m_model->getReceiverIndex()); updateBounds(); } } } bool LinkView::isSignal() const { return m_model->isSignal(); } void LinkView::paint(juce::Graphics & g) { const bool selected_by_other = (m_selected.by_another_user || m_selected.in_another_view); const float stroke = (isSignal() ? 2.f : 1.5f); juce::Colour bgcolor; if(m_selected.on_this_view) { bgcolor = findColour(PatcherView::ColourIds::Selection); } else if (m_selected.by_another_user) { bgcolor = findColour(PatcherView::ColourIds::SelectionOtherUser); } else if (m_selected.in_another_view) { bgcolor = findColour(PatcherView::ColourIds::SelectionOtherView); } else { bgcolor = findColour(isSignal() ? LinkView::ColourIds::SignalBackground : LinkView::ColourIds::ControlBackground); } g.setColour(bgcolor); g.strokePath(m_path, juce::PathStrokeType(stroke)); if(m_selected.on_this_view && selected_by_other) { g.setColour(findColour(m_selected.by_another_user ? PatcherView::ColourIds::SelectionOtherUser : PatcherView::ColourIds::SelectionOtherView) .withAlpha(1.f)); juce::Path path; const juce::PathStrokeType path_stroke(stroke * 0.5); float const dashed_length[2] {10.f, 10.f}; path_stroke.createDashedStroke(path, m_path, dashed_length, 2); g.strokePath(path, path_stroke); } } bool LinkView::hitTest(juce::Point<int> const& pt, HitTester& hit) const { const float max_distance = 3.f; juce::Point<float> point_on_line; const float distance_from_start = m_path.getNearestPoint(pt.toFloat(), point_on_line); const juce::Point<float> point_on_path = m_path.getPointAlongPath(distance_from_start); const float distance = point_on_path.getDistanceFrom(pt.toFloat()); if(distance <= max_distance) { return true; } return false; } bool LinkView::hitTest(juce::Rectangle<float> const& rect) { juce::Path p = m_path; p.applyTransform(juce::AffineTransform::translation(getPosition())); return (rect.contains(m_last_outlet_pos.toFloat()) || rect.contains(m_last_inlet_pos.toFloat()) || p.intersectsLine({rect.getPosition(), rect.getTopRight()}) || p.intersectsLine({rect.getTopRight(), rect.getBottomRight()}) || p.intersectsLine({rect.getBottomLeft(), rect.getBottomRight()}) || p.intersectsLine({rect.getPosition(), rect.getBottomLeft()})); } // ================================================================================ // // LINK VIEW CREATOR // // ================================================================================ // LinkViewCreator::LinkViewCreator(ObjectFrame& binded_object, const size_t index, bool is_sender, juce::Point<int> dragged_pos) : m_binded_object(binded_object), m_index(index), m_is_sender(is_sender) { m_last_outlet_pos = m_is_sender ? m_binded_object.getOutletPatcherPosition(m_index) : dragged_pos; m_last_inlet_pos = m_is_sender ? dragged_pos : m_binded_object.getInletPatcherPosition(m_index); updateBounds(); } void LinkViewCreator::setEndPosition(juce::Point<int> const& pos) { if(m_is_sender) { m_last_inlet_pos = pos; } else { m_last_outlet_pos = pos; } updateBounds(); } juce::Point<int> LinkViewCreator::getEndPosition() const noexcept { return m_is_sender ? m_last_inlet_pos : m_last_outlet_pos; } void LinkViewCreator::paint(juce::Graphics & g) { const juce::Colour link_color = juce::Colour::fromFloatRGBA(0.2, 0.2, 0.2, 1.); g.setColour(link_color); g.strokePath(m_path, juce::PathStrokeType(1.5f)); } }
12,053
C++
.cpp
274
31.693431
107
0.519117
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,362
KiwiApp_PatcherViewport.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Patcher/KiwiApp_PatcherViewport.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 : [email protected] ============================================================================== */ #include <KiwiApp_Patcher/KiwiApp_Objects/KiwiApp_ObjectFrame.h> #include "KiwiApp_PatcherViewport.h" #include "KiwiApp_PatcherView.h" namespace kiwi { // ================================================================================ // // PATCHER VIEWPORT // // ================================================================================ // PatcherViewport::PatcherViewport(PatcherView& patcher) : m_patcher(patcher) , m_can_hook_resized(false) { setScrollBarThickness(8); setSize(m_patcher.getWidth(), m_patcher.getHeight()); m_magnifier.setSize(m_patcher.getWidth(), m_patcher.getHeight()); m_magnifier.addAndMakeVisible(m_patcher); setViewedComponent(&m_magnifier, false); } void PatcherViewport::visibleAreaChanged(juce::Rectangle<int> const& new_visible_area) { m_patcher.saveState(); } void PatcherViewport::resized() { if(!m_can_hook_resized) { Viewport::resized(); m_can_hook_resized = true; m_last_bounds = getBounds(); } else { viewportResized(m_last_bounds, getBounds()); Viewport::resized(); m_last_bounds = getBounds(); } } void PatcherViewport::setZoomFactor(double zoom_factor) { if(zoom_factor != m_zoom_factor) { const double min_zoom = 0.25; const double max_zoom = 4.; m_zoom_factor = std::max(min_zoom, std::min(zoom_factor, max_zoom)); m_patcher.setTransform(juce::AffineTransform::scale(m_zoom_factor)); updatePatcherArea(false); } } double PatcherViewport::getZoomFactor() const noexcept { return m_zoom_factor; } juce::Rectangle<int> PatcherViewport::getRelativeViewArea() const noexcept { const auto rel_view_pos = getRelativeViewPosition(); return { rel_view_pos.getX(), rel_view_pos.getY(), static_cast<int>(getViewWidth() / m_zoom_factor), static_cast<int>(getViewHeight() / m_zoom_factor) }; } juce::Point<int> PatcherViewport::getRelativePosition(juce::Point<int> point) const noexcept { return (point / m_zoom_factor) - getOriginPosition(); } juce::Point<int> PatcherViewport::getRelativeViewPosition() const noexcept { return getRelativePosition(getViewPosition()); } void PatcherViewport::setRelativeViewPosition(juce::Point<int> position) { setViewPosition((position + getOriginPosition()) * m_zoom_factor); } void PatcherViewport::jumpViewToObject(ObjectFrame const& object_frame) { const auto view_area = getRelativeViewArea(); auto object_bounds = object_frame.getObjectBounds(); object_bounds.setPosition(((object_bounds.getPosition() - getOriginPosition()))); if(! view_area.contains(object_bounds)) { juce::Point<int> view_pos = view_area.getPosition(); juce::Point<int> area_bottom_right = view_area.getBottomRight(); juce::Point<int> object_bottom_right = object_bounds.getBottomRight(); if(object_bounds.getX() < view_area.getX()) { view_pos.setX(object_bounds.getX()); } else if(object_bottom_right.getX() > area_bottom_right.getX()) { view_pos.setX(view_pos.getX() + object_bottom_right.getX() - area_bottom_right.getX()); } if(object_bounds.getY() < view_area.getY()) { view_pos.setY(object_bounds.getY()); } else if(object_bottom_right.getY() > area_bottom_right.getY()) { view_pos.setY(view_pos.getY() + object_bottom_right.getY() - area_bottom_right.getY()); } setRelativeViewPosition(view_pos); } } void PatcherViewport::bringRectToCentre(juce::Rectangle<int> bounds) { const juce::Rectangle<int> view_area = getRelativeViewArea(); const juce::Point<int> center = bounds.getCentre(); const juce::Point<int> new_view_pos { static_cast<int>(center.getX() - view_area.getWidth()*0.5), static_cast<int>(center.getY() - view_area.getHeight()*0.5) }; setRelativeViewPosition(new_view_pos); } void PatcherViewport::resetObjectsArea() { m_patching_area = m_patcher.getCurrentObjectsArea(); updatePatcherArea(true); } juce::Rectangle<int> PatcherViewport::getObjectsArea() const noexcept { return m_patching_area; } juce::Point<int> PatcherViewport::getOriginPosition() const noexcept { const int x = m_patching_area.getX(); const int y = m_patching_area.getY(); return juce::Point<int>( x < 0 ? -x : 0, y < 0 ? -y : 0 ); } void PatcherViewport::viewportResized(juce::Rectangle<int> const& last_bounds, juce::Rectangle<int> const& new_bounds) { const int delta_width = new_bounds.getWidth() - last_bounds.getWidth(); const int delta_height = new_bounds.getHeight() - last_bounds.getHeight(); int new_width = m_patcher.getWidth() + delta_width; int new_height = m_patcher.getHeight() + delta_height; const juce::Rectangle<int> objects_area = m_patcher.getCurrentObjectsArea(); const int objects_width = objects_area.getWidth(); const int objects_height = objects_area.getHeight(); const juce::Point<int> view_pos = getViewPosition(); const double zoom = getZoomFactor(); if(delta_width != 0) { const int viewport_width = (getMaximumVisibleWidth() + view_pos.getX()) / zoom; bool need_resize = false; if(delta_width < 0) { if(viewport_width - delta_width > objects_width) { new_width = viewport_width - delta_width; need_resize = true; } else { new_width = objects_width; } } else if(delta_width > 0) { const bool smaller_than_objects_area = (objects_width > viewport_width); if(smaller_than_objects_area) { const bool will_be_bigger = (objects_width < (new_bounds.getWidth() + view_pos.getX()) / zoom); if(!will_be_bigger) { new_width = objects_width; } else { new_width = objects_width + (delta_width * 10); need_resize = true; } } else { new_width = viewport_width + (delta_width * 10); need_resize = true; } } if(need_resize) { m_magnifier.setSize(new_width * zoom, new_height * zoom); new_width = (getMaximumVisibleWidth() + view_pos.getX()) / zoom; } } if(delta_height != 0) { const int viewport_height = (getMaximumVisibleHeight() + view_pos.getY()) / zoom; bool need_resize = false; if(delta_height < 0) { if(viewport_height - delta_height > objects_height) { new_height = viewport_height - delta_height; need_resize = true; } else { new_height = objects_height; } } else if(delta_height > 0) { const bool smaller_than_objects_area = (objects_height > viewport_height); if(smaller_than_objects_area) { const bool will_be_bigger = (objects_height < (new_bounds.getHeight() + view_pos.getY()) / zoom); if(!will_be_bigger) { new_height = objects_height; } else { new_height = objects_height + (delta_height * 10); need_resize = true; } } else { new_height = viewport_height + (delta_height * 10); need_resize = true; } } if(need_resize) { m_magnifier.setSize(new_width * zoom, new_height * zoom); new_height = (getMaximumVisibleHeight() + view_pos.getY()) / zoom; } } m_patching_area.setSize(new_width, new_height); m_patcher.setSize(new_width, new_height); m_magnifier.setSize(new_width * zoom, new_height * zoom); } void PatcherViewport::updatePatcherArea(bool keep_view_pos) { const juce::Point<int> view_pos = getViewPosition(); const juce::Point<int> last_origin = getOriginPosition(); const double zoom = getZoomFactor(); const int viewport_width = getMaximumVisibleWidth() / zoom; const int viewport_height = getMaximumVisibleHeight() / zoom; juce::Rectangle<int> objects_current_area = m_patcher.getCurrentObjectsArea(); m_patching_area.setLeft(objects_current_area.getX()); m_patching_area.setTop(objects_current_area.getY()); if(objects_current_area.getWidth() > m_patching_area.getWidth()) { m_patching_area.setWidth(objects_current_area.getWidth()); } if(objects_current_area.getHeight() > m_patching_area.getHeight()) { m_patching_area.setHeight(objects_current_area.getHeight()); } const juce::Point<int> origin = getOriginPosition(); const int origin_x = origin.getX(); const int origin_y = origin.getY(); if(last_origin != origin) { m_patcher.originPositionChanged(); } const juce::Rectangle<int> objects_area = m_patching_area.withPosition(origin); const int objects_width = objects_area.getWidth(); const int objects_height = objects_area.getHeight(); int new_width = (viewport_width > objects_width) ? viewport_width : objects_width; int new_height = (viewport_height > objects_height) ? viewport_height : objects_height; // patcher positive area should never be smaller than viewport area new_width = new_width < (viewport_width + origin_x) ? (viewport_width + origin_x) : new_width; new_height = new_height < (viewport_height + origin_y) ? (viewport_height + origin_y) : new_height; m_patcher.setSize(new_width, new_height); m_magnifier.setSize(new_width * zoom, new_height * zoom); if(m_patching_area.getWidth() > viewport_width + (view_pos.getX() / zoom)) { m_patching_area.setWidth(viewport_width + (view_pos.getX() / zoom)); } if(m_patching_area.getHeight() > viewport_height + (view_pos.getY() / zoom)) { m_patching_area.setHeight(viewport_height + (view_pos.getY() / zoom)); } if(keep_view_pos) { const juce::Point<int> delta = (view_pos - origin) - (view_pos - last_origin); setViewPosition(view_pos - delta); } } }
13,096
C++
.cpp
298
31.201342
117
0.546648
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,363
KiwiApp_PatcherComponent.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Patcher/KiwiApp_PatcherComponent.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 : [email protected] ============================================================================== */ #include "KiwiApp_PatcherComponent.h" #include "KiwiApp_PatcherView.h" #include "../KiwiApp_Resources/KiwiApp_BinaryData.h" #include "../KiwiApp.h" #include "../KiwiApp_General/KiwiApp_CommandIDs.h" #include "../KiwiApp_Components/KiwiApp_CustomToolbarButton.h" namespace kiwi { class PatcherToolbar::PatcherToolbarLookAndFeel : public LookAndFeel { public: PatcherToolbarLookAndFeel(PatcherToolbar& toolbar) : m_toolbar(toolbar) {} void paintToolbarBackground(juce::Graphics& g, int width, int height, juce::Toolbar&) override { m_toolbar.paintToolbarBackground(g, width, height); } private: PatcherToolbar& m_toolbar; }; // ================================================================================ // // PATCHER COMPONENT TOOLBAR // // ================================================================================ // PatcherToolbar::PatcherToolbar(PatcherManager& patcher_manager) : m_patcher_manager(patcher_manager) , m_factory(m_patcher_manager) , m_toolbar_look_and_feel(std::make_unique<PatcherToolbarLookAndFeel>(*this)) { m_toolbar.setLookAndFeel(m_toolbar_look_and_feel.get()); m_toolbar.setVertical(false); m_toolbar.setStyle(juce::Toolbar::ToolbarItemStyle::iconsOnly); m_toolbar.setColour(juce::Toolbar::ColourIds::labelTextColourId, juce::Colours::black); m_toolbar.setColour(juce::Toolbar::ColourIds::buttonMouseOverBackgroundColourId, juce::Colours::whitesmoke.contrasting(0.1)); m_toolbar.setColour(juce::Toolbar::ColourIds::buttonMouseDownBackgroundColourId, juce::Colours::whitesmoke.contrasting(0.2)); m_toolbar.setWantsKeyboardFocus(false); setWantsKeyboardFocus(false); addAndMakeVisible(m_toolbar); m_toolbar.addDefaultItems(m_factory); } PatcherToolbar::~PatcherToolbar() { m_toolbar.setLookAndFeel(nullptr); } void PatcherToolbar::resized() { m_toolbar.setBounds(getLocalBounds()); } void PatcherToolbar::paintToolbarBackground(juce::Graphics& g, int width, int height) { g.fillAll(findColour(juce::Toolbar::ColourIds::backgroundColourId)); } int PatcherToolbar::getToolbarItemIndex(Factory::ItemIds item_id) { for(int index = 0; index < m_toolbar.getNumItems(); index++) { if(m_toolbar.getItemId(index) == item_id) { return index; } } return -1; } void PatcherToolbar::removeUsersIcon() { const int users_item_index = getToolbarItemIndex(Factory::ItemIds::users); if(users_item_index >= 0) { m_toolbar.removeToolbarItem(users_item_index); m_toolbar.repaint(); } } void PatcherToolbar::setStackOverflowIconVisible(bool should_be_visible) { const int stack_overflow_item_index = getToolbarItemIndex(Factory::ItemIds::stack_overflow); const bool is_visible = (stack_overflow_item_index >= 0); if(should_be_visible && !is_visible) { const int index = getToolbarItemIndex(Factory::ItemIds::lock_unlock) + 1; m_toolbar.addItem(m_factory, Factory::ItemIds::stack_overflow, index); } else if(!should_be_visible && is_visible) { m_toolbar.removeToolbarItem(stack_overflow_item_index); } } PatcherToolbar::Factory::Factory(PatcherManager& patcher_manager) : m_patcher_manager(patcher_manager) {} void PatcherToolbar::Factory::getAllToolbarItemIds(juce::Array<int>& ids) { ids.add(ItemIds::lock_unlock); ids.add(ItemIds::zoom_in); ids.add(ItemIds::zoom_out); ids.add(separatorBarId); ids.add(spacerId); ids.add(flexibleSpacerId); ids.add(ItemIds::dsp_on_off); ids.add(ItemIds::stack_overflow); if(m_patcher_manager.isConnected()) { ids.add(ItemIds::users); } } void PatcherToolbar::Factory::getDefaultItemSet(juce::Array<int>& ids) { if(m_patcher_manager.isConnected()) { ids.add(ItemIds::users); ids.add(separatorBarId); } ids.add(ItemIds::dsp_on_off); ids.add(separatorBarId); ids.add(ItemIds::lock_unlock); ids.add(spacerId); ids.add(flexibleSpacerId); ids.add(ItemIds::zoom_in); ids.add(ItemIds::zoom_out); } #define IMG_DATA(NAME) binary_data::images::NAME #define IMG_SIZE(NAME) binary_data::images::NAME ## _size #define IMG(name) juce::Drawable::createFromImageData(IMG_DATA(name), IMG_SIZE(name)) juce::ToolbarItemComponent* PatcherToolbar::Factory::createItem(int itemId) { juce::ToolbarItemComponent* btn = nullptr; if(itemId == ItemIds::lock_unlock) { btn = new CustomToolbarButton(itemId, "lock/unlock", juce::Colours::whitesmoke, IMG(locked_png), IMG(unlocked_png)); btn->setCommandToTrigger(&KiwiApp::getCommandManager(), CommandIDs::editModeSwitch, true); } else if(itemId == ItemIds::zoom_in) { btn = new CustomToolbarButton(itemId, "zoom in", juce::Colours::whitesmoke, IMG(zoom_in_png), nullptr); btn->setCommandToTrigger(&KiwiApp::getCommandManager(), CommandIDs::zoomIn, true); } else if(itemId == ItemIds::zoom_out) { btn = new CustomToolbarButton(itemId, "zoom out", juce::Colours::whitesmoke, IMG(zoom_out_png), nullptr); btn->setCommandToTrigger(&KiwiApp::getCommandManager(), CommandIDs::zoomOut, true); } else if(itemId == ItemIds::dsp_on_off) { btn = new CustomToolbarButton(itemId, "DSP on/off", juce::Colours::whitesmoke, IMG(dsp_off_png), IMG(dsp_on_png)); btn->setCommandToTrigger(&KiwiApp::getCommandManager(), CommandIDs::switchDsp, true); } else if(itemId == ItemIds::stack_overflow) { btn = new CustomToolbarButton(itemId, "clear stack-overflow message lock", juce::Colour(0xFFE52E2E), IMG(infinite_loop_png), IMG(infinite_loop_png)); btn->onClick = [this](){ m_patcher_manager.clearStackOverflow(); }; } else if(itemId == ItemIds::users) { btn = new UsersItemComponent(itemId, m_patcher_manager); } return btn; } #undef IMG_DATA #undef IMG_SIZE #undef IMG // ================================================================================ // // TOOLBAR USER COMPONENT // // ================================================================================ // PatcherToolbar::UsersItemComponent::UsersItemComponent(const int toolbarItemId, PatcherManager& patcher_manager) : ToolbarItemComponent (toolbarItemId, "Custom Toolbar Item", false) , m_patcher_manager(patcher_manager) , m_users() , m_user_nb(m_patcher_manager.getNumberOfUsers()) , m_users_img(juce::ImageCache::getFromMemory(binary_data::images::users_png, binary_data::images::users_png_size)) , m_flash_alpha(0.f) { updateUsers(); m_patcher_manager.addListener(*this); } PatcherToolbar::UsersItemComponent::~UsersItemComponent() { m_patcher_manager.removeListener(*this); } void PatcherToolbar::UsersItemComponent::updateUsers() { auto users_ids = m_patcher_manager.getConnectedUsers(); m_user_nb = users_ids.size(); startFlashing(); Component::SafePointer<UsersItemComponent> form(this); auto success = [form](Api::Users users) { KiwiApp::useScheduler().schedule([form, users]() { if (form) { form.getComponent()->m_users.clear(); for(Api::User const& user : users) { form.getComponent()->m_users.push_back(user.getName()); } } }); }; auto fail = [form](Api::Error error) { KiwiApp::useScheduler().schedule([form, error]() { if (form) { form.getComponent()->m_users.clear(); } }); }; KiwiApp::useApi().getUsers(users_ids, success, fail); } void PatcherToolbar::UsersItemComponent::connectedUserChanged(PatcherManager& manager) { if(&manager == &m_patcher_manager) { updateUsers(); startFlashing(); } } void PatcherToolbar::UsersItemComponent::paintButtonArea(juce::Graphics& g, int width, int height, bool isMouseOver, bool isMouseDown) { int padding = 2; int count_size = 14; juce::Rectangle<int> image_bounds(height - padding * 2, padding, height - padding * 2, height - padding * 2); g.drawImage(m_users_img, image_bounds.toFloat(), juce::RectanglePlacement::centred); int center_y = height / 2; juce::Rectangle<int> label_bounds(center_y - count_size / 2, center_y - count_size / 2, count_size, count_size); const auto online_color = juce::Colour::fromRGB(72, 165, 93); const auto badge_color = (juce::Colours::grey.withAlpha(0.5f) .overlaidWith(online_color.withAlpha(m_flash_alpha))); g.setColour(badge_color); g.drawEllipse(label_bounds.expanded(2).toFloat(), 0.5f); g.fillEllipse(label_bounds.expanded(2).toFloat()); g.setColour(juce::Colours::whitesmoke); g.drawText(std::to_string(m_user_nb), label_bounds, juce::Justification::centred); auto flag_rect = juce::Rectangle<float>(0, 0, 3, height).reduced(0, 2); g.setColour(online_color); g.fillRect(flag_rect); } bool PatcherToolbar::UsersItemComponent::getToolbarItemSizes(int toolbarDepth, bool isVertical, int& preferredSize, int& minSize, int& maxSize) { if (isVertical) return false; maxSize = minSize = preferredSize = 50; return true; } void PatcherToolbar::UsersItemComponent::contentAreaChanged(const juce::Rectangle<int>& newArea) { repaint(); } void PatcherToolbar::UsersItemComponent::startFlashing() { m_flash_alpha = 1.0f; startTimerHz (20); } void PatcherToolbar::UsersItemComponent::stopFlashing() { m_flash_alpha = 0.0f; stopTimer(); repaint(); } void PatcherToolbar::UsersItemComponent::mouseDown(juce::MouseEvent const& e) { if (m_users.size() > 0) { juce::PopupMenu m; for(std::string const& username : m_users) { m.addItem(1, username, false, false); } m.showAt(this); } } void PatcherToolbar::UsersItemComponent::timerCallback() { // Reduce the alpha level of the flash slightly so it fades out m_flash_alpha -= 0.075f; if(m_flash_alpha < 0.05f) { stopFlashing(); } repaint(); } // ================================================================================ // // PATCHER COMPONENT // // ================================================================================ // PatcherComponent::PatcherComponent(PatcherView& patcherview) : m_patcher_manager(patcherview.usePatcherManager()) , m_patcherview(patcherview) , m_toolbar(m_patcher_manager) { setSize(m_patcherview.getWidth(), m_patcherview.getHeight()); addAndMakeVisible(&patcherview.useViewport(), true); KiwiApp::bindToCommandManager(this); KiwiApp::bindToKeyMapping(this); addAndMakeVisible(m_toolbar); m_patcher_manager.addListener(*this); m_toolbar.setStackOverflowIconVisible(m_patcher_manager.hasStackOverflow()); } PatcherComponent::~PatcherComponent() { m_patcher_manager.removeListener(*this); } PatcherView& PatcherComponent::usePatcherView() { return m_patcherview; } //! @brief Returns the patcher manager. PatcherManager& PatcherComponent::usePatcherManager() { return m_patcher_manager; } void PatcherComponent::resized() { auto bounds = getLocalBounds(); const int toolbar_size = 36; m_toolbar.setBounds(bounds.removeFromTop(toolbar_size)); m_patcherview.useViewport().setBounds(bounds); } void PatcherComponent::paint(juce::Graphics& g) { ; } void PatcherComponent::removeUsersIcon() { m_toolbar.removeUsersIcon(); } void PatcherComponent::stackOverflowDetected(PatcherManager& manager, std::vector<flip::Ref> culprits) { m_toolbar.setStackOverflowIconVisible(true); } void PatcherComponent::stackOverflowCleared(PatcherManager& manager) { m_toolbar.setStackOverflowIconVisible(false); } // ================================================================================ // // APPLICATION COMMAND TARGET // // ================================================================================ // juce::ApplicationCommandTarget* PatcherComponent::getNextCommandTarget() { return findFirstTargetParentComponent(); } void PatcherComponent::getAllCommands(juce::Array<juce::CommandID>& commands) { m_patcherview.getAllCommands(commands); } void PatcherComponent::getCommandInfo(const juce::CommandID commandID, juce::ApplicationCommandInfo& result) { m_patcherview.getCommandInfo(commandID, result); } bool PatcherComponent::perform(InvocationInfo const& info) { bool performed = m_patcherview.perform(info); return performed; } // ================================================================================ // // PATCHER VIEW WINDOW // // ================================================================================ // PatcherViewWindow::PatcherViewWindow(PatcherManager& manager, PatcherView& patcherview) : Window("Untitled", nullptr, true, true, "", !KiwiApp::isMacOSX()) , juce::ComponentMovementWatcher(this) , m_patcher_component(patcherview) { setContentNonOwned(&m_patcher_component, true); setVisible(true); getLookAndFeel().setUsingNativeAlertWindows(false); const auto user_area = juce::Desktop::getInstance() .getDisplays().getMainDisplay().userArea; setResizeLimits(50, 50, user_area.getWidth(), user_area.getHeight()); patcherview.windowInitialized(); } void PatcherViewWindow::removeUsersIcon() { m_patcher_component.removeUsersIcon(); } bool PatcherViewWindow::showOkCancelBox(juce::AlertWindow::AlertIconType icon_type, std::string const& title, std::string const& message, std::string const& button_1, std::string const& button_2) { return juce::AlertWindow::showOkCancelBox(icon_type, title, message, button_1, button_2, this); } PatcherManager& PatcherViewWindow::getPatcherManager() { return m_patcher_component.usePatcherManager(); } PatcherView& PatcherViewWindow::getPatcherView() { return m_patcher_component.usePatcherView(); } void PatcherViewWindow::closeButtonPressed() { KiwiApp::use().useInstance().removePatcherWindow(*this); } void PatcherViewWindow::componentMovedOrResized(bool was_moved, bool was_resized) { m_patcher_component.usePatcherView().saveState(); } }
18,320
C++
.cpp
430
31.827907
133
0.565162
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,364
KiwiApp_SliderView.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Patcher/KiwiApp_Objects/KiwiApp_SliderView.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 : [email protected] ============================================================================== */ #include <functional> #include <juce_gui_basics/juce_gui_basics.h> #include <KiwiTool/KiwiTool_Scheduler.h> #include <KiwiApp.h> #include <KiwiApp_Patcher/KiwiApp_Factory.h> #include <KiwiApp_Patcher/KiwiApp_Objects/KiwiApp_SliderView.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Slider.h> namespace kiwi { // ================================================================================ // // SLIDER VIEW // // ================================================================================ // SliderView::SliderView(model::Object & object_model): ObjectView(object_model), m_slider(juce::Slider::SliderStyle::LinearVertical, juce::Slider::TextEntryBoxPosition::NoTextBox), m_output_value(object_model.getSignal<>(model::Slider::Signal::OutputValue)) { m_slider.setColour(juce::Slider::ColourIds::backgroundColourId, findColour(ObjectView::ColourIds::Background).contrasting(0.2f)); m_slider.setColour(juce::Slider::ColourIds::trackColourId, findColour(ObjectView::ColourIds::Active).contrasting(0.2f)); m_slider.setColour(juce::Slider::ColourIds::thumbColourId, findColour(ObjectView::ColourIds::Active)); m_slider.setRange(0., 1.); m_slider.setVelocityModeParameters(1., 1, 0., false); m_slider.addListener(this); addAndMakeVisible(m_slider); } SliderView::~SliderView() { m_slider.removeListener(this); } void SliderView::declare() { Factory::add<SliderView>("slider", &SliderView::create); } std::unique_ptr<ObjectView> SliderView::create(model::Object & object_model) { return std::make_unique<SliderView>(object_model); } void SliderView::paint(juce::Graphics & g) { g.setColour(findColour(ObjectView::ColourIds::Background)); g.fillRect(getLocalBounds()); g.setColour(findColour(ObjectView::ColourIds::Outline)); drawOutline(g); } void SliderView::mouseDown(juce::MouseEvent const& e) { m_slider.mouseDown(e.getEventRelativeTo(&m_slider)); } void SliderView::mouseUp(juce::MouseEvent const& e) { m_slider.mouseUp(e.getEventRelativeTo(&m_slider)); } void SliderView::mouseDrag(juce::MouseEvent const& e) { m_slider.mouseDrag(e.getEventRelativeTo(&m_slider)); } void SliderView::sliderValueChanged(juce::Slider * slider) { setParameter("value", tool::Parameter(tool::Parameter::Type::Float, {slider->getValue()})); m_output_value(); } void SliderView::resized() { const int min = 20; const int max = 40; const bool vertical = (getWidth() <= getHeight()); setMinimumSize(vertical ? min : max, vertical ? max : min); if (!vertical && m_slider.isVertical()) { m_slider.setSliderStyle(juce::Slider::SliderStyle::LinearHorizontal); } if (vertical && m_slider.isHorizontal()) { m_slider.setSliderStyle(juce::Slider::SliderStyle::LinearVertical); } m_slider.setBounds(getLocalBounds()); } void SliderView::parameterChanged(std::string const& name, tool::Parameter const& parameter) { if (name == "value") { m_slider.setValue(parameter[0].getFloat(), juce::NotificationType::dontSendNotification); repaint(); } } }
4,718
C++
.cpp
104
35.807692
104
0.577828
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,365
KiwiApp_NumberView.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Patcher/KiwiApp_Objects/KiwiApp_NumberView.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 : [email protected] ============================================================================== */ #include <KiwiModel/KiwiModel_Objects/KiwiModel_Number.h> #include <KiwiApp_Patcher/KiwiApp_Objects/KiwiApp_NumberView.h> #include <KiwiApp_Patcher/KiwiApp_Factory.h> namespace kiwi { // ================================================================================ // // NUMBER VIEW // // ================================================================================ // void NumberView::declare() { Factory::add<NumberView>("number", &NumberView::create); } std::unique_ptr<ObjectView> NumberView::create(model::Object & object_model) { return std::make_unique<NumberView>(object_model); } NumberView::NumberView(model::Object & object_model) : NumberViewBase(object_model) , m_output_message(object_model.getSignal<>(model::Message::Signal::outputMessage)) { setInterceptsMouseClicks(true, true); } NumberView::~NumberView() {} void NumberView::drawIcon (juce::Graphics& g) const { g.setColour(findColour(ObjectView::ColourIds::Background).contrasting(0.2)); const juce::Rectangle<int> icon_bounds = getLocalBounds() .withWidth(m_indent - 4).withHeight(getHeight() - 8).translated(2, 4); juce::Path corner; corner.addTriangle(icon_bounds.getTopLeft().toFloat(), icon_bounds.getTopRight().toFloat() + juce::Point<float>(0, (icon_bounds.getHeight() / 2.)), icon_bounds.getBottomLeft().toFloat()); g.fillPath(corner); } void NumberView::mouseDoubleClick(juce::MouseEvent const& e) { getLabel().showEditor(); } void NumberView::mouseDown(juce::MouseEvent const& e) { e.source.enableUnboundedMouseMovement(true, true); m_last_drag_pos = e.position; m_drag_value = m_value; auto const& label = getLabel(); const auto textArea = label.getBorderSize().subtractedFrom(label.getBounds()); juce::GlyphArrangement glyphs; glyphs.addFittedText (label.getFont(), label.getText(), textArea.getX(), 0., textArea.getWidth(), getHeight(), juce::Justification::centredLeft, 1, label.getMinimumHorizontalScale()); double decimal_x = getWidth(); for(int i = 0; i < glyphs.getNumGlyphs(); ++i) { auto const& glyph = glyphs.getGlyph(i); if(glyph.getCharacter() == '.') { decimal_x = glyph.getRight(); } } const bool is_dragging_decimal = e.x > decimal_x; m_decimal_drag = is_dragging_decimal ? 6 : 0; if(is_dragging_decimal) { juce::GlyphArrangement decimals_glyph; static const juce::String decimals_str("000000"); decimals_glyph.addFittedText (label.getFont(), decimals_str, decimal_x, 0, getWidth(), getHeight(), juce::Justification::centredLeft, 1, label.getMinimumHorizontalScale()); for(int i = 0; i < decimals_glyph.getNumGlyphs(); ++i) { auto const& glyph = decimals_glyph.getGlyph(i); if(e.x <= glyph.getRight()) { m_decimal_drag = i+1; break; } } } } void NumberView::mouseDrag(juce::MouseEvent const& e) { setMouseCursor(juce::MouseCursor::NoCursor); updateMouseCursor(); if (e.mouseWasDraggedSinceMouseDown()) { const int decimal = m_decimal_drag + e.mods.isShiftDown(); const double increment = (decimal == 0) ? 1. : (1. / std::pow(10., decimal)); const double delta_y = e.y - m_last_drag_pos.y; m_last_drag_pos = e.position; m_drag_value += increment * -delta_y; if(m_drag_value != m_value) { // truncate value and set double new_value = m_drag_value; if(decimal > 0) { const int sign = (new_value > 0) ? 1 : -1; unsigned int ui_temp = (new_value * std::pow(10, decimal)) * sign; new_value = (((double)ui_temp)/std::pow(10, decimal) * sign); } else { new_value = static_cast<int64_t>(new_value); } setParameter("value", tool::Parameter(tool::Parameter::Type::Float, {new_value})); m_output_message(); repaint(); } } } void NumberView::mouseUp(juce::MouseEvent const& e) { setMouseCursor(juce::MouseCursor::NormalCursor); updateMouseCursor(); juce::Desktop::getInstance() .getMainMouseSource().setScreenPosition(e.getMouseDownScreenPosition().toFloat()); } void NumberView::parameterChanged(std::string const& name, tool::Parameter const& param) { if (name == "value") { setDisplayNumber(param[0].getFloat()); } } void NumberView::displayNumberChanged(double number) { setParameter("value", tool::Parameter(tool::Parameter::Type::Float, {number})); m_output_message(); } }
6,670
C++
.cpp
147
32.843537
92
0.529412
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,366
KiwiApp_ToggleView.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Patcher/KiwiApp_Objects/KiwiApp_ToggleView.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 : [email protected] ============================================================================== */ #include <KiwiApp_Patcher/KiwiApp_Objects/KiwiApp_ToggleView.h> #include <KiwiApp_Patcher/KiwiApp_Factory.h> namespace kiwi { // ================================================================================ // // TOGGLE VIEW // // ================================================================================ // void ToggleView::declare() { Factory::add<ToggleView>("toggle", &ToggleView::create); } std::unique_ptr<ObjectView> ToggleView::create(model::Object & model) { return std::make_unique<ToggleView>(model); } ToggleView::ToggleView(model::Object & model): ObjectView(model), m_signal(model.getSignal<>(model::Toggle::Signal::OutputValue)), m_is_on(false) { setMinimumSize(20.f, 20.f); setFixedAspectRatio(1.f); } ToggleView::~ToggleView() { } void ToggleView::mouseDown(juce::MouseEvent const& e) { setParameter("value", tool::Parameter(tool::Parameter::Type::Int, {!m_is_on})); m_signal(); } void ToggleView::parameterChanged(std::string const& name, tool::Parameter const& param) { if (name == "value") { m_is_on = static_cast<bool>(param[0].getInt()); repaint(); } } void ToggleView::paint(juce::Graphics & g) { g.fillAll(findColour(ObjectView::ColourIds::Background)); drawOutline(g); g.setColour(m_is_on ? findColour(ObjectView::ColourIds::Active) : findColour(ObjectView::ColourIds::Background).contrasting(0.2)); const auto local_bounds = getLocalBounds().toFloat(); const auto max = std::max(local_bounds.getWidth(), local_bounds.getHeight()); const auto cross_stroke_width = max * 0.1; const auto cross_bounds = local_bounds.reduced(max * 0.3); g.drawLine({cross_bounds.getTopLeft(), cross_bounds.getBottomRight()}, cross_stroke_width); g.drawLine({cross_bounds.getBottomLeft(), cross_bounds.getTopRight()}, cross_stroke_width); } }
3,154
C++
.cpp
67
38.731343
100
0.545303
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,367
KiwiApp_CommentView.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Patcher/KiwiApp_Objects/KiwiApp_CommentView.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 : [email protected] ============================================================================== */ #include <KiwiModel/KiwiModel_DocumentManager.h> #include <KiwiApp_Patcher/KiwiApp_Objects/KiwiApp_CommentView.h> #include <KiwiApp_Patcher/KiwiApp_Factory.h> namespace kiwi { // ================================================================================ // // COMMENT VIEW // // ================================================================================ // void CommentView::declare() { Factory::add<CommentView>("comment", &CommentView::create); } std::unique_ptr<ObjectView> CommentView::create(model::Object & object_model) { return std::make_unique<CommentView>(object_model); } CommentView::CommentView(model::Object & object_model) : EditableObjectView(object_model) { setColour(ObjectView::ColourIds::Background, juce::Colours::transparentWhite); juce::Label& label = getLabel(); const auto comment_text = object_model.getAttribute("text")[0].getString(); label.setText(comment_text, juce::NotificationType::dontSendNotification); label.setColour(juce::Label::backgroundColourId, findColour(ObjectView::ColourIds::Background)); label.setColour(juce::Label::backgroundWhenEditingColourId, findColour(ObjectView::ColourIds::Background)); label.setColour(juce::Label::textColourId, findColour(ObjectView::ColourIds::Text).brighter(0.4)); label.setColour(juce::Label::textWhenEditingColourId, findColour(ObjectView::ColourIds::Text)); addAndMakeVisible(label); } CommentView::~CommentView() {} void CommentView::lockStatusChanged(bool is_locked) { m_patcher_view_locked = is_locked; repaint(); } void CommentView::paintOverChildren (juce::Graphics& g) { if(!m_patcher_view_locked) { // dashed outline juce::Path path; path.addRectangle(getLocalBounds()); const juce::PathStrokeType path_stroke(1.f); float const dashed_length[2] {2.f, 2.f}; path_stroke.createDashedStroke(path, path, dashed_length, 2); g.setColour(findColour (ObjectView::ColourIds::Outline)); g.strokePath(path, path_stroke); } } void CommentView::textEditorTextChanged(juce::TextEditor& editor) { setSize(std::max(getWidth(), getMinWidth()), std::max(editor.getTextHeight() + 2, getMinHeight())); } void CommentView::attributeChanged(std::string const& name, tool::Parameter const& param) { static const std::string text_param = "text"; if (name == text_param) { const auto new_text = param[0].getString(); getLabel().setText(new_text, juce::NotificationType::dontSendNotification); checkComponentBounds(this); } } void CommentView::textChanged() { const auto new_text = getLabel().getText().toStdString(); setAttribute("text", tool::Parameter(tool::Parameter::Type::String, {new_text})); } juce::TextEditor* CommentView::createdTextEditor() { auto* editor = new juce::TextEditor(); editor->setColour(juce::TextEditor::ColourIds::textColourId, getLabel().findColour(juce::Label::textWhenEditingColourId)); editor->setColour(juce::TextEditor::backgroundColourId, getLabel().findColour(juce::Label::backgroundWhenEditingColourId)); editor->setColour(juce::TextEditor::highlightColourId, findColour(ObjectView::ColourIds::Highlight, true).withAlpha(0.4f)); editor->setColour(juce::TextEditor::outlineColourId, juce::Colours::transparentWhite); editor->setColour(juce::TextEditor::focusedOutlineColourId, juce::Colours::transparentWhite); editor->setBounds(getLocalBounds()); editor->setIndents(getPadding(), getPadding()); editor->setBorder(juce::BorderSize<int>(0)); editor->setFont(getFont()); editor->setJustification(getLabel().getJustificationType()); editor->setScrollbarsShown(false); editor->setScrollToShowCursor(true); editor->setReturnKeyStartsNewLine(true); editor->setMultiLine(true, true); editor->setInterceptsMouseClicks(true, false); editor->addListener(this); return editor; } }
5,750
C++
.cpp
114
39.192982
95
0.592503
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,368
KiwiApp_BangView.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Patcher/KiwiApp_Objects/KiwiApp_BangView.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 : [email protected] ============================================================================== */ #include <chrono> #include <KiwiApp_Patcher/KiwiApp_Objects/KiwiApp_BangView.h> #include <KiwiApp_Patcher/KiwiApp_Factory.h> namespace kiwi { // ================================================================================ // // BANG VIEW // // ================================================================================ // void BangView::declare() { Factory::add<BangView>("bang", &BangView::create); } std::unique_ptr<ObjectView> BangView::create(model::Object & model) { return std::make_unique<BangView>(model); } BangView::BangView(model::Object & model) : ObjectView(model) , m_trigger_signal(model.getSignal<>(model::Bang::Signal::TriggerBang)) , m_flash_signal(model.getSignal<>(model::Bang::Signal::FlashBang)) , m_trigger_connection(m_trigger_signal.connect(std::bind(&BangView::signalTriggered, this))) , m_flash_connection(m_flash_signal.connect(std::bind(&BangView::signalTriggered, this))) , m_active(false) , m_mouse_down(false) { setMinimumSize(20.f, 20.f); setFixedAspectRatio(1.f); } BangView::~BangView() {} void BangView::paint(juce::Graphics & g) { g.fillAll(findColour(ObjectView::ColourIds::Background)); g.setColour(findColour(ObjectView::ColourIds::Outline)); drawOutline(g); const auto bounds = getLocalBounds().toFloat(); const auto width = std::max(bounds.getWidth(), bounds.getHeight()); const float circle_outer = 80.f * (width * 0.01f); const float circle_thickness = 10.f * (width * 0.01f); g.setColour(findColour(ObjectView::ColourIds::Background).contrasting(0.2)); g.drawEllipse(bounds.reduced(width - circle_outer), circle_thickness); if (m_mouse_down || m_active) { g.setColour(findColour(ObjectView::ColourIds::Active)); g.fillEllipse(bounds.reduced(width - circle_outer + circle_thickness)); } } void BangView::mouseDown(juce::MouseEvent const& e) { m_mouse_down = true; repaint(); m_trigger_signal(); } void BangView::mouseUp(juce::MouseEvent const& e) { m_mouse_down = false; repaint(); } void BangView::flash() { if (!m_active) { m_active = true; repaint(); schedule([this]() { m_active = false; repaint(); }, std::chrono::milliseconds(150)); } } void BangView::signalTriggered() { defer([this]() { flash(); }); } }
3,808
C++
.cpp
91
32.769231
98
0.535654
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,369
KiwiApp_ClassicView.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Patcher/KiwiApp_Objects/KiwiApp_ClassicView.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 : [email protected] ============================================================================== */ #include <KiwiModel/KiwiModel_Factory.h> #include <KiwiApp.h> #include <KiwiApp_Patcher/KiwiApp_Objects/KiwiApp_ClassicView.h> #include <KiwiApp_Components/KiwiApp_SuggestEditor.h> namespace kiwi { // ================================================================================ // // CLASSIC VIEW // // ================================================================================ // ClassicView::ClassicView(model::Object & object_model) : EditableObjectView(object_model) { juce::Label & label = getLabel(); const auto object_text = object_model.getText(); label.setText(object_text, juce::NotificationType::dontSendNotification); juce::Colour bg_colour = (object_model.getName() == "errorbox" ? findColour(ObjectView::ColourIds::Error) : findColour(ObjectView::ColourIds::Background)); setColour(ObjectView::ColourIds::Background, bg_colour); setColour(ObjectView::ColourIds::Outline, bg_colour.contrasting(0.4)); label.setColour(juce::Label::backgroundColourId, bg_colour); label.setColour(juce::Label::backgroundWhenEditingColourId, bg_colour); label.setColour(juce::Label::textColourId, findColour(ObjectView::ColourIds::Text)); label.setColour(juce::Label::textWhenEditingColourId, findColour(ObjectView::ColourIds::Text)); addAndMakeVisible(label); } ClassicView::~ClassicView() {} void ClassicView::paintOverChildren (juce::Graphics& g) { drawOutline(g); } void ClassicView::textChanged() {} void ClassicView::textEditorTextChanged(juce::TextEditor& editor) { const auto text = editor.getText(); auto single_line_text_width = editor.getFont().getStringWidthFloat(text) + getPadding() * 2 + 10; auto prev_width = getWidth(); auto text_bounds = getTextBoundingBox(text, single_line_text_width); setSize(std::max<int>(prev_width, single_line_text_width), std::max(std::min<int>(text_bounds.getHeight(), getHeight()), getMinHeight())); } juce::TextEditor* ClassicView::createdTextEditor() { juce::TextEditor * editor = new SuggestEditor(model::Factory::getNames()); editor->setColour(juce::TextEditor::ColourIds::textColourId, getLabel().findColour(juce::Label::textWhenEditingColourId)); editor->setColour(juce::TextEditor::backgroundColourId, getLabel().findColour(juce::Label::backgroundWhenEditingColourId)); editor->setColour(juce::TextEditor::highlightColourId, findColour(ObjectView::ColourIds::Highlight, true).withAlpha(0.4f)); editor->setColour(juce::TextEditor::outlineColourId, juce::Colours::transparentWhite); editor->setColour(juce::TextEditor::focusedOutlineColourId, juce::Colours::transparentWhite); editor->setBounds(getLocalBounds()); editor->setIndents(getPadding(), getPadding()); editor->setBorder(juce::BorderSize<int>(0)); editor->setFont(getLabel().getFont()); editor->setJustification(getLabel().getJustificationType()); editor->setScrollbarsShown(false); editor->setScrollToShowCursor(true); editor->setReturnKeyStartsNewLine(false); editor->setMultiLine(true, true); editor->setInterceptsMouseClicks(true, false); editor->addListener(this); return editor; } }
4,761
C++
.cpp
84
45.488095
105
0.600134
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,370
KiwiApp_ObjectFrame.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Patcher/KiwiApp_Objects/KiwiApp_ObjectFrame.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 : [email protected] ============================================================================== */ #define _USE_MATH_DEFINES #include <cmath> #include <KiwiApp.h> #include <KiwiApp_Patcher/KiwiApp_Objects/KiwiApp_ObjectFrame.h> #include <KiwiApp_Patcher/KiwiApp_Objects/KiwiApp_ClassicView.h> namespace kiwi { // ================================================================================ // // OBJECT FRAME // // ================================================================================ // ObjectFrame::ObjectFrame(PatcherView& patcher_view, std::unique_ptr<ObjectView> object_view) : m_object_view(std::move(object_view)) , m_patcher_view(patcher_view) , m_io_width(6) , m_io_height(3) , m_outline(10, 4) { const auto& model_object = getModel(); updateInlets(model_object); updateOutlets(model_object); const bool pv_locked = isLocked(); setInterceptsMouseClicks(pv_locked, pv_locked); m_object_view->lockStatusChanged(pv_locked); updateBoundsFromModel(false); addChildComponent(m_outline); updateOutline(); addAndMakeVisible(m_object_view.get()); } ObjectFrame::~ObjectFrame() {} size_t ObjectFrame::getNumberOfInlets() const noexcept { return m_inlets.size(); } size_t ObjectFrame::getNumberOfOutlets() const noexcept { return m_outlets.size(); } void ObjectFrame::childBoundsChanged(juce::Component * child) { setBounds(getObjectBounds().expanded(m_outline.getBorderThickness())); } void ObjectFrame::resized() { m_object_view->setBounds(getLocalBounds().reduced(m_outline.getBorderThickness())); m_outline.setBounds(getLocalBounds()); } void ObjectFrame::updateBoundsFromModel(bool animate) { model::Object const& model = getModel(); if(!model.removed()) { const juce::Point<int> origin = m_patcher_view.getOriginPosition(); juce::Rectangle<int> object_bounds(model.getX() + origin.getX(), model.getY() + origin.getY(), model.getWidth(), model.getHeight()); m_object_view->checkBounds(object_bounds, m_object_view->getBounds(), {}, false, false, false, false); const juce::Rectangle<int> frame_bounds = object_bounds.expanded(m_outline.getBorderThickness()); if (animate) { juce::ComponentAnimator& animator = juce::Desktop::getInstance().getAnimator(); animator.animateComponent(this, frame_bounds, 1., 150., false, 0.8, 1.); } else { setBounds(frame_bounds); } } } void ObjectFrame::paintOverChildren (juce::Graphics& g) { const bool locked = isLocked(); if(!locked) { drawInletsOutlets(g); } const auto distant_selection = getDistantSelection(); const bool other_selected = ! distant_selection.empty(); const bool other_view_selected = (other_selected && distant_selection.find(KiwiApp::userID()) != distant_selection.end()); const bool other_user_selected = ((other_selected && (other_view_selected && distant_selection.size() > 1)) || (other_selected && !other_view_selected)); if(other_user_selected || other_view_selected) { const bool selected = isSelected(); g.setColour(findColour(other_user_selected ? PatcherView::ColourIds::SelectionOtherUser : PatcherView::ColourIds::SelectionOtherView) .withAlpha(0.5f)); if(!locked) { g.fillRoundedRectangle(getLocalBounds().toFloat() .reduced(selected ? 5.f : 1.f), selected ? 0.f : 5.f); } else { const float amount = 3.f; g.drawRoundedRectangle(getLocalBounds().toFloat().reduced(amount), amount, amount); } } } void ObjectFrame::drawInletsOutlets(juce::Graphics & g) { const auto pin_control_color = findColour(ObjectView::ColourIds::PinControl); const auto pin_signal_color = findColour(ObjectView::ColourIds::PinSignal); for(unsigned int i = 0; i < getNumberOfInlets(); ++i) { g.setColour(m_inlets[i].is_signal ? pin_signal_color : pin_control_color); g.fillRect(getInletLocalBounds(i)); } for(unsigned int i = 0; i < getNumberOfOutlets(); ++i) { g.setColour(m_outlets[i].is_signal ? pin_signal_color : pin_control_color); g.fillRect(getOutletLocalBounds(i)); } } juce::Rectangle<int> ObjectFrame::getObjectBounds() const { const auto object_view_bounds = m_object_view->getBounds(); return object_view_bounds.withPosition(getPosition() + object_view_bounds.getPosition()); } juce::ComponentBoundsConstrainer* ObjectFrame::getBoundsConstrainer() const { return m_object_view.get(); } int ObjectFrame::getResizingFlags() const { return m_object_view->getResizingFlags(); } void ObjectFrame::mouseDown(juce::MouseEvent const& e) { m_object_view->mouseDown(e.getEventRelativeTo(m_object_view.get())); } void ObjectFrame::mouseUp(juce::MouseEvent const& e) { m_object_view->mouseUp(e.getEventRelativeTo(m_object_view.get())); } void ObjectFrame::mouseDrag(juce::MouseEvent const& e) { m_object_view->mouseDrag(e.getEventRelativeTo(m_object_view.get())); } bool ObjectFrame::hitTest(int x, int y) { bool allow_click; bool allow_click_onchild; getInterceptsMouseClicks(allow_click, allow_click_onchild); if (! allow_click) return false; return m_object_view->getBounds().contains(x, y); } bool ObjectFrame::hitTest(juce::Point<int> const& pt, HitTester& hit) const { const auto box_bounds = m_object_view->getBounds(); // test body and iolets if(box_bounds.contains(pt)) { const auto ninlets = getNumberOfInlets(); const auto noutlets = getNumberOfOutlets(); // test inlets if(ninlets > 0 && pt.getY() > getPinHeight()) { for(size_t i = 0; i < ninlets; ++i) { if(getInletLocalBounds(i).contains(pt)) { hit.m_zone = HitTester::Zone::Inlet; hit.m_index = i; return true; } } } // test outlets if(noutlets > 0 && pt.getY() > box_bounds.getHeight() - getPinHeight()) { for(size_t i = 0; i < noutlets; ++i) { if(getOutletLocalBounds(i).contains(pt)) { hit.m_zone = HitTester::Zone::Outlet; hit.m_index = i; return true; } } } // hit the body of the box hit.m_zone = HitTester::Zone::Inside; hit.m_index = 0; return true; } else if(m_outline.isVisible() && m_outline.hitTest(pt, hit)) // test borders { return true; } hit.m_zone = HitTester::Zone::Outside; hit.m_index = 0; return false; } bool ObjectFrame::hitTest(juce::Rectangle<int> const& rect) const { const juce::Rectangle<int> bounds = getObjectBounds(); return rect.intersects(bounds) || rect.contains(bounds) || bounds.contains(rect); } bool ObjectFrame::isSelected() const { return getPatcherView().isSelected(*this); } std::set<uint64_t> ObjectFrame::getDistantSelection() const { return getPatcherView().getDistantSelection(*this); } bool ObjectFrame::isLocked() const { return getPatcherView().isLocked(); } void ObjectFrame::updateInlets(model::Object const& object) { m_inlets.clear(); for(auto& inlet : object.getInlets()) { m_inlets.emplace_back(inlet.hasType(kiwi::model::PinType::IType::Signal)); } } void ObjectFrame::updateOutlets(model::Object const& object) { m_outlets.clear(); for(auto& outlet : object.getOutlets()) { m_outlets.emplace_back(outlet.getType() == kiwi::model::PinType::IType::Signal); } } void ObjectFrame::objectChanged(model::Patcher::View& view, model::Object& object) { if(object.inletsChanged()) { updateInlets(object); repaint(); } if(object.outletsChanged()) { updateOutlets(object); repaint(); } if(object.boundsChanged()) { const auto ctrl = object.document().controller(); const bool animate = (ctrl == flip::Controller::UNDO || ctrl == flip::Controller::EXTERNAL); updateBoundsFromModel(animate); repaint(); } } void ObjectFrame::attributeChanged(std::string const& name, tool::Parameter const& parameter) { m_object_view->modelAttributeChanged(name, parameter); } void ObjectFrame::textChanged(std::string const& new_text) { if (auto* editable_object_view = dynamic_cast<EditableObjectView*>(m_object_view.get())) { editable_object_view->removeListener(*this); if (dynamic_cast<ClassicView*>(m_object_view.get())) { getPatcherView().objectTextChanged(*this, new_text); } } } void ObjectFrame::editorHidden() { setInterceptsMouseClicks(isLocked(), isLocked()); getPatcherView().objectEditorHidden(*this); } void ObjectFrame::editorShown() { setInterceptsMouseClicks(true, true); getPatcherView().objectEditorShown(*this); } void ObjectFrame::editObject() { if (auto* editable_object_view = dynamic_cast<EditableObjectView*>(m_object_view.get())) { editable_object_view->addListener(*this); editable_object_view->edit(); } } void ObjectFrame::updateOutline() { m_outline.setVisible(isSelected()); } void ObjectFrame::selectionChanged() { updateOutline(); repaint(); } void ObjectFrame::lockStatusChanged() { const bool locked = isLocked(); setInterceptsMouseClicks(locked, locked); m_object_view->lockStatusChanged(locked); repaint(); } void ObjectFrame::patcherViewOriginPositionChanged() { updateBoundsFromModel(false); } juce::Point<int> ObjectFrame::getInletPatcherPosition(const size_t index) const { return getPosition() + getInletLocalBounds(index).getCentre(); } juce::Point<int> ObjectFrame::getOutletPatcherPosition(const size_t index) const { return getPosition() + getOutletLocalBounds(index).getCentre(); } model::Object& ObjectFrame::getModel() const { return m_object_view->getModel(); } size_t ObjectFrame::getPinWidth() const { return m_io_width; } size_t ObjectFrame::getPinHeight() const { return m_io_height; } juce::Rectangle<int> ObjectFrame::getInletLocalBounds(const size_t index) const { juce::Rectangle<int> rect; const auto ninlets = getNumberOfInlets(); if(ninlets > 0 && index < ninlets) { juce::Rectangle<int> inlet_bounds = m_object_view->getBounds(); auto pin_width = getPinWidth(); const auto border_width = (m_outline.getResizeLength() - m_outline.getBorderThickness()); const auto space_to_remove = juce::jlimit<int>(0, border_width, inlet_bounds.getWidth() - (pin_width * ninlets) - border_width); if(space_to_remove > 0) { inlet_bounds.removeFromLeft(space_to_remove); inlet_bounds.removeFromRight(space_to_remove); } if(ninlets == 1 && index == 0) { rect.setBounds(inlet_bounds.getX(), inlet_bounds.getY(), pin_width, getPinHeight()); } else if(ninlets > 1) { const double ratio = (inlet_bounds.getWidth() - pin_width) / (double)(ninlets - 1); rect.setBounds(inlet_bounds.getX() + ratio * index, inlet_bounds.getY(), pin_width, getPinHeight()); } } return rect; } juce::Rectangle<int> ObjectFrame::getOutletLocalBounds(const size_t index) const { juce::Rectangle<int> rect; const auto noutlets = getNumberOfOutlets(); if(noutlets > 0 && index < noutlets) { juce::Rectangle<int> outlet_bounds = m_object_view->getBounds(); auto pin_width = getPinWidth(); const auto border_width = (m_outline.getResizeLength() - m_outline.getBorderThickness()); const auto space_to_remove = juce::jlimit<int>(0, border_width, outlet_bounds.getWidth() - (pin_width * noutlets) - border_width); if(space_to_remove > 0) { outlet_bounds.removeFromLeft(space_to_remove); outlet_bounds.removeFromRight(space_to_remove); } if(noutlets == 1 && index == 0) { rect.setBounds(outlet_bounds.getX(), outlet_bounds.getY() + outlet_bounds.getHeight() - getPinHeight(), pin_width, getPinHeight()); } if(noutlets > 1) { const double ratio = (outlet_bounds.getWidth() - getPinWidth()) / (double)(noutlets - 1); rect.setBounds(outlet_bounds.getX() + ratio * index, outlet_bounds.getY() + outlet_bounds.getHeight() - getPinHeight(), pin_width, getPinHeight()); } } return rect; } PatcherView& ObjectFrame::getPatcherView() const { return m_patcher_view; } // ================================================================================ // // OUTLINE // // ================================================================================ // ObjectFrame::Outline::Border operator|(ObjectFrame::Outline::Border const& l_border, ObjectFrame::Outline::Border const& r_border) { return static_cast<ObjectFrame::Outline::Border>(static_cast<int>(l_border) | static_cast<int>(r_border)); } ObjectFrame::Outline::Outline(int resize_length, int resize_thickness) : m_resize_length(resize_length) , m_resize_thickness(resize_thickness) {} ObjectFrame::Outline::~Outline() {} int ObjectFrame::Outline::getBorderThickness() const { return m_resize_thickness; } int ObjectFrame::Outline::getResizeLength() const { return m_resize_length; } void ObjectFrame::Outline::updateCorners() { juce::Rectangle<float> bounds = getLocalBounds().toFloat(); std::array<juce::Rectangle<float>, 3> corner; corner[0].setBounds(bounds.getX(), bounds.getY(), m_resize_thickness, m_resize_length); corner[1].setBounds(bounds.getX(), bounds.getY(), m_resize_length, m_resize_thickness); corner[2] = corner[0]; corner[2].reduceIfPartlyContainedIn(corner[1]); m_corners[Border::Top | Border::Left] = corner; juce::AffineTransform transform = juce::AffineTransform::rotation(M_PI / 2, bounds.getX(), bounds.getY()); transform = transform.translated(bounds.getTopRight()); m_corners[Border::Top | Border::Right][0] = corner[0].transformedBy(transform); m_corners[Border::Top | Border::Right][1] = corner[1].transformedBy(transform); m_corners[Border::Top | Border::Right][2] = corner[2].transformedBy(transform); transform = juce::AffineTransform::rotation(M_PI); transform = transform.translated(bounds.getBottomRight()); m_corners[Border::Bottom | Border::Right][0] = corner[0].transformedBy(transform); m_corners[Border::Bottom | Border::Right][1] = corner[1].transformedBy(transform); m_corners[Border::Bottom | Border::Right][2] = corner[2].transformedBy(transform); transform = juce::AffineTransform::rotation((3 * M_PI) / 2); transform = transform.translated(bounds.getBottomLeft()); m_corners[Border::Bottom | Border::Left][0] = corner[0].transformedBy(transform); m_corners[Border::Bottom | Border::Left][1] = corner[1].transformedBy(transform); m_corners[Border::Bottom | Border::Left][2] = corner[2].transformedBy(transform); } void ObjectFrame::Outline::resized() { updateCorners(); } bool ObjectFrame::Outline::hitTest(juce::Point<int> const& _pt, HitTester& hit_tester) const { const auto pt = _pt.toFloat(); bool success = false; if (m_corners.at(Border::Left | Border::Top)[1].contains(pt) || m_corners.at(Border::Top | Border::Right)[0].contains(pt)) { hit_tester.m_zone = HitTester::Zone::Border; hit_tester.m_border |= HitTester::Border::Top; success = true; } if(m_corners.at(Border::Top | Border::Right)[1].contains(pt) || m_corners.at(Border::Right | Border::Bottom)[0].contains(pt)) { hit_tester.m_zone = HitTester::Zone::Border; hit_tester.m_border |= HitTester::Border::Right; success = true; } if(m_corners.at(Border::Right | Border::Bottom)[1].contains(pt) || m_corners.at(Border::Bottom | Border::Left)[0].contains(pt)) { hit_tester.m_zone = HitTester::Zone::Border; hit_tester.m_border |= HitTester::Border::Bottom; success = true; } if(m_corners.at(Border::Bottom | Border::Left)[1].contains(pt) || m_corners.at(Border::Left | Border::Top)[0].contains(pt)) { hit_tester.m_zone = HitTester::Zone::Border; hit_tester.m_border |= HitTester::Border::Left; success = true; } if(hit_tester.m_zone == HitTester::Zone::Border) { hit_tester.m_border &= ~HitTester::Border::None; } return success; } void ObjectFrame::Outline::drawCorner(juce::Graphics & g, Border border) { g.fillRect(m_corners[border][2]); g.fillRect(m_corners[border][1]); } void ObjectFrame::Outline::paint(juce::Graphics & g) { g.setColour(findColour(PatcherView::ColourIds::Selection)); const auto outline_bounds = getLocalBounds().toFloat(); const float thickness = m_resize_thickness; g.drawRect(outline_bounds.reduced(thickness*0.75), thickness*0.25); /* // The following code do the same const auto object_bounds = outline_bounds.reduced(m_resize_thickness); juce::RectangleList<float> rectangles (outline_bounds); rectangles.subtract(object_bounds); rectangles.subtract(object_bounds.reduced(m_resize_thickness, -m_resize_thickness)); rectangles.subtract(object_bounds.reduced(-m_resize_thickness, m_resize_thickness)); rectangles.consolidate(); const juce::PathStrokeType stroke (1.f); g.strokePath(path, stroke); */ drawCorner(g, Border::Left | Border::Top); drawCorner(g, Border::Top | Border::Right); drawCorner(g, Border::Right | Border::Bottom); drawCorner(g, Border::Bottom | Border::Left); } }
23,488
C++
.cpp
535
30.26729
143
0.541932
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,371
KiwiApp_EditableObjectView.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Patcher/KiwiApp_Objects/KiwiApp_EditableObjectView.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 : [email protected] ============================================================================== */ #include <KiwiApp_Patcher/KiwiApp_Objects/KiwiApp_EditableObjectView.h> namespace kiwi { // ================================================================================ // // EDITABLE OBJECT VIEW // // ================================================================================ // EditableObjectView::EditableObjectView(model::Object & object_model) : ObjectView(object_model) , m_label(*this) { m_label.setFont(14); m_label.setMinimumHorizontalScale(0); m_label.setInterceptsMouseClicks(false, false); m_label.setBorderSize(juce::BorderSize<int>(getPadding())); m_label.setJustificationType(juce::Justification::topLeft); setMinimumWidth(20); setMinimumHeight(20); canGrowVertically(false); canGrowHorizontally(true); } EditableObjectView::~EditableObjectView() {} void EditableObjectView::checkBounds(juce::Rectangle<int>& bounds, juce::Rectangle<int> const& prev_bounds, juce::Rectangle<int> const& limits, bool stretching_top, bool stretching_left, bool stretching_bottom, bool stretching_right) { // the resize routine could impose a different ratio to our box // but we do not support fixed ratio for text box now // Todo: handle fixed ratio by resizing font height. setFixedAspectRatio(0); juce::ComponentBoundsConstrainer::checkBounds(bounds, prev_bounds, limits, stretching_top, stretching_left, stretching_bottom, stretching_right); if(!canGrowVertically()) { if(stretching_top) { bounds.setY(prev_bounds.getY()); } bounds.setHeight(prev_bounds.getHeight()); } const auto new_width = std::max(bounds.getWidth(), getMinWidth()); const auto text_bounds = getTextBoundingBox(getLabel().getText(), new_width); bounds.setHeight(std::max<int>(text_bounds.getHeight(), getMinHeight())); } void EditableObjectView::setEditable(bool editable) { m_editable = editable; } void EditableObjectView::edit() { if (m_editable) { m_label.showEditor(); } } void EditableObjectView::setText(juce::String const& new_text) { m_label.setText(new_text, juce::NotificationType::dontSendNotification); } juce::String EditableObjectView::getText() const { return m_label.getText(); } void EditableObjectView::setFont(juce::Font font) { m_label.setFont(font); } juce::Font EditableObjectView::getFont() const { return m_label.getFont(); } void EditableObjectView::setPadding(int padding) { m_padding = std::min<int>(0, padding); } int EditableObjectView::getPadding() const { return m_padding; } int EditableObjectView::getMinHeight() const { return getFont().getHeight() + m_padding * 2; } int EditableObjectView::getMinWidth() const { return getFont().getHeight() + m_padding * 2; } void EditableObjectView::resized() { m_label.setBounds(getLocalBounds()); } juce::Rectangle<float> EditableObjectView::getTextBoundingBox(juce::String const& text, float max_width) const { juce::GlyphArrangement arr; const int padding = getPadding(); const int side_padding = padding * 2; const float max_line_width = max_width - side_padding; arr.addJustifiedText (getFont(), text, padding, padding, max_line_width, juce::Justification::topLeft); const auto bounds = arr.getBoundingBox(0, -1, true); return bounds.withHeight(bounds.getHeight() + side_padding); } void EditableObjectView::labelTextChanged (juce::Label* label) { textChanged(); m_listeners.call(&EditableObjectView::Listener::textChanged, m_label.getText().toStdString()); } juce::Label & EditableObjectView::getLabel() { return m_label; } void EditableObjectView::editorHidden (juce::Label* label, juce::TextEditor& text_editor) { m_label.setInterceptsMouseClicks(false, false); m_listeners.call(&EditableObjectView::Listener::editorHidden); } void EditableObjectView::editorShown(juce::Label* label, juce::TextEditor& text_editor) { m_label.setInterceptsMouseClicks(true, true); m_listeners.call(&EditableObjectView::Listener::editorShown); } void EditableObjectView::addListener(Listener& listener) { m_listeners.add(listener); } void EditableObjectView::removeListener(Listener& listener) { m_listeners.remove(listener); } void EditableObjectView::paint(juce::Graphics& g) { g.fillAll(findColour(EditableObjectView::ColourIds::Background)); } void EditableObjectView::drawLabel(juce::Graphics& g) { if(!m_label.isBeingEdited()) { g.setColour (m_label.findColour(juce::Label::ColourIds::textColourId)); g.setFont(getFont()); g.drawMultiLineText(m_label.getText(), getPadding(), getFont().getHeight(), m_label.getWidth() - getPadding() * 2); } } // ================================================================================ // // LABEL // // ================================================================================ // EditableObjectView::Label::Label(EditableObjectView & object_view) : juce::Label() , m_object_view(object_view) { addListener(&m_object_view); } EditableObjectView::Label::~Label() { removeListener(&m_object_view); } juce::TextEditor* EditableObjectView::Label::createEditorComponent() { return m_object_view.createdTextEditor(); } void EditableObjectView::Label::paint(juce::Graphics& g) { m_object_view.drawLabel(g); } }
7,945
C++
.cpp
190
30.426316
94
0.539717
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,372
KiwiApp_ObjectView.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Patcher/KiwiApp_Objects/KiwiApp_ObjectView.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 : [email protected] ============================================================================== */ #include <juce_gui_basics/juce_gui_basics.h> #include <KiwiApp.h> #include <KiwiApp_Patcher/KiwiApp_Objects/KiwiApp_ObjectFrame.h> #include <KiwiApp_Patcher/KiwiApp_Objects/KiwiApp_ObjectView.h> #include <KiwiModel/KiwiModel_DocumentManager.h> namespace kiwi { // ================================================================================ // // OBJECT VIEW // // ================================================================================ // ObjectView::ObjectView(model::Object & object_model) : m_model(object_model) , m_master(this, [](ObjectView*){}) , m_resizing_flags(HitTester::Border::None) { object_model.addListener(*this); canGrowHorizontally(true); canGrowVertically(true); } ObjectView::~ObjectView() { getModel().removeListener(*this); } void ObjectView::setAttribute(std::string const& name, tool::Parameter const& parameter) { model::Object& object_model = getModel(); object_model.setAttribute(name, parameter); const auto commit_msg = object_model.getName() + " \"" + name + "\" changed"; model::DocumentManager::commit(object_model, commit_msg); } void ObjectView::setParameter(std::string const& name, tool::Parameter const& parameter) { getModel().setParameter(name, parameter); } void ObjectView::modelAttributeChanged(std::string const& name, tool::Parameter const& param) { attributeChanged(name, param); } void ObjectView::modelParameterChanged(std::string const& name, tool::Parameter const& param) { parameterChanged(name, param); } void ObjectView::attributeChanged(std::string const& name, tool::Parameter const& param) { } void ObjectView::parameterChanged(std::string const& name, tool::Parameter const& param) { } model::Object& ObjectView::getModel() const { return m_model; } juce::Rectangle<int> ObjectView::getOutline() const { return getLocalBounds(); } void ObjectView::drawOutline(juce::Graphics & g) { g.setColour(findColour(ObjectView::ColourIds::Outline)); const auto border_size = KiwiApp::useLookAndFeel().getObjectBorderSize(); g.drawRect(getOutline().toFloat(), border_size); } void ObjectView::lockStatusChanged(bool is_locked) { // nothing to do by default } int ObjectView::getResizingFlags() const { return m_resizing_flags; } bool ObjectView::canGrowHorizontally() const { return ((m_resizing_flags & HitTester::Border::Left) || m_resizing_flags & HitTester::Border::Right); } bool ObjectView::canGrowVertically() const { return ((m_resizing_flags & HitTester::Border::Top) || m_resizing_flags & HitTester::Border::Bottom); } void ObjectView::canGrowHorizontally(bool can) { if(can) { m_resizing_flags |= HitTester::Border::Left; m_resizing_flags |= HitTester::Border::Right; } else { m_resizing_flags &= ~HitTester::Border::Left; m_resizing_flags &= ~HitTester::Border::Right; } } void ObjectView::canGrowVertically(bool can) { if(can) { m_resizing_flags |= HitTester::Border::Top; m_resizing_flags |= HitTester::Border::Bottom; } else { m_resizing_flags &= ~HitTester::Border::Top; m_resizing_flags &= ~HitTester::Border::Bottom; } } // ================================================================================ // // SCHEDULER // // ================================================================================ // tool::Scheduler<> & ObjectView::getScheduler() const { return KiwiApp::useScheduler(); } void ObjectView::defer(std::function<void()> call_back) { std::weak_ptr<ObjectView> object(m_master); getScheduler().defer([object, cb = std::move(call_back)]() { if (!object.expired()) { cb(); } }); } void ObjectView::schedule(std::function<void()> call_back, tool::Scheduler<>::duration_t delay) { std::weak_ptr<ObjectView> object(m_master); getScheduler().schedule([object, cb = std::move(call_back)]() { if (!object.expired()) { cb(); } }, delay); } }
5,807
C++
.cpp
150
30.393333
100
0.53863
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,373
KiwiApp_NumberTildeView.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Patcher/KiwiApp_Objects/KiwiApp_NumberTildeView.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 : [email protected] ============================================================================== */ #include <KiwiApp_Patcher/KiwiApp_Objects/KiwiApp_NumberTildeView.h> #include <KiwiApp_Patcher/KiwiApp_Factory.h> namespace kiwi { // ================================================================================ // // NUMBER TILDE VIEW // // ================================================================================ // void NumberTildeView::declare() { Factory::add<NumberTildeView>("number~", &NumberTildeView::create); } std::unique_ptr<ObjectView> NumberTildeView::create(model::Object & object_model) { return std::make_unique<NumberTildeView>(object_model); } NumberTildeView::NumberTildeView(model::Object & object_model) : NumberViewBase(object_model) { setEditable(false); setInterceptsMouseClicks(false, false); } void NumberTildeView::drawIcon (juce::Graphics& g) const { g.setColour (findColour (ObjectView::ColourIds::Active)); g.setFont(22.f); g.drawFittedText("~", getLocalBounds().withWidth(getHeight()).withX(2), juce::Justification::centredLeft, 1); } void NumberTildeView::parameterChanged(std::string const& name, tool::Parameter const& param) { if (name == "value") { setDisplayNumber(param[0].getFloat()); } } void NumberTildeView::displayNumberChanged(double new_number) { } NumberTildeView::~NumberTildeView() { } }
2,443
C++
.cpp
55
38.054545
97
0.554025
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,374
KiwiApp_NumberViewBase.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Patcher/KiwiApp_Objects/KiwiApp_NumberViewBase.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 : [email protected] ============================================================================== */ #include <KiwiModel/KiwiModel_Objects/KiwiModel_Number.h> #include <KiwiApp_Patcher/KiwiApp_Objects/KiwiApp_NumberViewBase.h> #include <KiwiApp_Patcher/KiwiApp_Factory.h> namespace kiwi { // ================================================================================ // // NUMBER VIEW BASE // // ================================================================================ // NumberViewBase::NumberViewBase(model::Object & object_model) : EditableObjectView(object_model) , m_value(0) , m_indent(9) { juce::Label & label = getLabel(); label.setText("0.", juce::NotificationType::dontSendNotification); label.setColour(juce::Label::backgroundColourId, findColour(ObjectView::ColourIds::Background)); label.setColour(juce::Label::backgroundWhenEditingColourId, findColour(ObjectView::ColourIds::Background)); label.setColour(juce::Label::textColourId, findColour(ObjectView::ColourIds::Text)); label.setColour(juce::Label::textWhenEditingColourId, findColour(ObjectView::ColourIds::Text)); label.setMinimumHorizontalScale(1); label.setInterceptsMouseClicks(false, false); addAndMakeVisible(label); setMinimumSize(20., getMinHeight()); } NumberViewBase::~NumberViewBase() {} void NumberViewBase::paint(juce::Graphics & g) { g.fillAll(findColour(ObjectView::ColourIds::Background)); } void NumberViewBase::paintOverChildren (juce::Graphics& g) { drawOutline(g); drawIcon(g); } void NumberViewBase::drawIcon (juce::Graphics& g) const { // nothing by default } void NumberViewBase::resized() { juce::Rectangle<int> label_bounds = getLocalBounds(); label_bounds.removeFromLeft(m_indent); getLabel().setBounds(label_bounds); } double NumberViewBase::getDisplayNumber() const { return m_value; } void NumberViewBase::setDisplayNumber(double number) { m_value = number; juce::String display_value(std::to_string(m_value)); display_value = display_value.trimCharactersAtEnd("0"); getLabel().setText(display_value, juce::NotificationType::dontSendNotification); } void NumberViewBase::textChanged() { m_value = getLabel().getText().getDoubleValue(); displayNumberChanged(m_value); } juce::TextEditor* NumberViewBase::createdTextEditor() { juce::TextEditor * editor = new juce::TextEditor(); editor->setBounds(getLocalBounds()); editor->setBorder(juce::BorderSize<int>(0)); editor->setColour(juce::TextEditor::ColourIds::textColourId, getLabel().findColour(juce::Label::textWhenEditingColourId)); editor->setColour(juce::TextEditor::backgroundColourId, getLabel().findColour(juce::Label::backgroundWhenEditingColourId)); editor->setColour(juce::TextEditor::highlightColourId, findColour(ObjectView::ColourIds::Highlight, true).withAlpha(0.4f)); editor->setColour(juce::TextEditor::outlineColourId, juce::Colours::transparentWhite); editor->setColour(juce::TextEditor::focusedOutlineColourId, juce::Colours::transparentWhite); editor->setScrollbarsShown(false); editor->setScrollToShowCursor(true); editor->setReturnKeyStartsNewLine(false); editor->setMultiLine(true, false); editor->setInterceptsMouseClicks(true, false); editor->setInputFilter(new juce::TextEditor::LengthAndCharacterRestriction(-1, "0123456789.-"), true); return editor; } }
4,885
C++
.cpp
99
39.808081
110
0.616009
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,375
KiwiApp_MessageView.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Patcher/KiwiApp_Objects/KiwiApp_MessageView.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 : [email protected] ============================================================================== */ #include <KiwiModel/KiwiModel_DocumentManager.h> #include <KiwiApp_Patcher/KiwiApp_Objects/KiwiApp_MessageView.h> #include <KiwiApp_Patcher/KiwiApp_Factory.h> namespace kiwi { // ================================================================================ // // MESSAGE VIEW // // ================================================================================ // void MessageView::declare() { Factory::add<MessageView>("message", &MessageView::create); } std::unique_ptr<ObjectView> MessageView::create(model::Object & object_model) { return std::make_unique<MessageView>(object_model); } MessageView::MessageView(model::Object & object_model) : EditableObjectView(object_model) , m_output_message(object_model.getSignal<>(model::Message::Signal::outputMessage)) , m_active(false) { setColour(ObjectView::ColourIds::Background, juce::Colours::whitesmoke); setColour(ObjectView::ColourIds::Outline, juce::Colours::whitesmoke.withAlpha(0.f)); juce::Label & label = getLabel(); const auto object_text = object_model.getAttribute("text")[0].getString(); label.setText(object_text, juce::NotificationType::dontSendNotification); label.setColour(juce::Label::backgroundColourId, findColour(ObjectView::ColourIds::Background)); label.setColour(juce::Label::backgroundWhenEditingColourId, findColour(ObjectView::ColourIds::Background)); label.setColour(juce::Label::textColourId, findColour(ObjectView::ColourIds::Text)); label.setColour(juce::Label::textWhenEditingColourId, findColour(ObjectView::ColourIds::Text)); addAndMakeVisible(label); } MessageView::~MessageView() {} void MessageView::mouseDown(juce::MouseEvent const& e) { m_active = true; m_output_message(); repaint(); } void MessageView::mouseUp(juce::MouseEvent const& e) { m_active = false; repaint(); } void MessageView::paint(juce::Graphics& g) { const float roundness = 3.f; const float bordersize = 1.f; const auto bounds = getLocalBounds().toFloat().reduced(bordersize*0.5f); const auto bgcolor = findColour(ObjectView::ColourIds::Background); const auto active_color = findColour(ObjectView::ColourIds::Active); const bool clicked = m_active; g.setColour(bgcolor.contrasting(clicked ? 0.1 : 0.)); g.fillRoundedRectangle(bounds, roundness); g.setColour(clicked ? active_color : bgcolor.contrasting(0.25)); g.drawRoundedRectangle(bounds, roundness, bordersize); } void MessageView::paintOverChildren (juce::Graphics& g) { if(getLabel().isBeingEdited()) return; // abort g.setColour(m_active ? findColour(ObjectView::ColourIds::Active) : findColour(ObjectView::ColourIds::Background).contrasting(0.25)); const auto bounds = getLocalBounds(); const auto topright = bounds.getTopRight().toFloat(); juce::Path corner; corner.addTriangle(topright.translated(-10.f, 0.f), topright, topright.translated(0, 10)); g.fillPath(corner); } void MessageView::textEditorTextChanged(juce::TextEditor& editor) { const auto text = editor.getText(); auto single_line_text_width = editor.getFont().getStringWidthFloat(text) + 16 + 2; auto width = std::max<float>(getWidth() + 16, single_line_text_width); auto prev_width = getWidth(); auto text_bounds = getTextBoundingBox(text, width); setSize(std::max<int>(prev_width, single_line_text_width), std::max(std::min<int>(text_bounds.getHeight(), getHeight()), getMinHeight())); } void MessageView::attributeChanged(std::string const& name, tool::Parameter const& param) { static const std::string name_text = "text"; if (name == name_text) { setText(param[0].getString()); checkComponentBounds(this); } } void MessageView::textChanged() { // Parse text and convert it back to string to display the formated version. const auto atoms = tool::AtomHelper::parse(getText().toStdString(), tool::AtomHelper::ParsingFlags::Comma | tool::AtomHelper::ParsingFlags::Dollar); auto formatted_text = tool::AtomHelper::toString(atoms); const int text_width = getFont().getStringWidth(formatted_text); model::Object & model = getModel(); model.setWidth(std::max(26, text_width) + 10); model.setHeight(getMinHeight()); // set the attribute and label text with formated text getLabel().setText(formatted_text, juce::NotificationType::dontSendNotification); setAttribute("text", tool::Parameter(tool::Parameter::Type::String, {std::move(formatted_text)})); } juce::TextEditor* MessageView::createdTextEditor() { auto* editor = new juce::TextEditor(); editor->setColour(juce::TextEditor::ColourIds::textColourId, getLabel().findColour(juce::Label::textWhenEditingColourId)); editor->setColour(juce::TextEditor::backgroundColourId, juce::Colours::transparentWhite); editor->setColour(juce::TextEditor::highlightColourId, findColour(ObjectView::ColourIds::Highlight, true).withAlpha(0.4f)); editor->setColour(juce::TextEditor::outlineColourId, juce::Colours::transparentWhite); editor->setColour(juce::TextEditor::focusedOutlineColourId, juce::Colours::transparentWhite); editor->setBounds(getLocalBounds()); editor->setIndents(getPadding(), getPadding()); editor->setBorder(juce::BorderSize<int>(0)); editor->setFont(getFont()); editor->setJustification(getLabel().getJustificationType()); editor->setScrollbarsShown(false); editor->setScrollToShowCursor(true); editor->setReturnKeyStartsNewLine(false); editor->setMultiLine(true, true); editor->setInterceptsMouseClicks(true, false); editor->addListener(this); return editor; } }
7,905
C++
.cpp
152
39.861842
96
0.596574
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,376
KiwiApp_MeterTildeView.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Patcher/KiwiApp_Objects/KiwiApp_MeterTildeView.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 : [email protected] ============================================================================== */ #include <cmath> #include <functional> #include <KiwiModel/KiwiModel_Objects/KiwiModel_MeterTilde.h> #include <KiwiApp.h> #include <KiwiApp_Patcher/KiwiApp_Objects/KiwiApp_MeterTildeView.h> #include <KiwiApp_Patcher/KiwiApp_Factory.h> namespace kiwi { // ================================================================================ // // METER~ VIEW // // ================================================================================ // void MeterTildeView::declare() { Factory::add<MeterTildeView>("meter~", &MeterTildeView::create); } std::unique_ptr<ObjectView> MeterTildeView::create(model::Object & model) { return std::make_unique<MeterTildeView>(model); } MeterTildeView::MeterTildeView(model::Object & object_model) : ObjectView(object_model) , m_connection(object_model.getSignal<float>(model::MeterTilde::Signal::PeakChanged) .connect([this](float new_peak){ peakChanged(new_peak); })) { const size_t num_leds = 12; m_leds.resize(num_leds); for(size_t i = 0; i < num_leds; ++i) { auto& led = m_leds[i]; led.min_db = -3.f * (num_leds - (i + 1.f)); led.colour = computeGradientColour(static_cast<float>(i) / (num_leds - 1.f)); } computeActiveLed(-120.f); } MeterTildeView::~MeterTildeView() {} void MeterTildeView::resized() { const auto bounds = getLocalBounds().toFloat(); const int min = 10; const int max = 30; const bool vertical = (getWidth() <= getHeight()); setMinimumSize(vertical ? min : max, vertical ? max : min); const float num_leds = m_leds.size(); const float padding = m_padding; const float sep = m_led_distance; auto space = bounds.reduced(padding, padding); if(vertical) { const auto led_space = (space.getHeight() / num_leds); for(auto& led : m_leds) { led.bounds = (space.removeFromBottom(led_space) .removeFromTop(led_space - sep)); } } else { const auto led_space = (space.getWidth() / num_leds); for(auto& led : m_leds) { led.bounds = (space.removeFromLeft(led_space) .removeFromLeft(led_space - sep)); } } } juce::Colour MeterTildeView::computeGradientColour(float delta) const { assert((delta >= 0 && delta <= 1.) && "meter wrong index for gradient"); float hue = m_cold_colour.getHue() + delta * (m_hot_colour.getHue() - m_cold_colour.getHue()); float saturation = m_cold_colour.getSaturation() + delta * (m_hot_colour.getSaturation() - m_cold_colour.getSaturation()); float brightness = m_cold_colour.getBrightness() + delta * (m_hot_colour.getBrightness() - m_cold_colour.getBrightness()); float alpha = 1; return juce::Colour(hue, saturation, brightness, alpha); } void MeterTildeView::computeActiveLed(float peak_db) { auto it = std::find_if(m_leds.rbegin(), m_leds.rend(), [peak_db](Led const& led) { return peak_db >= led.min_db; }); m_active_led = it != m_leds.rend() ? m_leds.rend() - (it + 1) : -1; } void MeterTildeView::peakChanged(float new_peak) { defer([this, new_peak]() { float peak_db = 20. * log10(new_peak); computeActiveLed(peak_db); repaint(); }); } void MeterTildeView::paint(juce::Graphics & g) { const auto bgcolor = findColour(ObjectView::ColourIds::Background); g.fillAll(bgcolor); const auto led_border_size = 0.5f; const auto outline_color = bgcolor.contrasting(0.2); for(int i = 0; i < m_leds.size(); i++) { const auto& led = m_leds[i]; if (i <= m_active_led) { g.setColour(led.colour); g.fillRect(led.bounds); } else { g.setColour(outline_color); g.drawRect(led.bounds, led_border_size); } } g.setColour(outline_color); drawOutline(g); } }
5,507
C++
.cpp
133
31.466165
98
0.52974
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,377
KiwiApp_DspDeviceManager.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Audio/KiwiApp_DspDeviceManager.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 : [email protected] ============================================================================== */ #include <juce_audio_utils/juce_audio_utils.h> #include "KiwiApp_DspDeviceManager.h" #include "../KiwiApp_General/KiwiApp_StoredSettings.h" #include "../KiwiApp.h" namespace kiwi { // ================================================================================ // // DSP DEVICE MANAGER // // ================================================================================ // DspDeviceManager::DspDeviceManager() : m_input_matrix(nullptr), m_output_matrix(nullptr), m_chains(), m_is_playing(false), m_mutex() { juce::ScopedPointer<juce::XmlElement> previous_settings(getGlobalProperties().getXmlValue("Audio Settings")); if (previous_settings) { initialise(256, 256, previous_settings, false); } else { initialiseWithDefaultDevices(256, 256); } } DspDeviceManager::~DspDeviceManager() { juce::ScopedPointer<juce::XmlElement> data(createStateXml()); getGlobalProperties().setValue("Audio Settings", data); stopAudio(); } void DspDeviceManager::add(dsp::Chain& chain) { if(std::find(m_chains.begin(), m_chains.end(), &chain) == m_chains.cend()) { if (m_is_playing) { juce::AudioIODevice * const device = getCurrentAudioDevice(); chain.prepare(device->getCurrentSampleRate(), device->getCurrentBufferSizeSamples()); } { juce::GenericScopedLock<juce::CriticalSection> lock(getAudioCallbackLock()); m_chains.push_back(&chain); } } } void DspDeviceManager::remove(dsp::Chain& chain) { const auto it = std::find(m_chains.begin(), m_chains.end(), &chain); if(it != m_chains.cend()) { (*it)->release(); { juce::GenericScopedLock<juce::CriticalSection> lock(getAudioCallbackLock()); m_chains.erase(it); } } } void DspDeviceManager::startAudio() { addAudioCallback(this); m_is_playing = true; KiwiApp::commandStatusChanged(); } void DspDeviceManager::stopAudio() { removeAudioCallback(this); m_is_playing = false; KiwiApp::commandStatusChanged(); } bool DspDeviceManager::isAudioOn() const { return m_is_playing; }; void DspDeviceManager::addToChannel(size_t const channel, dsp::Signal const& output_signal) { if (channel < m_output_matrix->getNumberOfChannels() && output_signal.size() == m_output_matrix->getVectorSize()) { (*m_output_matrix)[channel].add(output_signal); } } void DspDeviceManager::getFromChannel(size_t const channel, dsp::Signal & input_signal) { if (channel < m_input_matrix->getNumberOfChannels() && input_signal.size() == m_input_matrix->getVectorSize()) { input_signal.copy((*m_input_matrix)[channel]); } } void DspDeviceManager::tick() const noexcept { for(dsp::Chain* chain : m_chains) { chain->tick(); } } void DspDeviceManager::audioDeviceAboutToStart(juce::AudioIODevice *device) { size_t sample_rate = device->getCurrentSampleRate(); size_t buffer_size = device->getCurrentBufferSizeSamples(); for(dsp::Chain * chain : m_chains) { try { chain->prepare(sample_rate, buffer_size); } catch(dsp::LoopError & e) { KiwiApp::use().error(e.what()); } } // allocate input matrix m_input_matrix.reset(new dsp::Buffer(device->getActiveInputChannels().getHighestBit() + 1, device->getCurrentBufferSizeSamples())); // allocate output matrix m_output_matrix.reset(new dsp::Buffer(device->getActiveOutputChannels().getHighestBit() + 1, device->getCurrentBufferSizeSamples())); } void DspDeviceManager::audioDeviceStopped() { for(dsp::Chain * chain : m_chains) { chain->release(); } // clear input matrix m_input_matrix.reset(); // clear output matrix m_output_matrix.reset(); } void DspDeviceManager::audioDeviceIOCallback(float const** inputs, int numins, float** outputs, int numouts, int vector_size) { //@todo may be pointing to same samples instead of copying them for(int i = 0; i < numins; ++i) { dsp::Signal& channel = (*m_input_matrix)[i]; float const* const input_channel = inputs[i]; for(int j = 0; j < vector_size; ++j) { channel[j] = input_channel[j]; } } tick(); for(int i = 0; i < numouts; ++i) { dsp::Signal const& channel = (*m_output_matrix)[i]; float* const output_channel = outputs[i]; for(int j = 0; j < vector_size; ++j) { output_channel[j] = channel[j]; } } for (int i = 0; i < numouts; ++i) { (*m_output_matrix)[i].fill(0); } } }
6,623
C++
.cpp
173
27.676301
121
0.529887
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,378
KiwiApp_AuthPanel.cpp
Musicoll_Kiwi/Client/Source/KiwiApp_Auth/KiwiApp_AuthPanel.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 : [email protected] ============================================================================== */ #include <KiwiApp_Auth/KiwiApp_AuthPanel.h> #include <KiwiApp.h> #include <KiwiApp_General/KiwiApp_CommandIDs.h> namespace kiwi { // ================================================================================ // // LOGIN FORM // // ================================================================================ // LoginForm::LoginForm() : FormComponent("Login", "login...") { setState(State::Login); } void LoginForm::setState(State state) { clearFields(); m_state = state; switch (state) { case State::Login: { addField<Field::KiwiLogo>(); addField<Field::SingleLineText>("username", KiwiApp::getCurrentUser().getName(), "Username or Email"); addField<Field::Password>("password", "", "Password"); addField<Field::ToggleButton>("remember_me", "Remember me", getAppSettings().network().getRememberUserFlag()); addField<Field::TextButton>("forgot_pass", "Forgot password ?", [this]() { setState(State::Request); showAlert("Enter email to request reset token", AlertBox::Type::Info); }); setSubmitText("Login"); break; } case State::Request: { addField<Field::KiwiLogo>(); addField<Field::SingleLineText>("email", "", "Email"); addField<Field::TextButton>("already_have", "Already have token ?", [this]() { setState(State::Reset); showAlert("Enter reset token.", AlertBox::Type::Info); }); setSubmitText("Send"); break; } case State::Reset: { addField<Field::KiwiLogo>(); addField<Field::SingleLineText>("token", "", "Token"); addField<Field::SingleLineText>("newpass", "", "New Password"); setSubmitText("Send"); break; } } setSize(getWidth(), getBestHeight()); } void LoginForm::performPassReset() { Component::SafePointer<LoginForm> form(this); auto success_callback = [form](std::string const& message) { KiwiApp::useScheduler().schedule([form]() { if (form) { form.getComponent()->setState(State::Login); form.getComponent()->showAlert("Password reset. Try login again.", AlertBox::Type::Info); } }); }; auto error_callback = [form](Api::Error error) { std::string error_message = error.getMessage(); KiwiApp::useScheduler().schedule([form, error_message]() { if (form) { form.getComponent()->showAlert(error_message, AlertBox::Type::Error); } }); }; const std::string token = getFieldValue("token").toString().toStdString(); const std::string newpass = getFieldValue("newpass").toString().toStdString(); KiwiApp::useApi().resetPassword(token, newpass, success_callback, error_callback); } void LoginForm::performPassRequest() { Component::SafePointer<LoginForm> form(this); auto success_callback = [form](std::string const& message) { KiwiApp::useScheduler().schedule([form]() { form.getComponent()->setState(State::Reset); form.getComponent()->showAlert("Reset token sent. Check your email.", AlertBox::Type::Info); }); }; auto error_callback = [form](Api::Error error) { std::string error_message = error.getMessage(); KiwiApp::useScheduler().schedule([form, error_message]() { form.getComponent()->showAlert(error_message, AlertBox::Type::Error); }); }; const std::string email = getFieldValue("email").toString().toStdString(); KiwiApp::useApi().requestPasswordToken(email, success_callback, error_callback); } void LoginForm::performLogin() { const auto username = getFieldValue("username").toString(); const auto password = getFieldValue("password").toString(); const bool remember_me = getFieldValue("remember_me").getValue(); if(username.trim().length() < 3) { showAlert("Please enter a valid email address or username!", AlertBox::Type::Error); return; } if(password.trim().length() < 3) { showAlert("Please enter a valid password!", AlertBox::Type::Error); return; } showOverlay(); Component::SafePointer<LoginForm> form(this); auto success_callback = [form, remember_me](Api::AuthUser auth_user) { KiwiApp::useScheduler().schedule([form, remember_me, auth_user]() { getAppSettings().network().setRememberUserFlag(remember_me); KiwiApp::use().setAuthUser(auth_user); if (form) { form.getComponent()->showSuccessOverlay("Login success !"); KiwiApp::useScheduler().schedule([form](){ if (form) { form.getComponent()->dismiss(); } }, std::chrono::milliseconds(1000)); } }, std::chrono::milliseconds(500)); }; auto error_callback = [form](Api::Error error) { KiwiApp::useScheduler().schedule([form, message = error.getMessage()]() { if (form) { form.getComponent()->hideOverlay(); form.getComponent()->showAlert(message, AlertBox::Type::Error); } }, std::chrono::milliseconds(500)); }; KiwiApp::useApi().login(username.toStdString(), password.toStdString(), std::move(success_callback), std::move(error_callback)); } void LoginForm::onUserSubmit() { switch (m_state) { case State::Login: { performLogin(); break; } case State::Request: { performPassRequest(); break; } case State::Reset: { performPassReset(); break; } } } void LoginForm::onUserCancelled() { switch(m_state) { case State::Login: { dismiss(); break; } case State::Request: { setState(State::Login); break; } case State::Reset: { setState(State::Login); break; } } } // ================================================================================ // // SIGNUP FORM // // ================================================================================ // SignUpForm::SignUpForm() : FormComponent("Register", "register...") { addField<Field::KiwiLogo>(); addField<Field::SingleLineText>("username", "", "Username"); addField<Field::SingleLineText>("email", "", "Email"); addField<Field::Password>("password", "", "Password"); //addField<Field::Password>("password_check", "", "Password again..."); } void SignUpForm::onUserSubmit() { const auto username = getFieldValue("username").toString(); const auto email = getFieldValue("email").toString(); const auto password = getFieldValue("password").toString(); //const auto password_check = getFieldValue("password_check").toString(); if(username.trim().length() < 3) { showAlert("Please enter a valid user name!", AlertBox::Type::Error); return; } if(email.trim().length() < 3) { showAlert("Please enter a valid email address!", AlertBox::Type::Error); return; } if(password.trim().length() < 3) { showAlert("Please enter a valid password!", AlertBox::Type::Error); return; } /* if(password != password_check) { showAlert("The two passwords must be the same!", AlertBox::Type::Error); return; } */ showOverlay(); Component::SafePointer<SignUpForm> form(this); auto success_callback = [form](std::string message) { KiwiApp::useScheduler().schedule([form, message]() { if (form) { form.getComponent()->showSuccessOverlay(message); KiwiApp::useScheduler().schedule([form]() { SignUpForm * this_form = form.getComponent(); if (this_form) { if(AuthPanel* auth_panel = this_form->findParentComponentOfClass<AuthPanel>()) { this_form->hideOverlay(); auth_panel->setCurrentTabIndex(AuthPanel::FormType::Login); } } }, std::chrono::milliseconds(1000)); } }, std::chrono::milliseconds(500)); }; auto error_callback = [form](Api::Error error) { KiwiApp::useScheduler().schedule([form, message = error.getMessage()]() { if (form) { form.getComponent()->hideOverlay(); form.getComponent()->showAlert(message, AlertBox::Type::Error); } }, std::chrono::milliseconds(500)); }; KiwiApp::useApi().signup(username.toStdString(), email.toStdString(), password.toStdString(), std::move(success_callback), std::move(error_callback)); } // ================================================================================ // // AUTH PANEL // // ================================================================================ // AuthPanel::AuthPanel(FormType form_type) : juce::TabbedComponent(juce::TabbedButtonBar::Orientation::TabsAtTop) , m_login_form() , m_signup_form() { auto& lf = KiwiApp::useLookAndFeel(); const auto bgcolor = lf.getCurrentColourScheme().getUIColour(juce::LookAndFeel_V4::ColourScheme::UIColour::windowBackground); addTab("Login", bgcolor, &m_login_form, false, static_cast<int>(FormType::Login)); addTab("Register", bgcolor, &m_signup_form, false, static_cast<int>(FormType::SignUp)); m_login_form.addComponentListener(this); m_signup_form.addComponentListener(this); setCurrentTabIndex(static_cast<int>(form_type)); setColour(juce::TabbedComponent::ColourIds::outlineColourId, juce::Colours::transparentBlack); setColour(juce::TabbedComponent::ColourIds::backgroundColourId, bgcolor.contrasting(0.05)); const int width = 440; m_login_form.setSize(width, m_login_form.getBestHeight()); m_signup_form.setSize(width, m_signup_form.getBestHeight()); auto& current_comp = dynamic_cast<FormComponent&>(*getCurrentContentComponent()); setSize(width, current_comp.getBestHeight()); } AuthPanel::~AuthPanel() { ; } void AuthPanel::updateSize(FormType type) { switch(type) { case FormType::Login: { setSize(getWidth(), m_login_form.getBestHeight()); break; } case FormType::SignUp: { setSize(getWidth(), m_signup_form.getBestHeight()); break; } default: break; } } void AuthPanel::currentTabChanged(int new_tab_index, juce::String const& /*new_tab_name*/) { updateSize(FormType(new_tab_index)); } void AuthPanel::componentMovedOrResized(juce::Component& /*component*/, bool /*moved*/, bool resized) { if(resized) { updateSize(FormType(getCurrentTabIndex())); } } }
15,443
C++
.cpp
357
27.397759
133
0.470667
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,379
Main.cpp
Musicoll_Kiwi/Server/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 : [email protected] ============================================================================== */ #include <csignal> #include <atomic> #include <flip/contrib/RunLoopTimer.h> #include <KiwiModel/KiwiModel_DataModel.h> #include <KiwiServer/KiwiServer_Server.h> #include "KiwiServer_CommandLineParser.h" #include <json.hpp> std::atomic<bool> server_stopped(false); void showHelp() { std::cout << "Usage:\n"; std::cout << " -h shows this help message. \n"; std::cout << " -f set the json configuration file to use (required). \n"; std::cout << '\n'; std::cout << "ex: ./Server -f prod.json" << std::endl; } void on_interupt(int signal) { server_stopped.store(true); } void on_terminate(int signal) { server_stopped.store(true); } int main(int argc, char const* argv[]) { using namespace kiwi; using nlohmann::json; std::signal(SIGINT, on_interupt); // interupt, kill -2, Ctrl + C std::signal(SIGTERM, on_terminate); // terminate, kill (-15) CommandLineParser cl_parser(argc, argv); if(cl_parser.hasOption("-h")) { showHelp(); return 0; } const auto config_filepath = cl_parser.getOption("-f"); if(config_filepath.empty()) { std::cerr << "Error: Server need a configuration file:\n" << std::endl; showHelp(); return 0; } juce::File::getSpecialLocation(juce::File::SpecialLocationType::currentExecutableFile) .setAsCurrentWorkingDirectory(); const auto config_file = juce::File::getCurrentWorkingDirectory().getChildFile(config_filepath); if(!config_file.exists()) { std::cerr << "Error: Config file: \"" << config_file.getFullPathName() << "\" not found !" << std::endl; showHelp(); return 0; } model::DataModel::init(); json config; try { config = json::parse(config_file.loadFileAsString().toStdString()); } catch(json::parse_error& e) { std::cerr << "Parsing config file failed : " << e.what() << '\n'; return 0; } // check config entries: const std::vector<std::string> required_config_entries { "backend_directory", "session_port", "open_token", "kiwi_version" }; for (auto const& entry : required_config_entries) { if(! (config.find(entry) != config.end()) ) { std::cerr << entry << " entry needed in config file\n"; return 0; } } const std::string backend_path = config["backend_directory"]; const juce::File backend_dir {config_file.getParentDirectory().getChildFile(backend_path)}; const uint16_t session_port = config["session_port"]; const std::string token = config["open_token"]; const std::string kiwi_client_version = config["kiwi_version"]; try { server::Server kiwi_server(session_port, backend_dir, token, kiwi_client_version); flip::RunLoopTimer run_loop ([&kiwi_server] { kiwi_server.process(); return !server_stopped.load(); }, 0.02); std::cout << "[server] - running on port: " << std::to_string(session_port) << std::endl; std::cout << "[server] - backend_directory: " << backend_dir.getFullPathName().toStdString() << std::endl; run_loop.run(); std::cout << "[server] - stopped" << std::endl; } catch(std::runtime_error const& e) { std::cerr << "Launching server failed: \nerr : " << e.what() << "\n"; std::cerr << "Maybe someone is already listening on port " << std::to_string(session_port) << "\n"; return 0; } return 0; }
4,530
C++
.cpp
117
32.188034
114
0.606253
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,380
test_Signal.cpp
Musicoll_Kiwi/Test/Dsp/test_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 : [email protected] ============================================================================== */ #include "../catch.hpp" #include <KiwiDsp/KiwiDsp_Signal.h> using namespace kiwi; using namespace dsp; // ================================================================================ // // SIGNAL // // ================================================================================ // TEST_CASE("Dsp - Signal", "[Dsp, Signal]") { SECTION("Signal ctor - throws as bad alloc") { REQUIRE_THROWS_AS(Signal(-1), std::bad_alloc); } SECTION("Signal - move ctor") { const size_t size = 64; Signal sig1(size, 1.); REQUIRE(sig1.size() == size); REQUIRE(sig1.data() != nullptr); Signal sig2 = std::move(sig1); REQUIRE(sig1.size() == 0ul); REQUIRE(sig1.data() == nullptr); REQUIRE(sig2.size() == size); REQUIRE(sig2.data() != nullptr); for(int j = 0; j < size; ++j) { CHECK(sig2[j] == 1.); } } SECTION("Signal - copy") { Signal sig1(64, 0.); Signal sig2(64, 0.5); sig2.copy(sig1); for(int j = 0; j < sig2.size(); ++j) { CHECK(sig2[j] == sig1[j]); } } SECTION("Signal - move assignment") { size_t size = 64; Signal sig1(size, 0.5); Signal sig2(size); sig2 = std::move(sig1); CHECK(sig1.size() == 0); CHECK(sig1.data() == nullptr); REQUIRE(sig2.size() == size); REQUIRE(sig2.data() != nullptr); for(int j = 0; j < size; ++j) { CHECK(sig2[j] == 0.5); } } SECTION("Signal - double move assignment support") { size_t size = 64; Signal sig1(size, 0.5); Signal sig2 = std::move(sig1); CHECK(sig1.size() == 0); CHECK(sig1.data() == nullptr); REQUIRE(sig2.size() == size); REQUIRE(sig2.data() != nullptr); for(int j = 0; j < size; ++j) { CHECK(sig2[j] == 0.5); } sig2 = std::move(sig1); CHECK(sig1.size() == 0); CHECK(sig1.data() == nullptr); CHECK(sig2.size() == 0); CHECK(sig2.data() == nullptr); } SECTION("Signal::fill(sample_t const&)") { const size_t size = 64; Signal sig(size); sig.fill(1.); for(int j = 0; j < size; ++j) { CHECK(sig[j] == 1.); } } SECTION("Signal - add += signal") { const size_t size = 64; Signal sig1(size); for (int i = 0; i < size; ++i) { sig1[i] = 4 * i; } Signal sig2(size, 1.); sig1.add(sig2); for(int j = 0; j < size; ++j) { CHECK(sig1[j] == 4 * j + 1.); } } SECTION("Signal - add +") { const size_t size = 64; Signal sig1(size); for (int i = 0; i < size; ++i) { sig1[i] = 4 * i; } Signal sig2(size, 1.); Signal result(size, 0); Signal::add(sig1, sig2, result); for(int j = 0; j < result.size(); ++j) { CHECK(result[j] == 4 * j + 1.); } } }
4,321
C++
.cpp
129
24.341085
90
0.452581
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,381
test_Chain.cpp
Musicoll_Kiwi/Test/Dsp/test_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 : [email protected] ============================================================================== */ #include <memory> #include "../catch.hpp" #include <KiwiDsp/KiwiDsp_Chain.h> #include <KiwiDsp/KiwiDsp_Misc.h> #include "Processors.h" using namespace kiwi; using namespace dsp; // ==================================================================================== // // TEST CHAIN // // ==================================================================================== // //@todo Link is duplicated and Processor is duplicated TEST_CASE("Dsp - Chain", "[Dsp, Chain]") { const size_t samplerate = 44100ul; const size_t vectorsize = 64ul; SECTION("Chain released not compiled") { Chain chain; chain.release(); } SECTION("Chain modification") { Chain chain; const size_t sr = 2ul; const size_t vs = 2ul; std::shared_ptr<Processor> sig_1(new Sig(1.)); std::shared_ptr<Processor> plus_scalar(new PlusScalar(2.)); chain.addProcessor(sig_1); chain.addProcessor(plus_scalar); chain.connect(*sig_1, 0, *plus_scalar, 0); // Adding processor twice chain.addProcessor(sig_1); REQUIRE_THROWS_AS(chain.prepare(sr, vs), Error); std::shared_ptr<Processor> scalar_out(new PlusScalar(0.)); // Connect with non existing node. chain.connect(*sig_1, 0, *scalar_out, 0); REQUIRE_THROWS_AS(chain.prepare(sr, vs), Error); // Disconnect non existing node chain.disconnect(*sig_1, 0, *scalar_out, 0); REQUIRE_THROWS_AS(chain.prepare(sr, vs), Error); chain.release(); } SECTION("Chain compiled") { Chain chain; std::shared_ptr<Processor> sig_1(new Sig(1.3)); std::shared_ptr<Processor> plus_scalar(new PlusScalar(1.)); chain.addProcessor(sig_1); chain.addProcessor(plus_scalar); chain.connect(*sig_1, 0, *plus_scalar, 0); REQUIRE_NOTHROW(chain.prepare(samplerate, vectorsize)); chain.release(); } SECTION("Fanning Inlet process") { Chain chain; std::shared_ptr<Processor> sig_1(new Sig(1.)); std::shared_ptr<Processor> sig_2(new Sig(2.)); std::shared_ptr<Processor> sig_3(new Sig(3.)); std::shared_ptr<Processor> plus_scalar_0(new PlusScalar(0.)); chain.addProcessor(sig_1); chain.addProcessor(sig_2); chain.addProcessor(sig_3); chain.addProcessor(plus_scalar_0); chain.connect(*sig_1, 0, *plus_scalar_0, 0); chain.connect(*sig_2, 0, *plus_scalar_0, 0); chain.connect(*sig_3, 0, *plus_scalar_0, 0); REQUIRE_NOTHROW(chain.prepare(samplerate, vectorsize)); chain.release(); } SECTION("empty Chain compiled") { Chain chain; REQUIRE_NOTHROW(chain.prepare(samplerate, vectorsize)); chain.release(); } SECTION("Loop Detected") { Chain chain; std::shared_ptr<Processor> sig_1(new Sig(1.3)); std::shared_ptr<Processor> sig_2(new Sig(2.7)); std::shared_ptr<Processor> plus_scalar(new PlusScalar(1.)); std::shared_ptr<Processor> plus_signal(new PlusSignal()); chain.addProcessor(sig_1); chain.addProcessor(sig_2); chain.addProcessor(plus_scalar); chain.addProcessor(plus_signal); chain.connect(*sig_1, 0, *plus_scalar, 0); chain.connect(*plus_scalar, 0, *plus_signal, 0); chain.connect(*sig_2, 0, *plus_signal, 1); // Adding a connnection that creates a loop chain.connect(*plus_signal, 0, *plus_scalar, 0); REQUIRE_THROWS_AS(chain.prepare(0, 0), LoopError); } SECTION("non-connected inlets and outlets share same signals") { Chain chain; std::shared_ptr<Processor> sig_1(new Sig(1.)); std::shared_ptr<Processor> checker_1(new SharedSignalsChecker()); std::shared_ptr<Processor> checker_2(new SharedSignalsChecker()); chain.addProcessor(sig_1); chain.addProcessor(checker_1); chain.addProcessor(checker_2); chain.connect(*sig_1, 0, *checker_1, 1); chain.connect(*checker_1, 1, *checker_2, 1); REQUIRE_NOTHROW(chain.prepare(samplerate, vectorsize)); chain.tick(); Buffer const& in_1 = *dynamic_cast<SharedSignalsChecker&>(*checker_1).m_input; Buffer const& out_1 = *dynamic_cast<SharedSignalsChecker&>(*checker_1).m_output; Buffer const& in_2 = *dynamic_cast<SharedSignalsChecker&>(*checker_2).m_input; Buffer const& out_2 = *dynamic_cast<SharedSignalsChecker&>(*checker_2).m_output; // check that all unconnected inlet share the same signal pointer. CHECK(in_1[0].data() == in_1[2].data()); CHECK(in_1[0].data() == in_2[0].data()); CHECK(in_1[0].data() == in_2[2].data()); // different than connected inlet signal CHECK_FALSE(in_1[0].data() == in_1[1].data()); // check that all unconnected outlet of same index share the same signal pointer. CHECK(out_1[0].data() == out_2[0].data()); CHECK(out_1[2].data() == out_2[2].data()); CHECK_FALSE(out_1[0].data() == out_2[2].data()); CHECK_FALSE(out_1[1].data() == out_2[1].data()); REQUIRE_NOTHROW(chain.release()); } SECTION("Updating after first prepare") { Chain chain; const size_t sr = 2ul; const size_t vs = 4ul; std::shared_ptr<Processor> sig_1(new Sig(1.)); std::shared_ptr<Processor> sig_2(new Sig(2.)); std::shared_ptr<Processor> plus_signal(new PlusSignal()); std::string result; std::shared_ptr<Processor> print(new Print(result)); chain.addProcessor(sig_1); chain.addProcessor(plus_signal); chain.addProcessor(print); chain.connect(*sig_1, 0, *plus_signal, 0); chain.connect(*plus_signal, 0, *print, 0); chain.prepare(sr, vs); chain.tick(); CHECK(result == "[1.000000, 1.000000, 1.000000, 1.000000]"); // Adding a processors chain.addProcessor(sig_2); chain.update(); chain.tick(); CHECK(result == "[1.000000, 1.000000, 1.000000, 1.000000]"); // Connecting processor chain.connect(*sig_2, 0, *plus_signal, 1); chain.update(); chain.tick(); CHECK(result == "[3.000000, 3.000000, 3.000000, 3.000000]"); // Disconnecting processor chain.disconnect(*sig_1, 0, *plus_signal, 0); chain.update(); chain.tick(); CHECK(result == "[2.000000, 2.000000, 2.000000, 2.000000]"); // Removing processor chain.removeProcessor(*plus_signal); chain.update(); chain.tick(); CHECK(result == "[0.000000, 0.000000, 0.000000, 0.000000]"); chain.release(); } SECTION("Chain compile failed - Processor already used") { ; } SECTION("Processor Throw Based on Infos") { Chain chain; std::shared_ptr<Processor> sig_1(new Sig(1.3)); std::shared_ptr<Processor> sig_2(new Sig(2.7)); std::shared_ptr<Processor> plus_scalar(new PlusScalar(1.)); std::shared_ptr<Processor> plus_signal(new PlusSignal()); std::shared_ptr<Processor> copy_throw(new CopyThrow()); chain.addProcessor(sig_1); chain.addProcessor(sig_2); chain.addProcessor(plus_scalar); chain.addProcessor(plus_signal); chain.connect(*sig_1, 0, *plus_scalar, 0); chain.connect(*plus_scalar, 0, *plus_signal, 0); chain.connect(*sig_2, 0, *plus_signal, 1); chain.addProcessor(copy_throw); chain.connect(*plus_signal, 0, *copy_throw, 0); REQUIRE_THROWS_AS(chain.prepare(samplerate, 128ul), Error); chain.release(); } SECTION("Chain tick - WIP") { Chain chain; std::shared_ptr<Processor> sig_1(new Sig(1.)); std::shared_ptr<Processor> plus(new PlusScalar(19.)); std::string result; std::shared_ptr<Processor> print(new Print(result)); chain.addProcessor(sig_1); chain.addProcessor(plus); chain.addProcessor(print); chain.connect(*sig_1, 0, *plus, 0); chain.connect(*plus, 0, *print, 0); REQUIRE_NOTHROW(chain.prepare(samplerate, 4ul)); chain.tick(); chain.tick(); CHECK(result == "[20.000000, 20.000000, 20.000000, 20.000000]"); chain.release(); } SECTION("Chain tick - fanning inlet (inlet add)") { Chain chain; std::shared_ptr<Processor> sig_1(new Sig(1.)); std::shared_ptr<Processor> sig_2(new Sig(2.)); std::shared_ptr<Processor> sig_3(new Sig(3.)); std::string result; std::shared_ptr<Processor> print(new Print(result)); chain.addProcessor(sig_1); chain.addProcessor(sig_2); chain.addProcessor(sig_3); chain.addProcessor(print); chain.connect(*sig_1, 0, *print, 0); chain.connect(*sig_2, 0, *print, 0); chain.connect(*sig_3, 0, *print, 0); REQUIRE_NOTHROW(chain.prepare(samplerate, 4ul)); chain.tick(); CHECK(result == "[6.000000, 6.000000, 6.000000, 6.000000]"); chain.release(); } SECTION("Chain tick - fanning outlet (outlet copy)") { Chain chain; std::shared_ptr<Processor> sig(new Sig(1.111111)); std::string result_1; std::shared_ptr<Processor> print_1(new Print(result_1)); std::string result_2; std::shared_ptr<Processor> print_2(new Print(result_2)); std::string result_3; std::shared_ptr<Processor> print_3(new Print(result_3)); chain.addProcessor(sig); chain.addProcessor(print_1); chain.addProcessor(print_2); chain.addProcessor(print_3); chain.connect(*sig, 0, *print_1, 0); chain.connect(*sig, 0, *print_2, 0); chain.connect(*sig, 0, *print_3, 0); REQUIRE_NOTHROW(chain.prepare(samplerate, 4ul)); chain.tick(); chain.tick(); CHECK(result_1 == "[1.111111, 1.111111, 1.111111, 1.111111]"); CHECK(result_1 == result_2); CHECK(result_1 == result_3); chain.release(); } SECTION("Chain tick - count example") { Chain chain; std::shared_ptr<Processor> count(new Count()); std::string result; std::shared_ptr<Processor> print(new Print(result)); chain.addProcessor(count); chain.addProcessor(print); chain.connect(*count, 0, *print, 0); REQUIRE_NOTHROW(chain.prepare(samplerate, 4ul)); chain.tick(); CHECK(result == "[0.000000, 1.000000, 2.000000, 3.000000]"); chain.tick(); CHECK(result == "[4.000000, 5.000000, 6.000000, 7.000000]"); chain.tick(); CHECK(result == "[8.000000, 9.000000, 10.000000, 11.000000]"); chain.release(); } SECTION("Chain tick - count example 2") { Chain chain; std::shared_ptr<Processor> count(new Count()); std::shared_ptr<Processor> plus(new PlusSignal()); std::string result; std::shared_ptr<Processor> print(new Print(result)); chain.addProcessor(count); chain.addProcessor(plus); chain.addProcessor(print); chain.connect(*count, 0, *plus, 0); chain.connect(*count, 0, *plus, 1); chain.connect(*plus, 0, *print, 0); REQUIRE_NOTHROW(chain.prepare(samplerate, 4ul)); chain.tick(); CHECK(result == "[0.000000, 2.000000, 4.000000, 6.000000]"); chain.tick(); CHECK(result == "[8.000000, 10.000000, 12.000000, 14.000000]"); chain.tick(); CHECK(result == "[16.000000, 18.000000, 20.000000, 22.000000]"); chain.release(); } SECTION("Chain processor without perform") { Chain chain; std::shared_ptr<Processor> sig1(new Sig(1)); std::shared_ptr<Processor> sig2(new Sig(2)); std::shared_ptr<Processor> plus_remove(new PlusScalarRemover()); std::string result; std::shared_ptr<Processor> print(new Print(result)); chain.addProcessor(sig1); chain.addProcessor(sig2); chain.addProcessor(plus_remove); chain.addProcessor(print); chain.connect(*sig2, 0, *plus_remove, 1); chain.connect(*plus_remove, 0, *print, 0); REQUIRE_NOTHROW(chain.prepare(samplerate, 4ul)); chain.tick(); CHECK(result == "[0.000000, 0.000000, 0.000000, 0.000000]"); chain.connect(*sig1, 0, *plus_remove, 0); chain.update(); chain.tick(); CHECK(result == "[3.000000, 3.000000, 3.000000, 3.000000]"); chain.release(); } }
14,801
C++
.cpp
329
33.574468
90
0.588244
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,382
test_KiwiDsp.cpp
Musicoll_Kiwi/Test/Dsp/test_KiwiDsp.cpp
/* ============================================================================== This file is part of the KIWI library. Copyright (c) 2014 Pierre Guillot & Eliott Paris. Permission is granted to use this software under the terms of either: a) the GPL v2 (or any later version) b) the Affero GPL v3 Details of these licenses 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. ------------------------------------------------------------------------------ To release a closed-source product which uses KIWI, contact : [email protected] ============================================================================== */ // Catch main function #define CATCH_CONFIG_RUNNER #include "../catch.hpp" int main( int argc, char* const argv[] ) { // global setup... std::cout << "running Unit-Tests - KiwiDsp ..." << '\n' << '\n'; int result = Catch::Session().run( argc, argv ); // global clean-up... return result; }
1,193
C++
.cpp
26
42.346154
87
0.576211
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,383
test_Buffer.cpp
Musicoll_Kiwi/Test/Dsp/test_Buffer.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 : [email protected] ============================================================================== */ #include "../catch.hpp" #include <KiwiDsp/KiwiDsp_Signal.h> using namespace kiwi; using namespace dsp; // ==================================================================================== // // BUFFER // // ==================================================================================== // TEST_CASE("Dsp - Buffer", "[Dsp, Buffer]") { SECTION("Buffer - aggregation constructor") { Signal::sPtr signal1 = std::make_shared<Signal>(4, 1); Signal::sPtr signal2 = std::make_shared<Signal>(4, 2); std::vector<Signal::sPtr> agg_signals ({signal1, signal2}); Buffer buffer(agg_signals); auto channels = buffer.getNumberOfChannels(); auto vectorsize = buffer.getVectorSize(); REQUIRE(channels == 2); REQUIRE(vectorsize == 4); CHECK(buffer[0][0] == 1); CHECK(buffer[1][1] == 2); signal1->operator[](0) = 5; signal2->operator[](1) = 3; CHECK(buffer[0][0] == 5); CHECK(buffer[1][1] == 3); signal1.reset(); signal2.reset(); CHECK(buffer[0][0] == 5); CHECK(buffer[1][1] == 3); } SECTION("Buffer - filled ctor") { Buffer buffer(2, 128, 1.); auto channels = buffer.getNumberOfChannels(); auto vectorsize = buffer.getVectorSize(); REQUIRE(channels == 2); REQUIRE(vectorsize == 128); for(int i = 0; i < channels; ++i) { for(int j = 0; j < vectorsize; ++j) { CHECK(buffer[i][j] == 1.); } } } SECTION("Buffer - move ctor") { Buffer buffer_1(2, 128, 1.); REQUIRE(buffer_1.getNumberOfChannels() == 2); REQUIRE(buffer_1.getVectorSize() == 128); Buffer buffer_2(std::move(buffer_1)); REQUIRE(buffer_1.empty()); REQUIRE(buffer_1.getNumberOfChannels() == 0); REQUIRE(buffer_1.getVectorSize() == 0); REQUIRE(buffer_2.getNumberOfChannels() == 2); REQUIRE(buffer_2.getVectorSize() == 128); auto channels = buffer_2.getNumberOfChannels(); auto vectorsize = buffer_2.getVectorSize(); for(int i = 0; i < channels; ++i) { for(int j = 0; j < vectorsize; ++j) { CHECK(buffer_2[i][j] == 1.); } } } SECTION("Test") { Buffer buffer(2, 128, 1.); auto channels = buffer.getNumberOfChannels(); auto vectorsize = buffer.getVectorSize(); REQUIRE(channels == 2); REQUIRE(vectorsize == 128); sample_t* left = buffer[0].data(); sample_t* right = buffer[1].data(); while(vectorsize--) { *left++ = 0.5; *right++ = 0.5; } for(int i = 0; i < channels; ++i) { for(int j = 0; j < buffer.getVectorSize(); ++j) { CHECK(buffer[i][j] == 0.5); } } } }
4,121
C++
.cpp
103
30.23301
90
0.493517
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,384
test_PatcherValidator.cpp
Musicoll_Kiwi/Test/Model/test_PatcherValidator.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 : [email protected] ============================================================================== */ #include "../catch.hpp" #include "flip/Document.h" #include "flip/DocumentServer.h" #include "flip/PortDirect.h" #include "flip/CarrierDirect.h" #include <KiwiTool/KiwiTool_Atom.h> #include <KiwiModel/KiwiModel_DataModel.h> #include <KiwiModel/KiwiModel_PatcherUser.h> #include <KiwiModel/KiwiModel_PatcherValidator.h> #include <KiwiModel/KiwiModel_Factory.h> using namespace kiwi; // ==================================================================================== // // VALIDATOR // // ==================================================================================== // TEST_CASE("Model Validator", "[Validator]") { SECTION("Concurrent object deletion and link creation (deletion first)") { model::PatcherValidator validator; flip::DocumentServer server (model::DataModel::use(), validator, 123456789ULL); server.root<model::Patcher>().addObject(model::Factory::create(tool::AtomHelper::parse("+"))); server.root<model::Patcher>().addObject(model::Factory::create(tool::AtomHelper::parse("+"))); server.commit(); // Connect client 1 flip::PortDirect port_01; server.port_factory_add (port_01); flip::Document document_01 (model::DataModel::use(), validator, 11, 23, 24); flip::CarrierDirect carrier_01 (document_01, port_01); document_01.pull(); // Connect client 2 flip::PortDirect port_02; server.port_factory_add (port_02); flip::Document document_02 (model::DataModel::use(), validator, 12, 23, 24); flip::CarrierDirect carrier_02 (document_02, port_02); document_02.pull(); // client 1 delete objects model::Patcher& patcher_01 = document_01.root<model::Patcher>(); patcher_01.removeObject(*patcher_01.getObjects().begin()); patcher_01.removeObject(*(++patcher_01.getObjects().begin())); // client 2 create link model::Patcher& patcher_02 = document_02.root<model::Patcher>(); patcher_02.addLink(*patcher_02.getObjects().begin(), 0, *(++patcher_02.getObjects().begin()), 0); // client 1 commit and push document_01.commit(); document_01.push(); CHECK(server.root<model::Patcher>().getObjects().count_if([](model::Object &){return true;}) == 0); // client 2 commit and push (server reject link creation) document_02.commit(); document_02.push(); CHECK(server.root<model::Patcher>().getLinks().count_if([](model::Link &){return true;}) == 0); // client 1 pull document_01.pull(); CHECK(patcher_01.getObjects().count_if([](model::Object &){return true;}) == 0); CHECK(patcher_01.getLinks().count_if([](model::Link &){return true;}) == 0); // client 2 pull (stack unwind plus link creation rejected) document_02.pull(); CHECK(patcher_02.getObjects().count_if([](model::Object &){return true;}) == 0); CHECK(patcher_02.getLinks().count_if([](model::Link &){return true;}) == 0); server.port_factory_remove (port_01); server.port_factory_remove (port_02); } SECTION("Concurrent object deletion and link creation (creation first)") { model::PatcherValidator validator; flip::DocumentServer server (model::DataModel::use(), validator, 123456789ULL); server.root<model::Patcher>().addObject(model::Factory::create(tool::AtomHelper::parse("+"))); server.root<model::Patcher>().addObject(model::Factory::create(tool::AtomHelper::parse("+"))); server.commit(); // Connect client 1 flip::PortDirect port_01; server.port_factory_add (port_01); flip::Document document_01 (model::DataModel::use(), validator, 11, 23, 24); flip::CarrierDirect carrier_01 (document_01, port_01); document_01.pull(); // Connect client 2 flip::PortDirect port_02; server.port_factory_add (port_02); flip::Document document_02 (model::DataModel::use(), validator, 12, 23, 24); flip::CarrierDirect carrier_02 (document_02, port_02); document_02.pull(); // client 1 delete objects model::Patcher& patcher_01 = document_01.root<model::Patcher>(); patcher_01.removeObject(*patcher_01.getObjects().begin()); patcher_01.removeObject(*(++patcher_01.getObjects().begin())); // client 2 create link model::Patcher& patcher_02 = document_02.root<model::Patcher>(); patcher_02.addLink(*patcher_02.getObjects().begin(), 0, *(++patcher_02.getObjects().begin()), 0); // client 2 commit and push document_02.commit(); document_02.push(); CHECK(server.root<model::Patcher>().getLinks().count_if([](model::Link &){return true;}) == 1); // client 1 commit and push (transaction rejected) document_01.commit(); document_01.push(); CHECK(server.root<model::Patcher>().getObjects().count_if([](model::Object &){return true;}) == 2); // client 1 pull (stack unwind plus deletion rejected) document_01.pull(); CHECK(patcher_01.getObjects().count_if([](model::Object &){return true;}) == 2); CHECK(patcher_01.getLinks().count_if([](model::Link &){return true;}) == 1); // client 2 pull document_02.pull(); CHECK(patcher_02.getObjects().count_if([](model::Object &){return true;}) == 2); CHECK(patcher_02.getLinks().count_if([](model::Link &){return true;}) == 1); server.port_factory_remove (port_01); server.port_factory_remove (port_02); } }
6,848
C++
.cpp
121
47.008264
107
0.601532
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,385
test_Factory.cpp
Musicoll_Kiwi/Test/Model/test_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 : [email protected] ============================================================================== */ #include "../catch.hpp" #include <KiwiModel/KiwiModel_Factory.h> using namespace kiwi; // ==================================================================================== // // FACTORY // // ==================================================================================== // TEST_CASE("Model Factory", "[Names]") { SECTION("One special character") { std::string kiwi_name = "¨"; std::string model_name = model::Factory::toModelName(kiwi_name); CHECK(kiwi_name == model::Factory::toKiwiName(model_name)); } SECTION("More complex character chain") { std::string kiwi_name = "¨ç*$$sd$sdf$@#2342ééé"; std::cout << kiwi_name.size() << std::endl; std::string model_name = model::Factory::toModelName(kiwi_name); CHECK(kiwi_name == model::Factory::toKiwiName(model_name)); } }
1,859
C++
.cpp
36
46.027778
90
0.503429
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,386
test_KiwiModel.cpp
Musicoll_Kiwi/Test/Model/test_KiwiModel.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 : [email protected] ============================================================================== */ #define CATCH_CONFIG_RUNNER #include "../catch.hpp" #include <KiwiModel/KiwiModel_DataModel.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Plus.h> using namespace kiwi; int main( int argc, char* const argv[] ) { std::cout << "running Unit-Tests - KiwiModel ..." << '\n' << '\n'; model::DataModel::init(); int result = Catch::Session().run( argc, argv ); return result; }
1,273
C++
.cpp
26
45.576923
90
0.598023
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,387
test_KiwiServer.cpp
Musicoll_Kiwi/Test/Server/test_KiwiServer.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v2 (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 : [email protected] ============================================================================== */ #define CATCH_CONFIG_RUNNER #include "../catch.hpp" #include <KiwiModel/KiwiModel_DataModel.h> int main( int argc, char* const argv[] ) { std::cout << "running Unit-Tests - KiwiServer ..." << '\n' << '\n'; kiwi::model::DataModel::init(); int result = Catch::Session().run( argc, argv ); return result; }
1,195
C++
.cpp
24
46.291667
85
0.581579
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,388
test_Server.cpp
Musicoll_Kiwi/Test/Server/test_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 : [email protected] ============================================================================== */ #include "../catch.hpp" #include <thread> #include <json.hpp> #include <KiwiServer/KiwiServer_Server.h> #include <KiwiModel/KiwiModel_DataModel.h> #include <KiwiModel/KiwiModel_Def.h> #include <flip/Document.h> #include <flip/contrib/transport_tcp/CarrierTransportSocketTcp.h> using namespace kiwi; // ==================================================================================== // // SERVER // // ==================================================================================== // std::string token = "token"; std::string kiwi_version = "v0.1.0"; std::string getMetaData() { nlohmann::json j; j["model_version"] = KIWI_MODEL_VERSION_STRING; j["open_token"] = token; j["kiwi_version"] = kiwi_version; return j.dump(); } TEST_CASE("Server - Server", "[Server, Server]") { const auto app_file = juce::File::SpecialLocationType::currentExecutableFile; const auto backend_dir = (juce::File::getSpecialLocation(app_file) .getParentDirectory() .getChildFile("./server_backend_test")); SECTION("Simple Connection - Deconnection") { kiwi::server::Server server(9191, backend_dir, token, kiwi_version); // Initializing document flip::Document document (kiwi::model::DataModel::use (), 123456789, 'appl', 'gui '); flip::CarrierTransportSocketTcp carrier (document, 987654, getMetaData(), "localhost", 9191); // Client/Document connecting to server. while(!carrier.is_connected() || server.getSessions().empty()) { carrier.process(); server.process(); } CHECK(carrier.is_connected()); CHECK(server.getSessions().count(987654)); CHECK(server.getConnectedUsers(987654).count(123456789)); // Client/Document disconnects from server. carrier.rebind("", 0); // Client/Document connecting to server. while(carrier.is_connected() || !server.getSessions().empty()) { carrier.process(); server.process(); } CHECK(!carrier.is_connected()); CHECK(server.getSessions().empty()); if (backend_dir.exists()) { backend_dir.deleteRecursively(); } } SECTION("Simple Connection - Server Killed") { auto server = std::make_unique<kiwi::server::Server>(9191, backend_dir, token, kiwi_version); // Initializing document. flip::Document document (kiwi::model::DataModel::use (), 123456789, 'appl', 'gui '); flip::CarrierTransportSocketTcp carrier (document, 987654, getMetaData(), "localhost", 9191); // Client/Document connecting to server. while(!carrier.is_connected() || server->getSessions().empty()) { carrier.process(); server->process(); } CHECK(carrier.is_connected()); CHECK(server->getSessions().count(987654)); // Killing server before client is disconnected. server.reset(nullptr); // Client automatically disconnected from server. while(carrier.is_connected()) { carrier.process(); } CHECK(!carrier.is_connected()); if (backend_dir.exists()) { backend_dir.deleteRecursively(); } } SECTION("One user connecting to multiple document") { kiwi::server::Server server(9191, backend_dir, token, kiwi_version); // Initializing documents. flip::Document document_1 (kiwi::model::DataModel::use (), 123456789, 'appl', 'gui '); flip::CarrierTransportSocketTcp carrier_1 (document_1, 987654, getMetaData(), "localhost", 9191); flip::Document document_2 (kiwi::model::DataModel::use (), 123456789, 'appl', 'gui '); flip::CarrierTransportSocketTcp carrier_2 (document_2, 987655, getMetaData(), "localhost", 9191); // Client/Document connecting to server. while(!carrier_1.is_connected() || !carrier_2.is_connected() || server.getSessions().size() != 2) { carrier_1.process(); carrier_2.process(); server.process(); } CHECK(carrier_1.is_connected()); CHECK(carrier_2.is_connected()); CHECK(server.getSessions().count(987654)); CHECK(server.getSessions().count(987655)); carrier_1.rebind("", 0); carrier_2.rebind("", 0); while(carrier_1.is_connected() || carrier_2.is_connected() || !server.getSessions().empty()) { carrier_1.process(); carrier_2.process(); server.process(); } CHECK(!carrier_1.is_connected()); CHECK(!carrier_2.is_connected()); if (backend_dir.exists()) { backend_dir.deleteRecursively(); } } SECTION("Multiple connections") { kiwi::server::Server server(9191, backend_dir, token, kiwi_version); // Initializing client 1 flip::Document document_1 (kiwi::model::DataModel::use (), 1, 'appl', 'gui '); flip::CarrierTransportSocketTcp carrier_1 (document_1, 1234, getMetaData(), "localhost", 9191); kiwi::model::Patcher& patcher_1 = document_1.root<kiwi::model::Patcher>(); uint64_t other_connect_1 = 0; auto m_cnx_connect_1 = patcher_1.signal_user_connect.connect([&other_connect_1](uint64_t user_id) { other_connect_1 = user_id; }); uint64_t other_disonnect_1 = 0; auto m_cnx_disconnect_1 = patcher_1.signal_user_disconnect.connect([&other_disonnect_1](uint64_t user_id) { other_disonnect_1 = user_id; }); // Initializing client 2 flip::Document document_2 (kiwi::model::DataModel::use (), 2, 'appl', 'gui '); flip::CarrierTransportSocketTcp carrier_2 (document_2, 1234, getMetaData(), "localhost", 9191); kiwi::model::Patcher& patcher_2 = document_2.root<kiwi::model::Patcher>(); std::vector<uint64_t> connected_users_2; auto m_cnx_2 = patcher_2.signal_receive_connected_users.connect([&connected_users_2](std::vector<uint64_t> users) { connected_users_2 = users; }); // Client 1 connects to server. while(!carrier_1.is_connected() || server.getSessions().empty()){carrier_1.process(); server.process();} CHECK(carrier_1.is_connected()); CHECK(server.getConnectedUsers(1234).count(1)); // Client 2 connects to server. Client 2 receives all connected users, client 1 is notified. while(connected_users_2.empty() || !server.getConnectedUsers(1234).count(2)) { carrier_2.process(); document_2.pull(); server.process(); } auto it = std::find_if(connected_users_2.begin(), connected_users_2.end(), [](uint64_t id){return id == 1;}); CHECK(it != connected_users_2.end()); while(other_connect_1 == 0) { carrier_1.process(); document_1.pull(); server.process(); } CHECK(other_connect_1 == 2); // Client 2 disconnects from server. Client 1 is notified. carrier_2.rebind("", 0); while(carrier_2.is_connected() || server.getConnectedUsers(1234).count(2)){carrier_2.process(); server.process();} while(other_disonnect_1 == 0){carrier_1.process(); document_1.pull(); server.process();} CHECK(other_disonnect_1 == 2); // Client 1 disconnects from server. Client 1 is notified. carrier_1.rebind("", 0); while(carrier_1.is_connected() || !server.getSessions().empty()){carrier_1.process(); server.process();} if (backend_dir.exists()) { backend_dir.deleteRecursively(); } SECTION("Hexadecimal convert") { std::string hex = server::hexadecimal_convert(139928974906665000); CHECK(hex == "01f120a94b18a828"); } } }
9,379
C++
.cpp
198
36.90404
122
0.585859
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,389
test_KiwiNetwork.cpp
Musicoll_Kiwi/Test/Network/test_KiwiNetwork.cpp
/* ============================================================================== This file is part of the KIWI library. - Copyright (c) 2014-2016, Pierre Guillot & Eliott Paris. - Copyright (c) 2016, CICM, ANR MUSICOLL, Eliott Paris, Pierre Guillot, Jean Millot. Permission is granted to use this software under the terms of the GPL v2 (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 : [email protected] ============================================================================== */ #define CATCH_CONFIG_RUNNER #include "../catch.hpp" int main( int argc, char* const argv[] ) { std::cout << "running Unit-Tests - KiwiNetwork ..." << '\n' << '\n'; int result = Catch::Session().run( argc, argv ); return result; }
1,111
C++
.cpp
22
47.227273
85
0.570489
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,390
test_Http.cpp
Musicoll_Kiwi/Test/Network/test_Http.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 : [email protected] ============================================================================== */ // ==================================================================================== // // NETWORK // // ==================================================================================== // #include <iostream> #include "../catch.hpp" #include <boost/beast/http.hpp> namespace beast = boost::beast; #include <KiwiNetwork/KiwiNetwork_Http.h> TEST_CASE("Network - Http Query", "[Network, Http]") { using namespace kiwi::network; SECTION("Query - Client get request to echo server") { auto request = std::make_unique<beast::http::request<beast::http::string_body>>(); request->method(beast::http::verb::get); request->target("/get"); request->version(11); request->set(beast::http::field::host, "httpbin.org"); request->set(beast::http::field::user_agent, "test"); http::Query<beast::http::string_body, beast::http::string_body> query(std::move(request), "80"); http::Response<beast::http::string_body> response = query.writeQuery(); REQUIRE(!response.error); CHECK(response.result() == beast::http::status::ok); CHECK(query.executed()); } SECTION("Query - Client asynchronous get request to echo server") { auto request = std::make_unique<http::Request<beast::http::string_body>>(); request->method(beast::http::verb::get); request->target("/get"); request->version(11); request->set(beast::http::field::host, "httpbin.org"); request->set(beast::http::field::user_agent, "test"); http::Query<beast::http::string_body, beast::http::string_body> query(std::move(request), "80"); int callback_called = 0; std::function<void(http::Response<beast::http::string_body> const&)> callback_1 = [&query, &callback_called](http::Response<beast::http::string_body> const & response) { CHECK(!query.executed()); REQUIRE(!response.error); CHECK(response.result() == beast::http::status::ok); callback_called = 1; }; std::function<void(http::Response<beast::http::string_body> const&)> callback_2 = [&callback_called](http::Response<beast::http::string_body> const & response) { callback_called = 2; }; query.writeQueryAsync(std::move(callback_1)); query.writeQueryAsync(std::move(callback_2)); while(!query.executed()){}; CHECK(callback_called == 1); } SECTION("Query - Reaching timeout sync query") { auto request = std::make_unique<http::Request<beast::http::string_body>>(); request->method(beast::http::verb::get);; request->version(11); request->set(beast::http::field::host, "example.com"); http::Query<beast::http::string_body, beast::http::string_body> query(std::move(request), "81"); http::Response<beast::http::string_body> response = query.writeQuery(http::Timeout(100)); CHECK(response.error); CHECK(response.error == boost::asio::error::basic_errors::timed_out); } SECTION("Query - Reaching timeout async query") { auto request = std::make_unique<http::Request<beast::http::string_body>>(); request->method(beast::http::verb::get); request->version(11); request->set(beast::http::field::host, "example.com"); std::function<void(http::Response<beast::http::string_body> const&)> callback = [](http::Response<beast::http::string_body> const & response) { CHECK(response.error); CHECK(response.error == boost::asio::error::basic_errors::timed_out); }; http::Query<beast::http::string_body, beast::http::string_body> query(std::move(request), "81"); query.writeQueryAsync(std::move(callback), http::Timeout(100)); } SECTION("Query - Cancelling query sync request") { auto request = std::make_unique<beast::http::request<beast::http::string_body>>(); request->method(beast::http::verb::get); request->target("/get"); request->version(11); request->set(beast::http::field::host, "httpbin.org"); request->set(beast::http::field::user_agent, "test"); http::Query<beast::http::string_body, beast::http::string_body> query(std::move(request), "80"); query.cancel(); CHECK(query.executed()); http::Response<beast::http::string_body> response = query.writeQuery(); CHECK(response.error == boost::asio::error::basic_errors::timed_out); } SECTION("Query - Cancelling query async request") { auto request = std::make_unique<http::Request<beast::http::string_body>>(); request->method(beast::http::verb::get); request->version(11); request->set(beast::http::field::host, "example.com"); std::function<void(http::Response<beast::http::string_body> const&)> callback = [](http::Response<beast::http::string_body> const & response) { CHECK(response.error); CHECK(response.error == boost::asio::error::basic_errors::timed_out); }; http::Query<beast::http::string_body, beast::http::string_body> query(std::move(request), "81"); query.writeQueryAsync(std::move(callback)); query.cancel(); CHECK(query.executed()); } } TEST_CASE("Network - Http Session", "[Network, Http]") { using namespace kiwi::network; SECTION("Session GetAsync") { http::Session session; session.setHost("httpbin.org"); session.setTarget("/get"); session.GetAsync([](http::Session::Response response) { REQUIRE(!response.error); CHECK(response.result() == beast::http::status::ok); }); } SECTION("Session GetAsync with Parameters") { http::Session session; session.setHost("httpbin.org"); session.setTarget("/get"); session.setParameters({ {"foo", "bar bar"}, {"value", "42"} }); session.GetAsync([](http::Session::Response response) { REQUIRE(!response.error); CHECK(response.result() == beast::http::status::ok); }); } SECTION("Session Get request with timeout") { http::Session session; session.setHost("example.com"); session.setTarget("/get"); session.setPort("81"); session.setTimeout(http::Timeout(100)); http::Session::Response response = session.Get(); CHECK(response.error); CHECK(response.error == boost::asio::error::basic_errors::timed_out); } SECTION("Session GetAsync with timeout") { http::Session session; session.setHost("example.com"); session.setTarget("/get"); session.setPort("81"); session.setTimeout(http::Timeout(100)); session.GetAsync([](http::Session::Response response) { CHECK(response.error); CHECK(response.error == boost::asio::error::basic_errors::timed_out); }); } }
8,353
C++
.cpp
176
38.017045
106
0.586357
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,391
test_Atom.cpp
Musicoll_Kiwi/Test/Tool/test_Atom.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 : [email protected] ============================================================================== */ #include <vector> #include "../catch.hpp" #include <KiwiTool/KiwiTool_Atom.h> using namespace kiwi::tool; // ================================================================================ // // ATOM CONSTRUCTORS // // ================================================================================ // TEST_CASE("Atom Constructors", "[Atom]") { SECTION("Default (Atom::Type::Null)") { Atom atom; CHECK(atom.getType() == Atom::Type::Null); CHECK(atom.isNull()); CHECK(Atom().getType() == Atom::Type::Null); } SECTION("bool (Atom::Type::Int)") { Atom atom_true(true); REQUIRE(atom_true.isInt()); CHECK(atom_true.getInt() == 1); Atom atom_false(false); REQUIRE(atom_false.isInt()); CHECK(atom_false.getInt() == 0); } SECTION("Signed Integral types") { CHECK(Atom('c').isInt()); // char CHECK(Atom(true).isInt()); // bool CHECK(Atom(false).isInt()); // bool CHECK(Atom(short(1)).isInt()); // short CHECK(Atom(1).isInt()); // int CHECK(Atom(1l).isInt()); // long CHECK(Atom(1ll).isInt()); // long long CHECK(Atom(0xFFFFFF).isInt()); // hexadecimal CHECK(Atom(0113).isInt()); // octal } SECTION("int (Atom::Type::Int)") { Atom atom_1(440); REQUIRE(atom_1.isInt()); CHECK(atom_1.getInt() == 440); Atom atom_2(-440); REQUIRE(atom_2.isInt()); CHECK(atom_2.getInt() == -440); Atom atom_3(std::numeric_limits<int>::max()); REQUIRE(atom_3.isInt()); CHECK(atom_3.getInt() == std::numeric_limits<int>::max()); Atom atom_4(std::numeric_limits<int>::lowest()); REQUIRE(atom_4.isInt()); CHECK(atom_4.getInt() == std::numeric_limits<int>::lowest()); } SECTION("long (Atom::Type::Int)") { Atom atom_1(440l); REQUIRE(atom_1.isInt()); CHECK(atom_1.getInt() == 440l); Atom atom_2(-440l); REQUIRE(atom_2.isInt()); CHECK(atom_2.getInt() == -440l); Atom atom_3(std::numeric_limits<long>::max()); REQUIRE(atom_3.isInt()); CHECK(atom_3.getInt() == std::numeric_limits<long>::max()); Atom atom_4(std::numeric_limits<long>::lowest()); REQUIRE(atom_4.isInt()); CHECK(atom_4.getInt() == std::numeric_limits<long>::lowest()); } SECTION("long long (Atom::Type::Int)") { Atom atom_1(440ll); REQUIRE(atom_1.isInt()); CHECK(atom_1.getInt() == 440ll); Atom atom_2(-440ll); REQUIRE(atom_2.isInt()); CHECK(atom_2.getInt() == -440ll); Atom atom_3(std::numeric_limits<long long>::max()); REQUIRE(atom_3.isInt()); CHECK(atom_3.getInt() == std::numeric_limits<long long>::max()); Atom atom_4(std::numeric_limits<long long>::lowest()); REQUIRE(atom_4.isInt()); CHECK(atom_4.getInt() == std::numeric_limits<long long>::lowest()); } /* SECTION("Unsigned Integral types are unsupported") { CHECK(Atom(1u).getType() == Atom::Type::Int); // unsigned (int) CHECK(Atom(1ul).getType() == Atom::Type::Int); // unsigned long CHECK(Atom(1lu).getType() == Atom::Type::Int); // unsigned long CHECK(Atom(1ull).getType() == Atom::Type::Int); // unsigned long long CHECK(Atom(1llu).getType() == Atom::Type::Int); // unsigned long long } */ SECTION("Floating-Point types") { CHECK(Atom(3.14f).getType() == Atom::Type::Float); // float CHECK(Atom(3.14).getType() == Atom::Type::Float); // double //CHECK(Atom(3.14l).getType() == Atom::Type::Float); // long double are not supported CHECK(Atom(6.02e23).getType() == Atom::Type::Float); // 6.02 x 10^23 (Avogadro constant) CHECK(Atom(1.6e-19).getType() == Atom::Type::Float); // 1.6 x 10^-19 (electric charge of an electron) } SECTION("float (Atom::Type::Float)") { Atom atom_1(3.14f); REQUIRE(atom_1.isFloat()); CHECK(atom_1.getFloat() == 3.14f); Atom atom_2(-3.14f); REQUIRE(atom_2.isFloat()); CHECK(atom_2.getFloat() == -3.14f); Atom atom_3(std::numeric_limits<float>::max()); REQUIRE(atom_3.isFloat()); CHECK(atom_3.getFloat() == std::numeric_limits<float>::max()); Atom atom_4(std::numeric_limits<float>::lowest()); REQUIRE(atom_4.isFloat()); CHECK(atom_4.getFloat() == std::numeric_limits<float>::lowest()); } SECTION("double (Atom::Type::Float)") { Atom atom_1(3.14); REQUIRE(atom_1.isFloat()); CHECK(atom_1.getFloat() == 3.14); Atom atom_2(-3.14); REQUIRE(atom_2.isFloat()); CHECK(atom_2.getFloat() == -3.14); Atom atom_3(std::numeric_limits<double>::max()); REQUIRE(atom_3.isFloat()); CHECK(atom_3.getFloat() == std::numeric_limits<double>::max()); Atom atom_4(std::numeric_limits<double>::lowest()); REQUIRE(atom_4.isFloat()); CHECK(atom_4.getFloat() == std::numeric_limits<double>::lowest()); } SECTION("char const* (Atom::Type::String)") { const std::string str("string"); Atom a_sym("string"); CHECK(a_sym.getType() == Atom::Type::String); CHECK(a_sym.isString()); CHECK(a_sym.getString() == str); } SECTION("std::string const& (Atom::Type::String)") { const std::string str("string"); Atom a_sym(str); CHECK(a_sym.getType() == Atom::Type::String); CHECK(a_sym.isString()); CHECK(a_sym.getString() == str); } SECTION("Copy constructor") { Atom a_null; Atom a_null_copy = a_null; CHECK(a_null_copy.isNull()); Atom a_int(42); Atom a_int_copy = a_int; CHECK(a_int_copy.isInt()); CHECK(a_int_copy.getInt() == a_int.getInt()); Atom a_float(3.14); Atom a_float_copy = a_float; CHECK(a_float_copy.isFloat()); CHECK(a_float_copy.getFloat() == a_float.getFloat()); Atom a_string("string"); Atom a_string_copy = a_string; CHECK(a_string_copy.isString()); CHECK(a_string_copy.getString() == a_string.getString()); Atom a_comma = Atom::Comma(); Atom a_comma_copy = a_comma; CHECK(a_comma_copy.getType()== Atom::Type::Comma); Atom a_dollar = Atom::Dollar(1); Atom a_dollar_copy = a_dollar; CHECK(a_dollar_copy.isDollar()); CHECK(a_dollar_copy.getDollarIndex() == a_dollar.getDollarIndex()); } SECTION("Copy assigment operator") { Atom a_null; Atom a_int(42); Atom a_float(3.14); Atom a_string("string"); Atom a_string_2("string_2"); Atom a_temp; CHECK(a_temp.getType() == Atom::Type::Null); a_temp = a_int; CHECK(a_temp.getType() == Atom::Type::Int); a_temp = a_float; CHECK(a_temp.getType() == Atom::Type::Float); a_temp = a_string; CHECK(a_temp.getType() == Atom::Type::String); a_temp = a_string_2; CHECK(a_temp.getType() == Atom::Type::String); a_temp = a_null; CHECK(a_temp.getType() == Atom::Type::Null); } SECTION("Move constructor") { SECTION("Null") { Atom to_move; Atom moved(std::move(to_move)); CHECK(to_move.isNull() == true); CHECK(moved.isNull() == true); } SECTION("Int") { Atom to_move(42); Atom moved(std::move(to_move)); CHECK(to_move.isNull() == true); CHECK(moved.isNumber() == true); CHECK(moved.isInt() == true); CHECK(moved.getInt() == 42); } SECTION("Float") { Atom to_move(3.14); Atom moved(std::move(to_move)); CHECK(to_move.isNull() == true); CHECK(moved.isNumber() == true); CHECK(moved.isFloat() == true); CHECK(moved.getFloat() == 3.14); } SECTION("String") { Atom to_move("string"); Atom moved(std::move(to_move)); CHECK(to_move.isNull() == true); CHECK(moved.isString() == true); CHECK(moved.getString() == "string"); } SECTION("std::string move ctor") { std::string str_to_move("string"); Atom moved(std::move(str_to_move)); CHECK(moved.isString() == true); CHECK(moved.getString() == "string"); } } } TEST_CASE("Atom Copy assignment", "[Atom]") { Atom a_temp; CHECK(a_temp.getType() == Atom::Type::Null); a_temp = 123456789; CHECK(a_temp.getType() == Atom::Type::Int); CHECK(a_temp.getInt() == 123456789); a_temp = 123456789l; CHECK(a_temp.getType() == Atom::Type::Int); CHECK(a_temp.getInt() == 123456789l); a_temp = 123456789ll; CHECK(a_temp.getType() == Atom::Type::Int); CHECK(a_temp.getInt() == 123456789ll); a_temp = 1.23456789f; CHECK(a_temp.getType() == Atom::Type::Float); CHECK(a_temp.getFloat() == 1.23456789f); a_temp = 1.23456789; CHECK(a_temp.getType() == Atom::Type::Float); CHECK(a_temp.getFloat() == 1.23456789); std::string str("jujube"); a_temp = str; CHECK(a_temp.getType() == Atom::Type::String); CHECK(a_temp.getString() == str); a_temp = "kiwi"; CHECK(a_temp.getType() == Atom::Type::String); CHECK(a_temp.getString() == "kiwi"); a_temp = {}; CHECK(a_temp.getType() == Atom::Type::Null); } TEST_CASE("Check Types", "[Atom]") { SECTION("Check Types (Null)") { Atom atom; CHECK(atom.getType() == Atom::Type::Null); CHECK(atom.isNull() == true); CHECK(atom.isNumber() == false); CHECK(atom.isInt() == false); CHECK(atom.isFloat() == false); CHECK(atom.isString() == false); CHECK(atom.isBang() == false); CHECK(atom.isComma() == false); CHECK(atom.isDollar() == false); } SECTION("Check Types (Int)") { Atom atom(42); CHECK(atom.getType() == Atom::Type::Int); CHECK(atom.isNull() == false); CHECK(atom.isNumber() == true); CHECK(atom.isInt() == true); CHECK(atom.isFloat() == false); CHECK(atom.isString() == false); CHECK(atom.isBang() == false); CHECK(atom.isComma() == false); CHECK(atom.isDollar() == false); } SECTION("Check Types (Float)") { Atom atom(3.14); CHECK(atom.getType() == Atom::Type::Float); CHECK(atom.isNull() == false); CHECK(atom.isNumber() == true); CHECK(atom.isInt() == false); CHECK(atom.isFloat() == true); CHECK(atom.isString() == false); CHECK(atom.isBang() == false); CHECK(atom.isComma() == false); CHECK(atom.isDollar() == false); } SECTION("Check Types (String)") { Atom atom("foo"); CHECK(atom.getType() == Atom::Type::String); CHECK(atom.isNull() == false); CHECK(atom.isNumber() == false); CHECK(atom.isInt() == false); CHECK(atom.isFloat() == false); CHECK(atom.isString() == true); CHECK(atom.isBang() == false); CHECK(atom.isComma() == false); CHECK(atom.isDollar() == false); } SECTION("Check Types (String) - bang") { Atom atom("bang"); CHECK(atom.getType() == Atom::Type::String); CHECK(atom.isNull() == false); CHECK(atom.isNumber() == false); CHECK(atom.isInt() == false); CHECK(atom.isFloat() == false); CHECK(atom.isString() == true); CHECK(atom.isBang() == true); CHECK(atom.isComma() == false); CHECK(atom.isDollar() == false); } SECTION("Check Types (Comma)") { Atom atom = Atom::Comma(); CHECK(atom.getType() == Atom::Type::Comma); CHECK(atom.isNull() == false); CHECK(atom.isNumber() == false); CHECK(atom.isInt() == false); CHECK(atom.isFloat() == false); CHECK(atom.isString() == false); CHECK(atom.isBang() == false); CHECK(atom.isComma() == true); CHECK(atom.isDollar() == false); } SECTION("Check Types (Dollar)") { Atom atom = Atom::Dollar(1); CHECK(atom.getType() == Atom::Type::Dollar); CHECK(atom.isNull() == false); CHECK(atom.isNumber() == false); CHECK(atom.isInt() == false); CHECK(atom.isFloat() == false); CHECK(atom.isString() == false); CHECK(atom.isBang() == false); CHECK(atom.isComma() == false); CHECK(atom.isDollar() == true); } } TEST_CASE("Value getters", "[Atom]") { SECTION("When Atom is of Type::Null") { Atom a_null; CHECK(a_null.getInt() == 0); CHECK(a_null.getFloat() == 0.0); CHECK(a_null.getString() == ""); } SECTION("When Atom is of Type::Int") { Atom a_int(42); CHECK(a_int.getInt() == 42); CHECK(a_int.getFloat() == 42.); CHECK(a_int.getString() == ""); } SECTION("When Atom is of Type::Float") { Atom a_float(3.14f); CHECK(a_float.getInt() == 3); CHECK(a_float.getFloat() == 3.14f); CHECK(a_float.getString() == ""); Atom a_double(3.99); CHECK(a_double.getInt() == 3); CHECK(a_double.getFloat() == 3.99); CHECK(a_double.getString() == ""); } SECTION("When Atom is of Type::String") { Atom a_sym("foo"); CHECK(a_sym.getInt() == 0); CHECK(a_sym.getFloat() == 0.0); CHECK(a_sym.getString() == "foo"); } } // ------- // Parser // ------- TEST_CASE("Atom Parse", "[Atom]") { SECTION("basic atom parsing") { const auto atoms = AtomHelper::parse("foo \"bar 42\" 1 -2 3.14 -3.14"); REQUIRE(atoms.size() == 6); CHECK(atoms[0].getString() == "foo"); CHECK(atoms[1].getString() == "bar 42"); CHECK((atoms[2].isInt() && atoms[3].isInt())); CHECK(atoms[4].isFloat()); CHECK(atoms[4].getFloat() == 3.14); CHECK(atoms[5].isFloat()); CHECK(atoms[5].getFloat() == -3.14); } SECTION("parse integer beginning with multiple zeros") { const auto atoms = AtomHelper::parse("000101"); REQUIRE(atoms.size() == 1); CHECK(atoms[0].isInt()); CHECK(atoms[0].getInt() == 101); } SECTION("parse float beginning with multiple zeros") { const auto atoms = AtomHelper::parse("000.101"); REQUIRE(atoms.size() == 1); CHECK(atoms[0].isFloat()); CHECK(atoms[0].getFloat() == 0.101); } SECTION("simple dot is a string") { const auto atoms = AtomHelper::parse("."); REQUIRE(atoms.size() == 1); CHECK(atoms[0].isString()); } SECTION("dot following by digits is a Float") { const auto atoms = AtomHelper::parse(".001"); REQUIRE(atoms.size() == 1); CHECK(atoms[0].isFloat()); } SECTION("float values are trimmed") { const auto atoms = AtomHelper::parse(".001000"); REQUIRE(atoms.size() == 1); CHECK(atoms[0].isFloat()); CHECK(AtomHelper::toString(atoms[0]) == "0.001"); } SECTION("negative sign following by a dot and digits is a Float") { const auto atoms = AtomHelper::parse("-.001"); REQUIRE(atoms.size() == 1); CHECK(atoms[0].isFloat()); CHECK(atoms[0].getFloat() == -.001); } SECTION("exponent is a Float") { const auto atoms = AtomHelper::parse("6.02e23"); REQUIRE(atoms.size() == 1); CHECK(atoms[0].isFloat()); CHECK(atoms[0].getFloat() == 6.02e23); } SECTION("digits with more than one dot is a String") { const auto atoms = AtomHelper::parse("0.001."); REQUIRE(atoms.size() == 1); CHECK(atoms[0].isString()); } SECTION("skip whitespaces") { const auto atoms = AtomHelper::parse(" toto 44"); CHECK(atoms.size() == 2); CHECK(atoms[0].isString()); CHECK(atoms[0].getString() == "toto"); CHECK(atoms[1].isInt()); CHECK(atoms[1].getInt() == 44); } SECTION("skip special whitespace characters") { const auto text = "\f\n\r\t\v \f \n \r \t \v "; const auto atoms = AtomHelper::parse(text); REQUIRE(atoms.size() == 0); } SECTION("preserve special whitespace characters in double-quoted text sequence") { const auto text = "\"\f\n\r\t\v \f \n \r \t \v \""; const auto atoms = AtomHelper::parse(text); REQUIRE(atoms.size() == 1); CHECK(atoms[0].isString()); CHECK(AtomHelper::toString(atoms) == text); CHECK(AtomHelper::toString(atoms[0]) == text); CHECK(atoms[0].getString() == "\f\n\r\t\v \f \n \r \t \v "); } SECTION("strip slashes") { const auto text = R"(\0\a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q\r\s\t\u\v\w\x\y\z)"; const auto text_result = "0abcdefghijklmnopqrstuvwxyz"; const auto atoms = AtomHelper::parse(text); REQUIRE(atoms.size() == 1); CHECK(atoms[0].isString()); CHECK(AtomHelper::toString(atoms) == text_result); CHECK(AtomHelper::toString(atoms[0]) == text_result); CHECK(atoms[0].getString() == text_result); } SECTION("strip slashes double slash") { const auto text = R"(\\a\\b\\c\\d)"; const auto normal_text = "\\\\a\\\\b\\\\c\\\\d"; REQUIRE(text == normal_text); const auto atoms = AtomHelper::parse(text); REQUIRE(atoms.size() == 1); CHECK(atoms[0].isString()); /* CHECK(AtomHelper::toString(atoms) == text_result); CHECK(AtomHelper::toString(atoms[0]) == text_result); CHECK(atoms[0].getString() == text_result); */ } SECTION("foo \"bar 42\" 1 -2 3.14") { const auto atoms = AtomHelper::parse("foo \"bar 42\" 1 -2 3.14"); REQUIRE(atoms.size() == 5); CHECK(atoms[0].getString() == "foo"); CHECK(atoms[1].getString() == "bar 42"); CHECK((atoms[2].isInt() && atoms[3].isInt())); CHECK(atoms[4].isFloat()); } SECTION("test escaping") { const auto original_text = R"(foo "bar 42" 1 -2 3.14)"; const auto atoms = AtomHelper::parse(original_text); const auto text = AtomHelper::toString(atoms); CHECK(text == original_text); } } TEST_CASE("Atom Parse Quoted", "[Atom]") { SECTION("basic") { const auto atoms = AtomHelper::parse("\"0 10\""); REQUIRE(atoms.size() == 1); CHECK(atoms[0].isString()); CHECK(atoms[0].getString() == "0 10"); } SECTION("with comma") { const auto atoms = AtomHelper::parse(R"("0, 10")"); REQUIRE(atoms.size() == 1); CHECK(atoms[0].isString()); CHECK(atoms[0].getString() == "0, 10"); } SECTION("with escaped quote") { const auto typed_text = R"("name: \"toto\"")"; const auto formated_text = R"("name: \"toto\"")"; const auto display_text = R"(name: "toto")"; const auto atoms = AtomHelper::parse(typed_text); REQUIRE(atoms.size() == 1); REQUIRE(atoms[0].isString()); CHECK(atoms[0].getString() == display_text); CHECK(AtomHelper::toString(atoms[0]) == formated_text); CHECK(AtomHelper::toString(atoms[0], false) == display_text); } } TEST_CASE("Atom Parse Comma", "[Atom]") { SECTION("parse \"0, 10\" without comma option") { const auto atoms = AtomHelper::parse("0, 10"); REQUIRE(atoms.size() == 2); CHECK(atoms[0].isString()); CHECK(atoms[0].getString() == "0,"); CHECK(atoms[1].isInt()); } SECTION("parse \"0, 10\" without flag then toString") { const auto typed_text = R"(0, 10)"; const auto text_to_display = R"(0, 10)"; const auto atoms = AtomHelper::parse(typed_text); REQUIRE(atoms.size() == 2); CHECK(atoms[0].getString() == "0,"); CHECK(AtomHelper::toString(atoms[0]) == "0,"); const auto formated_text = AtomHelper::toString(atoms); CHECK(text_to_display == formated_text); } SECTION("parse with comma flag") { const auto atoms = AtomHelper::parse("0, 10", AtomHelper::ParsingFlags::Comma); REQUIRE(atoms.size() == 3); CHECK(atoms[0].isInt()); CHECK(atoms[1].isComma()); CHECK(atoms[2].isInt()); } SECTION("parse \"0, 10\" with comma flag then toString") { const auto original_text = "0, 10"; const auto atoms = AtomHelper::parse(original_text, AtomHelper::ParsingFlags::Comma); REQUIRE(atoms.size() == 3); const auto text = AtomHelper::toString(atoms); CHECK(text == original_text); } SECTION("parse comma without space after it") { const auto original_text = "0,10"; const auto atoms = AtomHelper::parse(original_text, AtomHelper::ParsingFlags::Comma); REQUIRE(atoms.size() == 3); CHECK(atoms[0].isInt()); CHECK(atoms[1].isComma()); CHECK(atoms[2].isInt()); const auto text = AtomHelper::toString(atoms); CHECK(text == "0, 10"); } SECTION("parse several commas") { const auto original_text = ",,,"; const auto atoms = AtomHelper::parse(original_text, AtomHelper::ParsingFlags::Comma); REQUIRE(atoms.size() == 3); CHECK(atoms[0].isComma()); CHECK(atoms[1].isComma()); CHECK(atoms[2].isComma()); const auto text = AtomHelper::toString(atoms); CHECK(text == ",,,"); } } TEST_CASE("Atom Parse Dollar", "[Atom]") { const int flags = AtomHelper::ParsingFlags::Dollar; SECTION("parse without dollar flags") { const auto atoms = AtomHelper::parse("$1 $2 $3 $4 $5 $6 $7 $8 $9"); REQUIRE(atoms.size() == 9); for (auto const& atom : atoms) { CHECK(atom.isString()); } } SECTION("invalid dollar atoms") { const auto atoms = AtomHelper::parse("$0 a$1 $10 $-1 $ $$", AtomHelper::ParsingFlags::Dollar); REQUIRE(atoms.size() == 6); for (auto const& atom : atoms) { CHECK(atom.isString()); CHECK(atom.getDollarIndex() == 0); } } SECTION("valid dollar atoms") { const auto atoms = AtomHelper::parse("$1 $2 $3 $4 $5 $6 $7 $8 $9", AtomHelper::ParsingFlags::Dollar); REQUIRE(atoms.size() == 9); for (auto const& atom : atoms) { REQUIRE(atom.isDollar()); static auto count = 0; CHECK(++count == atom.getDollarIndex()); } } SECTION("dollar followed by comma") { const auto atoms = AtomHelper::parse("$1, $2", AtomHelper::ParsingFlags::Dollar | AtomHelper::ParsingFlags::Comma); REQUIRE(atoms.size() == 3); CHECK(atoms[0].isDollar()); CHECK(atoms[1].isComma()); CHECK(atoms[2].isDollar()); } SECTION("dollar followed by comma without Comma flag") { const auto atoms = AtomHelper::parse("$1, $2", AtomHelper::ParsingFlags::Dollar); REQUIRE(atoms.size() == 2); CHECK(atoms[0].isString()); CHECK(atoms[0].getString() == "$1,"); CHECK(atoms[1].isDollar()); } }
26,088
C++
.cpp
686
29.432945
112
0.524123
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,392
test_Scheduler.cpp
Musicoll_Kiwi/Test/Tool/test_Scheduler.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 : [email protected] ============================================================================== */ #include <chrono> #include <atomic> #include <vector> #include <iostream> #include <thread> #include <memory> #include "../catch.hpp" #include <KiwiTool/KiwiTool_Scheduler.h> using namespace kiwi; ; using Scheduler = tool::Scheduler<std::chrono::high_resolution_clock>; using Task = Scheduler::Task; using CallBack = Scheduler::CallBack; // ==================================================================================== // // SCHEDULER // // ==================================================================================== // TEST_CASE("Scheduler - mono thread", "[Scheduler]") { Scheduler sch; SECTION("Simple add and process") { int counter = 0; std::function<void()> func = [&counter]() { ++counter; }; for(int i = 0 ; i < 10; ++i) { sch.schedule(std::make_shared<CallBack>(func), std::chrono::milliseconds(10 * i)); } while(counter < 10) { sch.process(); } CHECK(counter == 10); } SECTION("Schedule lambda") { bool success = false; sch.schedule([&success]() { success = true; }, std::chrono::milliseconds(0)); REQUIRE_FALSE(success); sch.process(); REQUIRE(success); } SECTION("Schedule lambda with delay") { bool success = false; sch.schedule([&success]() { success = true; }, std::chrono::milliseconds(1000)); REQUIRE_FALSE(success); sch.process(); REQUIRE_FALSE(success); std::this_thread::sleep_for(std::chrono::milliseconds(500)); sch.process(); REQUIRE_FALSE(success); // check with 5ms precision. std::this_thread::sleep_for(std::chrono::milliseconds(505)); sch.process(); REQUIRE(success); } SECTION("Ownership") { struct TestDestructor : public Task { TestDestructor(int &counter) : m_counter(counter) {} ~TestDestructor() { ++m_counter; } void execute() override final {} private: int& m_counter; }; int shared_count = 0; int transfered_count = 0; auto shared = std::make_shared<TestDestructor>(shared_count); auto transfered = std::make_shared<TestDestructor>(transfered_count); sch.schedule(shared); CHECK(shared.use_count() == 2); sch.schedule(std::move(transfered)); CHECK(transfered.use_count() == 0); sch.process(); CHECK(transfered_count == 1); // Check that transfered was destroyed. CHECK(shared_count == 0); // Check that shared was not destroyed. } SECTION("Cancel/Reschedule mono thread") { int i_standard = 0; int i_cancel = 0; int i_reschedule = 0; std::function<void()> func_std = [&i_standard](){++i_standard;}; std::function<void()> func_cancel = [&i_cancel](){++i_cancel;}; std::function<void()> func_reschedule = [&i_reschedule](){++i_reschedule;}; auto standard = std::make_shared<CallBack>(func_std); auto reschedule = std::make_shared<CallBack>(func_reschedule); auto cancel = std::make_shared<CallBack>(func_cancel); sch.schedule(std::move(standard)); sch.schedule(reschedule); sch.schedule(cancel); sch.schedule(reschedule, std::chrono::milliseconds(1000 * 60 * 60)); sch.unschedule(cancel); while(i_standard < 1) { sch.process(); } CHECK(i_standard == 1); CHECK(i_reschedule == 0); CHECK(i_cancel == 0); sch.schedule(reschedule); while(i_reschedule < 1) { sch.process(); } CHECK(i_reschedule == 1); } } // ==================================================================================== // // SCHEDULER - MULTI THREAD // // ==================================================================================== // TEST_CASE("Scheduler - Multithread", "[Scheduler]") { Scheduler sch; SECTION("multiproducer - multiconsumer") { std::atomic<size_t> count_producer_1(0); std::atomic<size_t> count_producer_2(0); std::function<void()> func_1 = [&count_producer_1]() { ++count_producer_1; }; std::function<void()> func_2 = [&count_producer_2]() { ++count_producer_2; }; std::thread producer_1([&sch, &func_1]() { size_t count_event = 0; while(count_event < 30) { sch.schedule(std::make_shared<CallBack>(func_1)); ++count_event; } }); std::thread producer_2([&sch, &func_2]() { size_t count_event = 0; while(count_event < 20) { sch.schedule(std::make_shared<CallBack>(func_2)); ++count_event; } }); while(count_producer_1 < 30 || count_producer_2 < 20) { sch.process(); } CHECK(count_producer_1 == 30); CHECK(count_producer_2 == 20); producer_1.join(); producer_2.join(); } SECTION("Execution Order") { std::vector<int> order; std::function<void(int)> func = [&order](int stamp) {order.push_back(stamp);}; SECTION("Pushing producer 1 before producer 2") { std::thread producer_1([&sch, &func]() { sch.schedule(std::make_shared<CallBack>(std::bind(func, 1))); }); producer_1.join(); std::thread producer_2([&sch, &func]() { sch.schedule(std::make_shared<CallBack>(std::bind(func, 2))); }); producer_2.join(); while(order.size() < 2) { sch.process(); } // Check that producer 1's task is executed first. CHECK(order[0] == 1); CHECK(order[1] == 2); } SECTION("Pushing producer 2 before producer 1") { std::thread producer_2([&sch, &func]() { sch.schedule(std::make_shared<CallBack>(std::bind(func, 2))); }); producer_2.join(); std::thread producer_1([&sch, &func]() { sch.schedule(std::make_shared<CallBack>(std::bind(func, 1))); }); producer_1.join(); while(order.size() < 2) { sch.process(); } // Check that producer 2's task is executed first. CHECK(order[0] == 2); CHECK(order[1] == 1); } } } // ==================================================================================== // // SCHEDULER - OWNERSHIP TRANSFER // // ==================================================================================== // TEST_CASE("Scheduler - Thread ids", "[Scheduler]") { Scheduler sch; SECTION("Consumer ownership transfer") { REQUIRE(sch.isThisConsumerThread()); // Transfer consumer ownership. std::thread consumer_thread([&sch]() { sch.setThreadAsConsumer(); REQUIRE(sch.isThisConsumerThread()); }); consumer_thread.join(); CHECK(!sch.isThisConsumerThread()); } } // ==================================================================================== // // SCHEDULER - LOCK // // ==================================================================================== // TEST_CASE("Scheduler - Lock", "[Scheduler]") { Scheduler sch; SECTION("Scheduler lock") { std::atomic<bool> quit_requested(false); std::thread consumer([&sch, &quit_requested]() { sch.setThreadAsConsumer(); while(!quit_requested.load()) { sch.process(); } }); { std::unique_lock<std::mutex> lock(sch.lock()); sch.schedule(std::make_shared<CallBack>([&quit_requested]() { quit_requested.store(true); })); std::this_thread::sleep_for(std::chrono::seconds(1)); REQUIRE(!quit_requested); } consumer.join(); CHECK(quit_requested); } } // ==================================================================================== // // SCHEDULER - DEFERING TASKS // // ==================================================================================== // TEST_CASE("Scheduler - Defering tasks", "[Scheduler]") { Scheduler sch; struct DeferTask : public Scheduler::Task { DeferTask(std::atomic<std::thread::id>& thread_id, std::atomic_bool& executed_flag) : m_thread_id(thread_id) , m_executed_flag(executed_flag) {} void execute() override { m_executed_flag.store(true); m_thread_id.store(std::this_thread::get_id()); } private: std::atomic<std::thread::id>& m_thread_id; std::atomic_bool& m_executed_flag; }; SECTION("Defering task on the same thread execute task directly") { std::atomic<std::thread::id> exec_thread; std::atomic_bool executed_flag(false); auto task = std::make_shared<DeferTask>(exec_thread, executed_flag); REQUIRE(!executed_flag); SECTION("task copy") { sch.defer(task); CHECK(task.use_count() == 1); } SECTION("task move") { sch.defer(std::move(task)); CHECK(task.use_count() == 0); } SECTION("task lambda") { sch.defer([&exec_thread, &executed_flag]() { executed_flag.store(true); exec_thread.store(std::this_thread::get_id()); }); } CHECK(executed_flag); CHECK(exec_thread == std::this_thread::get_id()); } SECTION("Defering task on another thread schedule the task") { std::atomic_bool quit_requested(false); std::thread consumer([&sch, &quit_requested]() { sch.setThreadAsConsumer(); while(!quit_requested.load()) { sch.process(); } }); std::atomic<std::thread::id> exec_thread(std::this_thread::get_id()); std::atomic_bool executed_flag(false); auto task = std::make_shared<DeferTask>(exec_thread, executed_flag); while(sch.isThisConsumerThread()){} REQUIRE(!executed_flag); SECTION("task copy") { sch.defer(task); while(exec_thread != consumer.get_id()){} CHECK(task.use_count() == 1); } SECTION("task move") { sch.defer(std::move(task)); while(exec_thread != consumer.get_id()){} CHECK(task.use_count() == 0); } SECTION("task lambda") { sch.defer([&exec_thread, &executed_flag]() { executed_flag.store(true); exec_thread.store(std::this_thread::get_id()); }); while(exec_thread != consumer.get_id()){} } CHECK(executed_flag); CHECK(exec_thread == consumer.get_id()); quit_requested.store(true); consumer.join(); } } // ==================================================================================== // // SCHEDULER - CUSTOM CLOCK // // ==================================================================================== // struct TickClock { using clock_t = std::chrono::high_resolution_clock; using duration = clock_t::duration; using time_point = clock_t::time_point; static void start() {current_time = clock_t::now();} static void tick() {current_time += std::chrono::milliseconds(1);}; static time_point now() {return current_time;}; private: static time_point current_time; }; TickClock::time_point TickClock::current_time = TickClock::clock_t::now(); TEST_CASE("Scheduler - custom clock", "[Scheduler]") { using TickScheduler = tool::Scheduler<TickClock>; SECTION("Execution order and custom clock") { TickClock::start(); TickScheduler scheduler; std::vector<int> order; std::function<void(int)> func = [&order](int number){order.push_back(number);}; auto task_0 = std::make_shared<TickScheduler::CallBack>(std::bind(func, 0)); auto task_1 = std::make_shared<TickScheduler::CallBack>(std::bind(func, 1)); auto task_2 = std::make_shared<TickScheduler::CallBack>(std::bind(func, 2)); auto task_3 = std::make_shared<TickScheduler::CallBack>(std::bind(func, 3)); scheduler.schedule(task_0, std::chrono::milliseconds(1)); scheduler.schedule(task_1, std::chrono::milliseconds(3)); scheduler.schedule(std::move(task_2), std::chrono::milliseconds(2)); scheduler.schedule(std::move(task_3), std::chrono::milliseconds(2)); scheduler.schedule(task_0, std::chrono::milliseconds(3)); scheduler.unschedule(task_1); while(order.size() < 3) { TickClock::tick(); scheduler.process(); } scheduler.unschedule(task_0); CHECK(order[0] == 2); CHECK(order[1] == 3); CHECK(order[2] == 0); } }
15,484
C++
.cpp
374
30.390374
91
0.500071
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,393
test_KiwiTool.cpp
Musicoll_Kiwi/Test/Tool/test_KiwiTool.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 : [email protected] ============================================================================== */ #define CATCH_CONFIG_RUNNER #include "../catch.hpp" int main( int argc, char* const argv[] ) { std::cout << "running Unit-Tests - KiwiTool ..." << '\n' << '\n'; int result = Catch::Session().run( argc, argv ); return result; }
1,113
C++
.cpp
22
47.318182
90
0.570356
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,394
test_Matrix.cpp
Musicoll_Kiwi/Test/Tool/test_Matrix.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 : [email protected] ============================================================================== */ #include <iostream> #include "../catch.hpp" #include <KiwiTool/KiwiTool_Matrix.h> using namespace kiwi; // ==================================================================================== // // MATRIX // // ==================================================================================== // void fill(tool::Matrix<int> & matrix) { for (size_t row = 0; row < matrix.getNumRows(); ++row) { for (size_t col = 0; col < matrix.getNumCols(); ++col) { matrix.at(row, col) = row * matrix.getNumCols() + col; } } } TEST_CASE("Matrix", "[Matrix]") { tool::Matrix<int> matrix(3, 4); fill(matrix); SECTION("Constructor") { tool::Matrix<int> matrix_cons(3, 4); CHECK(matrix_cons.getNumRows() == 3); CHECK(matrix_cons.getNumCols() == 4); CHECK(matrix_cons.at(2, 3) == 0); } SECTION("Copy Constructor") { tool::Matrix<int> matrix_cp(matrix); CHECK(matrix_cp.getNumRows() == matrix.getNumRows()); CHECK(matrix_cp.getNumCols() == matrix.getNumCols()); CHECK(matrix_cp.at(2, 1)== matrix.at(2, 1)); } SECTION("Move Constructors") { size_t rows = matrix.getNumRows(); size_t cols = matrix.getNumCols(); int value22 = matrix.at(2, 2); tool::Matrix<int> matrix_mv(std::move(matrix)); CHECK(matrix.getNumRows() == 0); CHECK(matrix.getNumCols() == 0); CHECK(matrix_mv.getNumRows() == rows); CHECK(matrix_mv.getNumCols() == cols); CHECK(matrix_mv.at(2, 2) == value22); } SECTION("Assignement") { tool::Matrix<int> matrix_as(matrix.getNumRows(), matrix.getNumCols()); matrix_as = matrix; CHECK(matrix_as.getNumRows() == matrix.getNumRows()); CHECK(matrix_as.getNumCols() == matrix.getNumCols()); CHECK(matrix_as.at(2, 2) == matrix.at(2, 2)); } SECTION("Move assignement") { size_t rows = matrix.getNumRows(); size_t cols = matrix.getNumCols(); int value22 = matrix.at(2, 2); tool::Matrix<int> matrix_mv(matrix.getNumRows(), matrix.getNumCols()); matrix_mv = std::move(matrix); CHECK(matrix.getNumRows() == 0); CHECK(matrix.getNumCols() == 0); CHECK(matrix_mv.getNumRows() == rows); CHECK(matrix_mv.getNumCols() == cols); CHECK(matrix_mv.at(2, 2) == value22); } }
3,457
C++
.cpp
83
34.650602
90
0.529899
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,395
KiwiNetwork_Http.h
Musicoll_Kiwi/Modules/KiwiNetwork/KiwiNetwork_Http.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once #include "KiwiHttp/KiwiHttp.h" #include "KiwiHttp/KiwiHttp_Session.h"
946
C++
.h
17
53.058824
90
0.580328
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,396
KiwiHttp.h
Musicoll_Kiwi/Modules/KiwiNetwork/KiwiHttp/KiwiHttp.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once #include <memory> #include <chrono> #include <functional> #include <thread> #include <atomic> #include <iostream> #include <boost/asio.hpp> #include <boost/asio/steady_timer.hpp> #include <boost/beast/core.hpp> #include <boost/beast/http.hpp> namespace beast = boost::beast; namespace kiwi { namespace network { namespace http { using Timeout = std::chrono::milliseconds; using Error = beast::error_code; // ================================================================================ // // RESPONSE // // ================================================================================ // template<class BodyType> class Response : public beast::http::response<BodyType> { public: Error error; }; template<class BodyType> using Request = beast::http::request<BodyType>; // ================================================================================ // // QUERY // // ================================================================================ // template<class ReqType, class ResType> class Query { private: // classes using Callback = std::function<void(Response<ResType> const&)>; public: // methods //! @brief Constructor. Query(std::unique_ptr<Request<ReqType>> request, std::string port); //! @brief Destructor. //! @details Wait for asynchronous operation to terminate. ~Query(); //! @brief Call request on the network. //! @details If query is already executed query will not be sent again. //! Previous reponse will be returned. Response<ResType> writeQuery(Timeout timeout = Timeout(0)); //! @brief Calls the request on a specific thread. //! @details If an asnchronous read is currently running, it will not be updated or relaunched. void writeQueryAsync(std::function<void(Response<ResType> const& res)> && callback, Timeout timeout = Timeout(0)); //! @brief Cancels the request. //! @details Once cancel is called query is executed and cannot be invoked again. //! If query was launched asynchronously callback will be called with a timeout error. void cancel(); //! @brief Returns true if the query was executed or cancelled. bool executed(); private: // methods using tcp = boost::asio::ip::tcp; //! @internal void init(Timeout timeout); //! @internal void handleTimeout(beast::error_code const& error); //! @internal void connect(tcp::resolver::results_type results); //! @internal void write(); //! @internal void read(); //! @internal void shutdown(beast::error_code const& error); private: // members std::unique_ptr<Request<ReqType>> m_request; Response<ResType> m_response; std::string m_port; boost::asio::io_context m_io_context; tcp::socket m_socket; boost::asio::steady_timer m_timer; tcp::resolver m_resolver; beast::flat_buffer m_buffer; std::thread m_thread; std::atomic<bool> m_executed; Callback m_callback; private: // deleted methods Query() = delete; Query(Query const& other) = delete; Query(Query && other) = delete; Query& operator=(Query const& other) = delete; Query& operator=(Query && other) = delete; }; }}} // namespace kiwi::network::http #include "KiwiHttp.hpp"
4,971
C++
.h
103
39.902913
122
0.527135
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,397
KiwiHttp_Session.h
Musicoll_Kiwi/Modules/KiwiNetwork/KiwiHttp/KiwiHttp_Session.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once #include "KiwiHttp.h" namespace kiwi { namespace network { namespace http { // ================================================================================ // // PAYLOAD // // ================================================================================ // class Payload { public: struct Pair; Payload() = default; template <class It> Payload(const It begin, const It end); Payload(std::initializer_list<Pair> const& pairs); void AddPair(Pair const& pair); std::string content; }; // ================================================================================ // // PARAMETERS // // ================================================================================ // class Parameters { public: struct Parameter; Parameters() = default; Parameters(const std::initializer_list<Parameter>& parameters); void AddParameter(Parameter const& parameter); std::string content; }; struct Parameters::Parameter { template <typename KeyType, typename ValueType> Parameter(KeyType&& key, ValueType&& value); std::string key; std::string value; }; // ================================================================================ // // BODY // // ================================================================================ // class Body { public: Body() = default; Body(std::string const& body); std::string content; }; // ================================================================================ // // SESSION // // ================================================================================ // class Session { private: // classes using HttpQuery = Query<beast::http::string_body, beast::http::string_body>; public: // methods using Response = http::Response<beast::http::string_body>; using Callback = std::function<void(Response)>; Session(); ~Session() = default; uint64_t getId() const; void setHost(std::string const& host); void setPort(std::string const& port); void setTarget(std::string const& endpoint); void setTimeout(Timeout timeout); void setAuthorization(std::string const& auth); void setParameters(Parameters && parameters); void setPayload(Payload && payload); void setBody(std::string const& content); bool executed(); void cancel(); Response Get(); void GetAsync(Callback callback); Response Post(); void PostAsync(Callback callback); Response Put(); void PutAsync(Callback callback); Response Delete(); void DeleteAsync(Callback callback); private: // methods void initQuery(); Response makeResponse(beast::http::verb verb); void makeResponse(beast::http::verb verb, Callback && callback); private: // members std::string m_port; std::string m_target; Parameters m_parameters; Payload m_payload; Body m_body; Timeout m_timeout; uint64_t m_id; std::unique_ptr<HttpQuery> m_query; beast::http::request_header<> m_req_header; }; }}} // namespace kiwi::network::http #include "KiwiHttp_Session.hpp"
5,028
C++
.h
108
36.898148
90
0.451585
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,398
KiwiHttp_Util.h
Musicoll_Kiwi/Modules/KiwiNetwork/KiwiHttp/KiwiHttp_Util.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once #include <string> namespace kiwi { namespace network { namespace http { namespace util { std::string urlEncode(std::string const& response); }}}} // namespace kiwi::network::http::util
1,072
C++
.h
19
53.421053
90
0.593023
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,399
KiwiHttp_Session.hpp
Musicoll_Kiwi/Modules/KiwiNetwork/KiwiHttp/KiwiHttp_Session.hpp
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once namespace kiwi { namespace network { namespace http { // ================================================================================ // // HTTP PAYLOAD // // ================================================================================ // template <class It> Payload::Payload(const It begin, const It end) { for (It pair = begin; pair != end; ++pair) { AddPair(*pair); } } struct Payload::Pair { template <typename KeyType, typename ValueType, typename std::enable_if<!std::is_integral<ValueType>::value, bool>::type = true> Pair(KeyType&& p_key, ValueType&& p_value) : key{std::forward<KeyType>(p_key)} , value{std::forward<ValueType>(p_value)} { ; } template <typename KeyType> Pair(KeyType&& p_key, const std::int32_t& p_value) : key{std::forward<KeyType>(p_key)} , value{std::to_string(p_value)} { ; } std::string key; std::string value; }; // ================================================================================ // // HTTP PARAMETERS // // ================================================================================ // template <typename KeyType, typename ValueType> Parameters::Parameter::Parameter(KeyType&& key, ValueType&& value) : key{std::forward<KeyType>(key)} , value{std::forward<ValueType>(value)} { ; } }}} // namespace kiwi::network::http
2,602
C++
.h
58
38.017241
90
0.454069
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,400
KiwiHttp.hpp
Musicoll_Kiwi/Modules/KiwiNetwork/KiwiHttp/KiwiHttp.hpp
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once namespace kiwi { namespace network { namespace http { // ================================================================================ // // HTTP QUERY // // ================================================================================ // template<class ReqType, class ResType> Query<ReqType, ResType>::Query(std::unique_ptr<beast::http::request<ReqType>> request, std::string port) : m_request(std::move(request)) , m_response() , m_port(port) , m_io_context() , m_socket(m_io_context) , m_timer(m_io_context) , m_resolver(m_io_context) , m_buffer() , m_thread() , m_executed(false) , m_callback() { } template<class ReqType, class ResType> Query<ReqType, ResType>::~Query() { if (m_thread.joinable()) { m_thread.join(); } } template<class ReqType, class ResType> Response<ResType> Query<ReqType, ResType>::writeQuery(Timeout timeout) { if (m_thread.joinable()) { m_thread.join(); } if (!executed()) { init(timeout); while(!executed()) { m_socket.get_io_context().poll_one(); } } return m_response; } template<class ReqType, class ResType> void Query<ReqType, ResType>::writeQueryAsync(std::function<void(Response<ResType> const& res)> && callback, Timeout timeout) { if (!executed() && !m_thread.joinable()) { init(timeout); m_callback = std::move(callback); m_thread = std::thread([this]() { while(!executed()) { m_socket.get_io_context().poll_one(); } }); } } template<class ReqType, class ResType> void Query<ReqType, ResType>::cancel() { if (m_timer.cancel() != 0) { if (m_thread.joinable()) { m_thread.join(); } } if (!m_executed) { shutdown(boost::asio::error::basic_errors::timed_out); } } template<class ReqType, class ResType> bool Query<ReqType, ResType>::executed() { return m_executed.load(); } template<class ReqType, class ResType> void Query<ReqType, ResType>::init(Timeout timeout) { if (timeout > Timeout(0)) { m_timer.expires_from_now(timeout); m_timer.async_wait([this](Error const& error) { handleTimeout(error); }); } m_request->prepare_payload(); const std::string host = m_request->at(beast::http::field::host).to_string(); m_resolver.async_resolve(host, m_port, [this](beast::error_code ec, tcp::resolver::results_type results) { if (ec) { shutdown(ec); } else { connect(results); } }); } template<class ReqType, class ResType> void Query<ReqType, ResType>::handleTimeout(Error const& error) { shutdown(boost::asio::error::basic_errors::timed_out); } template<class ReqType, class ResType> void Query<ReqType, ResType>::connect(tcp::resolver::results_type results) { boost::asio::async_connect(m_socket, results, [this](beast::error_code ec, tcp::endpoint const& endpoint){ boost::ignore_unused(endpoint); if (ec) { shutdown(ec); } else { write(); } }); } template<class ReqType, class ResType> void Query<ReqType, ResType>::write() { beast::http::async_write(m_socket, *m_request, [this](beast::error_code ec, std::size_t bytes_transferred) { boost::ignore_unused(bytes_transferred); if (ec) { shutdown(ec); } else { read(); } }); } template<class ReqType, class ResType> void Query<ReqType, ResType>::read() { beast::http::async_read(m_socket, m_buffer, m_response, [this](beast::error_code ec, std::size_t bytes_transferred) { boost::ignore_unused(bytes_transferred); shutdown(ec); }); } template<class ReqType, class ResType> void Query<ReqType, ResType>::shutdown(Error const& error) { if (error) { m_response.error = error; } boost::system::error_code ec; m_socket.shutdown(tcp::socket::shutdown_both, ec); if (m_callback) { m_callback(m_response); } m_executed.store(true); } }}} // namespace kiwi::network::http
6,306
C++
.h
185
23.167568
129
0.486616
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,401
KiwiTool_Atom.h
Musicoll_Kiwi/Modules/KiwiTool/KiwiTool_Atom.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once #include <cassert> #include <iostream> #include <sstream> #include <cstring> #include <memory> #include <vector> namespace kiwi { namespace tool { // ================================================================================ // // ATOM // // ================================================================================ // //! @brief The Atom can dynamically hold different types of value //! @details The Atom can hold an integer, a float or a string. class Atom { public: // methods // ================================================================================ // // Types // // ================================================================================ // //! @brief The type of a signed integer number in the Atom class. using int_t = int64_t; //! @brief The type of a floating-point number in the Atom class. using float_t = double; //! @brief The type of a string type in the Atom class. using string_t = std::string; //! @brief Enum of Atom value types //! @see getType(), isNull(), isInt(), isFloat(), isNumber(), isString(), isComma(), isDollar() enum class Type : uint8_t { // basic types: Null = 0, Int, Float, String, // special types: Comma, Dollar, }; // ================================================================================ // // CONSTRUCTORS // // ================================================================================ // //! @brief Default constructor. //! @details Constructs an Atom of type Null. Atom() noexcept; //! @brief Constructs an int_t Atom. //! @details The integer value will be 1 or 0 depending on the bool value. //! @param value The value. Atom(const bool value) noexcept; //! @brief Constructs an int_t Atom. //! @param value The value. Atom(const int value) noexcept; //! @brief Constructs an int_t Atom. //! @param value The value. Atom(const long value) noexcept; //! @brief Constructs an int_t Atom. //! @param value The value. Atom(const long long value) noexcept; //! @brief Constructs a float_t Atom. //! @details infinty and NaN value both produce a Null Atom type. //! @param value The value. Atom(const float value) noexcept; //! @brief Constructs a float_t Atom. //! @details infinty and NaN value both produce a Null Atom type. //! @param value The value. Atom(const double value) noexcept; //! @brief Constructs a string_t Atom. //! @param sym The value. Atom(string_t const& sym); //! @brief Constructs a string_t Atom. //! @param sym The value. Atom(string_t&& sym); //! @brief Constructs a string_t Atom. //! @param sym The value. Atom(char const* sym); //! @brief Constructs a Comma Atom. static Atom Comma(); //! @brief Constructs a Dollar Atom. //! @param index must be between 1 and 9 //! @return A Dollar Atom or a Null Atom if out of range. static Atom Dollar(int_t index); //! @brief Copy constructor. //! @details Constructs an Atom by copying the contents of an other Atom. //! @param other The other Atom. Atom(Atom const& other); //! @brief Move constructor. //! @details Constructs an Atom value by stealing the contents of an other Atom //! using move semantics, leaving the other as a Null value Atom. //! @param other The other Atom value. Atom(Atom&& other); //! @brief Destructor. ~Atom(); //! @brief Copy assigment operator. //! @details Copies an Atom value. //! @param other The Atom object to copy. Atom& operator=(Atom const& other); //! @brief Copy assigment operator. //! @details Copies an Atom value with the "copy and swap" method. //! @param other The Atom object to copy. Atom& operator=(Atom&& other) noexcept; // ================================================================================ // // Type Getters // // ================================================================================ // //! @brief Get the type of the Atom. //! @return The Type of the atom as a Type. //! @see isNull(), isInt(), isFloat(), isNumber(), isString() Type getType() const noexcept; //! @brief Returns true if the Atom is Null. //! @return true if the Atom is Null. //! @see getType(), isInt(), isFloat(), isNumber(), isString() bool isNull() const noexcept; //! @brief Returns true if the Atom is an int_t. //! @return true if the Atom is an int_t. //! @see getType(), isNull(), isFloat(), isNumber(), isString() bool isInt() const noexcept; //! @brief Returns true if the Atom is a float_t. //! @return true if the Atom is an float_t. //! @see getType(), isNull(), isInt(), isNumber(), isString() bool isFloat() const noexcept; //! @brief Returns true if the Atom is a bool, an int_t, or a float_t. //! @return true if the Atom is a bool, an int_t, or a float_t. //! @see getType(), isNull(), isInt(), isFloat(), isString() bool isNumber() const noexcept; //! @brief Returns true if the Atom is a string_t. //! @return true if the Atom is a string_t. //! @see getType(), isNull(), isInt(), isFloat(), isNumber() bool isString() const noexcept; //! @brief Returns true if the Atom is a string_t that contains the special "bang" keyword. //! @return true if the Atom is a string_t that contains the special "bang" keyword. //! @see getType(), isNull(), isInt(), isFloat(), isString() bool isBang() const; //! @brief Returns true if the Atom is an comma_t. //! @return true if the Atom is a comma_t. //! @see getType(), isNull(), isInt(), isFloat(), isNumber(), isString() bool isComma() const noexcept; //! @brief Returns true if the Atom is a dollar or a dollar typed. //! @return true if the Atom is a dollar_t. //! @see getType(), isNull(), isInt(), isFloat(), isNumber(), isString() bool isDollar() const noexcept; // ================================================================================ // // Value Getters // // ================================================================================ // //! @brief Retrieves the Atom value as an int_t value. //! @return The current integer atom value if it is a number otherwise 0. //! @see getType(), isNumber(), isInt(), getFloat() int_t getInt() const noexcept; //! @brief Retrieves the Atom value as a float_t value. //! @return The current floating-point atom value if it is a number otherwise 0.0. //! @see getType(), isNumber(), isFloat(), getInt() float_t getFloat() const noexcept; //! @brief Retrieves the Atom value as a string_t value. //! @return The current string atom value if it is a string otherwise an empty string. //! @see getType(), isString(), getInt(), getFloat() string_t const& getString() const; //! @brief Retrieves the Dollar index value if the Atom is a dollar type. //! @return The Dollar index if the Atom is a dollar, 0 otherwise. //! @see getType(), isDollar(), isDollarTyped() int_t getDollarIndex() const; private: // methods // ================================================================================ // // VALUE // // ================================================================================ // //! @internal Exception-safe object creation helper static string_t* create_string_pointer(string_t const& v); static string_t* create_string_pointer(string_t&& v); //! @internal The actual storage union for an Atom value. union atom_value { //! @brief number (integer). int_t int_v; //! @brief number (floating-point). float_t float_v; //! @brief string. string_t* string_v; //! @brief default constructor (for null values). atom_value() = default; //! @brief constructor for numbers (integer). atom_value(const int_t v) noexcept : int_v(v) {} //! @brief constructor for numbers (floating-point). atom_value(const float_t v) noexcept : float_v(v) {} //! @brief constructor for strings atom_value(string_t const& v) : string_v(create_string_pointer(v)) {} //! @brief constructor for strings atom_value(string_t&& v) : string_v(create_string_pointer(std::move(v))) {} }; private: // methods //! @internal Atom Type (Null by default) Type m_type = Type::Null; //! @internal Atom value atom_value m_value = {}; }; // ================================================================================ // // ATOM HELPER // // ================================================================================ // //! @brief An Atom helper class. struct AtomHelper { struct ParsingFlags { enum Flags { Comma = 0x01, Dollar = 0x02, }; }; //! @brief Parse a string into a vector of atoms. //! @param text The string to parse. //! @param flags The flags as a set of #ParsingFlags. //! @return The vector of atoms. //! @details The parsing method can be altered by the #ParsingFlags \flags passed as parameter. //! If the ParsingFlags::Comma flag is set, it will create a Comma atom type //! for each ',' char of the string (except if the text is in double quotes) //! If the ParsingFlags::Dollar flag is set, it will create a Dollar atom type //! for each '$' char followed by a digit between 1 and 9. //! @example The string : "foo \"bar 42\" 1 -2 3.14" will be parsed into a vector of 5 Atom. //! The atom types will be determined automatically as : //! 2 #Atom::Type::String, 2 #Atom::Type::Int, and 1 #Atom::Type::Float. static std::vector<Atom> parse(std::string const& text, int flags = 0); //! @brief Convert an Atom into a string. static std::string toString(Atom const& atom, const bool add_quotes = true); //! @brief Convert a vector of Atom into a string. //! @details This method will call the toString static method for each atom //! of the vector and output a whitespace between each one //! (except for the special Atom::Type::Comma that is stuck to the previous Atom). static std::string toString(std::vector<Atom> const& atoms, const bool add_quotes = true); static std::string trimDecimal(std::string const& text); }; }}
13,268
C++
.h
237
45.059072
103
0.50398
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,402
KiwiTool_ConcurrentQueue.h
Musicoll_Kiwi/Modules/KiwiTool/KiwiTool_ConcurrentQueue.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once #include <cstddef> #include <atomic> #include <concurrentqueue.h> namespace kiwi { namespace tool { // ==================================================================================== // // CONCURRENTQUEUE // // ==================================================================================== // namespace mc = moodycamel; //! @brief A mono producer, mono consumer FIFO lock free queue. //! @details Wrapper around a thirdparty concurrent queue. //! @see https://github.com/cameron314/readerwriterqueue template <class T> class ConcurrentQueue final { public: // methods //! @brief Constructor. //! @details Reserves memory space for at least capcity elements. ConcurrentQueue(size_t capacity): m_queue(capacity), m_size(0) { } //! @brief Destructor. ~ConcurrentQueue() = default; //! @brief Pushes element at end of queue (by copy). //! @details If number of elements exceeds capacity allocation will occur. //! Increments element counter. void push(T const& value) { if(m_queue.enqueue(value)) { m_size++; } } //! @brief Pushes element at end of queue (by move). //! @details If number of elements exceeds capacity allocation will occur. //! Increments element counter. void push(T&& value) { if(m_queue.enqueue(std::forward<T>(value))) { m_size++; } } //! @brief Pops first element in the queue. //! @details Returns false if the queue was empty and pop failed, true otherwise. bool pop(T & value) { if(m_queue.try_dequeue(value)) { m_size--; return true; } return false; } //! @brief Returns an approximative size for the queue. //! @details Since size is increased and decreased after elements are effectively pushed or poped, //! for the consumer the returned size is guaranteed to be lower or equal //! to the effective size of the queue, for the producer the returned size is guaranteed to be //! greater or equal than the effective size of the queue. size_t load_size() const { return m_size.load(); } private: // classes struct Trait : public moodycamel::ConcurrentQueueDefaultTraits { static const size_t BLOCK_SIZE = 1024; }; private: // members mc::ConcurrentQueue<T, Trait> m_queue; std::atomic<int> m_size; private: // deleted methods ConcurrentQueue() = delete; ConcurrentQueue(ConcurrentQueue const& other) = delete; ConcurrentQueue(ConcurrentQueue && other) = delete; ConcurrentQueue& operator=(ConcurrentQueue const& other) = delete; ConcurrentQueue& operator=(ConcurrentQueue && other) = delete; }; }}
4,284
C++
.h
95
34.421053
107
0.533767
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,403
KiwiTool_CircularBuffer.h
Musicoll_Kiwi/Modules/KiwiTool/KiwiTool_CircularBuffer.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once #include <algorithm> #include <cstdlib> #include <cassert> namespace kiwi { namespace tool { // ================================================================================ // // CIRCULAR BUFFER // // ================================================================================ // //! @todo documentation inspired from boost circular buffer //! @see http://www.boost.org/doc/libs/1_59_0/doc/html/boost/circular_buffer.html#idp23975984-bb template<class T> class CircularBuffer final { public: // methods CircularBuffer(size_t capacity): m_buffer((T*) std::malloc(capacity * sizeof(T))), m_head(0), m_tail(0), m_size(0), m_capacity(capacity) { } CircularBuffer(size_t capacity, size_t size, T const& value): m_buffer((T*) std::malloc(capacity * sizeof(T))), m_head(0), m_tail(0), m_size(0), m_capacity(capacity) { assert(m_capacity >= m_size); for (int i = 0; i < size; ++i) { push_back(value); } } ~CircularBuffer() { for (int i = std::min(m_head, m_tail); i < std::max(m_head, m_tail); ++i) { (m_buffer + i)->~T(); } std::free(m_buffer); } void assign(size_t nb_elements, const T& value) { clear(); for(int i = 0; i < nb_elements; ++i) { push_back(value); } } void clear() { size_t init_size = m_size; for (int i = 0; i < init_size; ++i) { pop_front(); } } size_t size() const { return m_size; } T const& operator[](size_t index) const noexcept { return *(m_buffer + ((m_head + index) % m_size)); } T& operator[](size_t index) noexcept { return *(m_buffer + ((m_head + index) % m_size)); } void push_back(T const& value) { if (m_size == m_capacity) { (m_buffer + m_tail)->~T(); increment_head(); } new (m_buffer + m_tail) T(value); increment_tail(); } void pop_front() { if (m_size != 0) { (m_buffer + m_head)->~T(); increment_head(); } } private: // methods void increment_head() { m_head = (m_head + 1) == m_capacity ? 0 : m_head + 1; --m_size; } void increment_tail() { m_tail = (m_tail + 1) == m_capacity ? 0 : m_tail + 1; ++m_size; } private: // members T* m_buffer; size_t m_head; size_t m_tail; size_t m_size; size_t m_capacity; private: // deleted methods CircularBuffer() = delete; CircularBuffer(CircularBuffer const& other) = delete; CircularBuffer(CircularBuffer && other) = delete; CircularBuffer& operator=(CircularBuffer const& other) = delete; CircularBuffer& operator=(CircularBuffer && other) = delete; }; }}
4,741
C++
.h
128
24.734375
101
0.436963
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,404
KiwiTool_Matrix.h
Musicoll_Kiwi/Modules/KiwiTool/KiwiTool_Matrix.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once #include <cstddef> namespace kiwi { namespace tool { // ================================================================================ // // MATRIX // // ================================================================================ // //! @brief A matrix data structure. //! @details Implementation of basic matrix operation. //! @todo Adds more usefull operation. template<class Type> class Matrix final { public: // methods //! @brief Constructor. //! @details Initializes matrix with default constructor. Matrix(size_t num_rows, size_t num_cols); //! @brief Destructor. ~Matrix(); //! @brief Copy constructor. Matrix(Matrix const& other); //! @brief Move constructor. Matrix(Matrix && other); //! @brief Assignment operator. //! @details Number of rows and columns must match. Matrix& operator=(Matrix const& other); //! @brief Move assignement operator. //! @details Number of rows and columns must match. Matrix& operator=(Matrix && other); //! @brief Returns the number of rows. size_t getNumRows() const; //! @brief Returns the number of colunms. size_t getNumCols() const; //! @brief Gets a value stored in matrix. //! @details row (res column) must be inferior to number of rows (res num columns). Type & at(size_t row, size_t colunm); //! @brief Gets a value stored in matrix. //! @details row (res column) must be inferior to number of rows (res num columns). Type const& at(size_t row, size_t column) const; private: // members size_t m_num_rows; size_t m_num_cols; Type* m_data; private: // deleted methods Matrix() = delete; }; }} #include <KiwiTool/KiwiTool_Matrix.hpp>
2,996
C++
.h
61
40.262295
91
0.53547
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,405
KiwiTool_Parameter.h
Musicoll_Kiwi/Modules/KiwiTool/KiwiTool_Parameter.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once #include <KiwiTool/KiwiTool_Atom.h> namespace kiwi { namespace tool { //! @brief Parameter is a class designed to represent any type of data. //! @details It's implemented as a vector of Atom. //! @todo Use virtual classes that implements check of atoms, copy and default initialization instead of using //! switches. See in juce::variant. class Parameter { public: // classes //! @brief The different types of data represented. enum class Type { Int, Float, String }; public: // methods //! @brief Default Constructor. //! @details Initialises data according to type. Parameter(Type type); //! @brief Constructor. //! @details Atoms must be well formated for the construction to succeed. Parameter(Type type, std::vector<Atom> const atoms); //! @brief Copy constructor. Parameter(Parameter const& other); //! @brief Assignment operator. Parameter& operator=(Parameter const& other); //! @brief Desctructor. ~Parameter(); //! @brief Returns the type of the parameter. Type getType() const; //! @brief Returns the underlying data of the parameter. Atom const& operator[](size_t index) const; private: // members Type m_type; std::vector<Atom> m_atoms; private: // deleted methods Parameter() = delete; }; }}
2,571
C++
.h
55
36.690909
115
0.58
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,406
KiwiTool_Beacon.h
Musicoll_Kiwi/Modules/KiwiTool/KiwiTool_Beacon.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once #include <string> #include <map> #include <set> #include <KiwiTool/KiwiTool_Atom.h> namespace kiwi { namespace tool { // ================================================================================ // // BEACON // // ================================================================================ // //! @brief The beacon is unique and matchs to a "unique" string in the scope of a beacon factory and can be used to bind beacon's castaways. //! @details The beacon are uniques in the scope of a beacon factory and matchs to a string. //! If you create a beacon with a string that already matchs to a beacon of the beacon factory, //! it will return this beacon otherwise it will create a new beacon. //! Thus, the beacons can be used to bind, unbind and retrieve castways. //! After recovering a castaway, you should dynamically cast it to the class you expect. //! More often, this will be a kiwi Object. //! @see Beacon::Factory //! @see Beacon::Castaway class Beacon { public: // methods class Castaway; //! @brief Gets the name of the beacon. inline std::string getName() const {return m_name;} //! @brief Destructor. ~Beacon() = default; //! @brief Adds a castaway in the binding list of the beacon. void bind(Castaway& castaway); //! @brief Removes a castaways from the binding list of the beacon. void unbind(Castaway& castaway); //! @brief Dispatch message to beacon castaways. void dispatch(std::vector<Atom> const& args); public: // nested classes // ================================================================================ // // BEACON CASTAWAY // // ================================================================================ // //! @brief The beacon castaway can be binded to a beacon. class Castaway { public: virtual ~Castaway() {} virtual void receive(std::vector<Atom> const& args) = 0; }; // ================================================================================ // // BEACON FACTORY // // ================================================================================ // //! @brief The beacon factory is used to create beacons. class Factory { public: Factory() = default; ~Factory() = default; Beacon& getBeacon(std::string const& name); private: std::map<std::string, std::unique_ptr<Beacon>> m_beacons; }; private: // methods //! @internal Constructor. Beacon(std::string const& name); friend class Beacon::Factory; private: // members const std::string m_name; std::set<Castaway*> m_castaways; private: // deleted methods Beacon(Beacon const&) = delete; Beacon(Beacon&&) = delete; Beacon& operator=(Beacon const&) = delete; Beacon& operator=(Beacon&&) = delete; }; }}
4,446
C++
.h
84
42.77381
145
0.481634
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,407
KiwiTool_Scheduler.h
Musicoll_Kiwi/Modules/KiwiTool/KiwiTool_Scheduler.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once #include <cstdint> #include <map> #include <list> #include <chrono> #include <stdexcept> #include <mutex> #include <set> #include <memory> #include <mutex> #include <thread> #include <KiwiTool/KiwiTool_ConcurrentQueue.h> namespace kiwi { namespace tool { // ==================================================================================== // // SCHEDULER // // ==================================================================================== // //! @brief A class designed to delay tasks' execution between threads that where previously declared. //! @details The scheduler is designed as a singleton that uses multiple event lists. //! Before processing the scheduler one should create an instance and register all threads that will //! use the scheduler. One can override the clock used by the scheduler to get time. template<class Clock = std::chrono::high_resolution_clock> class Scheduler final { public: // classes using clock_t = Clock; using time_point_t = typename Clock::time_point; using duration_t = typename Clock::duration; class Task; class CallBack; class Timer; private: // classes class Queue; class Event; public: // methods //! @brief Constructor //! @details Sets current thread as the consumer thread. Scheduler(); //! @brief Desctructor. ~Scheduler(); //! @brief Sets the current thread as the consumer thread. //! @details This method can be called for instance if the scheduler's constructor //! is called on another thread than desired consumer. void setThreadAsConsumer(); //! @brief Check wehter or not this thread is the consumer. //! @details This method can be usefull to help decide if a direct call can be made //! or if the scheduler shall be used. bool isThisConsumerThread() const; //! @brief Delays execution of a task. Shared ownership. //! @details Calling twice this method with same task will cancel the previous scheduled execution //! and add a new one at specified time. void schedule(std::shared_ptr<Task> const& task, duration_t delay = std::chrono::milliseconds(0)); //! @brief Delays execution of a task. Transfer ownership. //! @details Calling twice this method with same task will cancel the previous scheduled execution //! and add a new one at specified time. void schedule(std::shared_ptr<Task> && task, duration_t delay = std::chrono::milliseconds(0)); //! @brief Delays execution of a function by the scheduler. //! @details Internally create a callback that will be executed and destroyed by the scheduler. void schedule(std::function<void(void)> && func, duration_t delay = std::chrono::milliseconds(0)); //! @brief Conditionally schedule a task in the consumer thread. //! @details The task is scheduled only if the calling thread is not the consumer thread. Otherwise //! it is executed right away. void defer(std::shared_ptr<Task> const& task); //! @brief Conditionally schedule a task in the consumer thread. //! @details The task is scheduled only if the calling thread is not the consumer thread. //! Otherwise it is executed right away. Task is destroyed when executed. void defer(std::shared_ptr<Task> && task); //! @brief Conditionally schedule a function in the consumer thread. //! @details The function is scheduled only if the calling thread is not the consumer thread. //! Otherwise it is executed right away. void defer(std::function<void(void)> && func); //! @brief Used to cancel the execution of a previously scheduled task. //! @details If the task is currently being processed by the scheduler, this method does't //! wait for the execution to finish but only guarantee that further execution will no occur. void unschedule(std::shared_ptr<Task> const& task); //! @brief Processes events of the consumer that have reached exeuction time. void process(); //! @brief Lock the process until the returned lock is out of scope. std::unique_lock<std::mutex> lock() const; private: // members Queue m_queue; mutable std::mutex m_mutex; std::thread::id m_consumer_id; private: // deleted methods Scheduler(Scheduler const& other) = delete; Scheduler(Scheduler && other) = delete; Scheduler& operator=(Scheduler const& other) = delete; Scheduler& operator=(Scheduler && other) = delete; }; // ==================================================================================== // // QUEUE // // ==================================================================================== // //! @brief A class that holds a list of scheduled events. //! @details Implementation countains a list of events sorted by execution time that is updated //! before processing using commands. A queue is created for each consumer. template <class Clock> class Scheduler<Clock>::Queue final { public: // classes struct Command { std::shared_ptr<Task> m_task; time_point_t m_time; }; public: // methods //! @brief Constructor. Queue(); //! @brief Destructor ~Queue(); //! @brief Delays the execution of a task. Shared ownership. void schedule(std::shared_ptr<Task> const& task, duration_t delay); //! @brief Delays the execution of a task. Transfer ownership. void schedule(std::shared_ptr<Task> && task, duration_t delay); //! @brief Cancels the execution of a task. void unschedule(std::shared_ptr<Task> const& task); //! @brief Processes all events that have reached execution time. void process(time_point_t process_time); private: // methods //! @internal void emplace(Event && event); //! @internal void remove(Event const& event); private: // members std::vector<Event> m_events; ConcurrentQueue<Command> m_commands; private: // friend classes friend class Scheduler; private: // deleted methods Queue(Queue const& other) = delete; Queue(Queue && other) = delete; Queue& operator=(Queue const& other) = delete; Queue& operator=(Queue && other) = delete; }; // ==================================================================================== // // TASK // // ==================================================================================== // //! @brief The abstract class that the scheduler executes. Caller must override execute function //! to specify the callback behavior. template <class Clock> class Scheduler<Clock>::Task { public: // methods //! @brief Constructor. //! @details A certain task is designed to be scheduled on only one consumer. Task(); //! @brief Destructor. //! @details It is not safe to destroy a task from another thread than the consumer because it can be //! concurrent to its execution. One can create a task that deletes itself at exeuction time or lock //! a consumer using Scheduler::Lock before deleting the task. virtual ~Task(); private: // methods //! @brief The pure virtual execution method. Called by the scheduler when execution time //! is reached. virtual void execute() = 0; private: // friends friend class Scheduler; private: // deleted methods Task(Task const& other) = delete; Task(Task && other) = delete; Task& operator=(Task const& other) = delete; Task& operator=(Task && other) = delete; }; // ==================================================================================== // // CALLBACK // // ==================================================================================== // //! @brief The scheduler's callback is a task that uses an std::function for //! conveniency. template<class Clock> class Scheduler<Clock>::CallBack : public Scheduler<Clock>::Task { public: // methods //! @brief Constructor, initializes function. CallBack(std::function<void(void)> func); //! @brief Destructor. ~CallBack(); //! @brief Executes the given functions. void execute() override final; private: // members std::function<void(void)> m_func; private: // deleted methods CallBack() = delete; CallBack(CallBack const& other) = delete; CallBack(CallBack && other) = delete; CallBack& operator=(CallBack const& other) = delete; CallBack& operator=(CallBack && other) = delete; }; // ==================================================================================== // // TIMER // // ==================================================================================== // //! @brief An abstract class designed to repetedly call a method at a specified intervall of time. //! Overriding timerCallBack and calling startTimer will start repetdly calling method. template<class Clock> class Scheduler<Clock>::Timer { private: // classes class Task; public: // methods //! @brief Constructor. //! @details A timer can only be created for a certain consumer. Timer(Scheduler & scheduler); //! @brief Destructor. //! @details It is not safe to destroy a timer in another thread than the consumer. If intended //! one shall lock the consumer before destroying the timer. ~Timer(); //! @brief Starts the timer. //! @details Will cause timerCallBack to be called at a specified rate by the right consumer. void startTimer(duration_t period); //! @brief Stops the timer. //! @details If called when timerCallBack is being processed, stopTimer will not wait for the execution //! to finish but will only guarantee that further execution will not occur. void stopTimer(); private: // methods //! @brief The pure virtual call back function. virtual void timerCallBack() = 0; //! @brief Reschedule task before calling virtual method timerCallBack. void callBackInternal(); private: // members Scheduler & m_scheduler; std::shared_ptr<Task> m_task; duration_t m_period; private: // deleted methods Timer() = delete; Timer(Timer const& other) = delete; Timer(Timer && other) = delete; Timer& operator=(Timer const& other) = delete; Timer& operator=(Timer && other) = delete; }; // ==================================================================================== // // EVENT // // ==================================================================================== // //! @brief An event that associates a task and a execution time. template<class Clock> class Scheduler<Clock>::Event final { public: // methods //! @brief Constructor. Event(std::shared_ptr<Task> && task, time_point_t time); //! @brief Moove constructor Event(Event && other); //! @brief Moove assignment operator. Event& operator=(Event && other); //! @brief Destructor. ~Event(); //! @brief Called by the scheduler to execute a the task. void execute(); private: // friends friend class Scheduler; private: // members std::shared_ptr<Task> m_task; time_point_t m_time; private: // deleted methods Event() = delete; Event(Event const& other) = delete; Event& operator=(Event const& other) = delete; }; }} #include <KiwiTool/KiwiTool_Scheduler.hpp>
14,666
C++
.h
270
42.840741
112
0.54913
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,408
KiwiTool_Matrix.hpp
Musicoll_Kiwi/Modules/KiwiTool/KiwiTool_Matrix.hpp
/* ============================================================================== 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 : [email protected] ============================================================================== */ #include <cstring> #include <cassert> #include <KiwiTool/KiwiTool_Matrix.h> namespace kiwi { namespace tool { // ================================================================================ // // MATRIX // // ================================================================================ // template<class Type> void copy(Type * const dest, Type const * const src, size_t size) { for (size_t index = 0; index < size; ++index) { dest[index] = src[index]; } } template<class Type> Matrix<Type>::Matrix(size_t num_rows, size_t num_cols): m_num_rows(num_rows), m_num_cols(num_cols), m_data(new Type[m_num_rows * m_num_cols]()) { } template<class Type> Matrix<Type>::~Matrix() { delete[] m_data; } template<class Type> Matrix<Type>::Matrix(Matrix const& other): m_num_rows(other.m_num_rows), m_num_cols(other.m_num_cols), m_data(new Type[m_num_rows * m_num_cols]()) { copy(m_data, other.m_data, m_num_rows * m_num_cols); } template<class Type> Matrix<Type>::Matrix(Matrix && other): m_num_rows(other.m_num_rows), m_num_cols(other.m_num_cols), m_data(new Type[m_num_rows * m_num_cols]()) { copy(m_data, other.m_data, m_num_rows * m_num_cols); other.m_num_cols = 0; other.m_num_rows = 0; other.m_data = nullptr; } template<class Type> Matrix<Type> & Matrix<Type>::operator=(Matrix const& other) { assert((m_num_rows == other.m_num_rows && m_num_cols == other.m_num_cols) && "Assigning matrixes with different size"); copy(m_data, other.m_data, m_num_rows * m_num_cols); return *this; } template<class Type> Matrix<Type> & Matrix<Type>::operator=(Matrix && other) { assert((m_num_rows == other.m_num_rows && m_num_cols == other.m_num_cols) && "Assigning matrixes with different size"); copy(m_data, other.m_data, m_num_rows * m_num_cols); other.m_num_cols = 0; other.m_num_rows = 0; other.m_data = nullptr; return *this; } template<class Type> size_t Matrix<Type>::getNumRows() const { return m_num_rows; } template<class Type> size_t Matrix<Type>::getNumCols() const { return m_num_cols; } template<class Type> Type & Matrix<Type>::at(size_t row, size_t column) { assert((row < m_num_rows && column < m_num_cols) && "Accessing matrix out of bounds"); return m_data[m_num_cols * row + column]; } template<class Type> Type const& Matrix<Type>::at(size_t row, size_t column) const { assert((row < m_num_rows && column < m_num_cols) && "Accessing matrix out of bounds"); return m_data[m_num_cols * row + column]; } }}
3,923
C++
.h
102
31.578431
94
0.540087
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,409
KiwiTool_Scheduler.hpp
Musicoll_Kiwi/Modules/KiwiTool/KiwiTool_Scheduler.hpp
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once #include <algorithm> namespace kiwi { namespace tool { // ==================================================================================== // // SCHEDULER // // ==================================================================================== // template<class Clock> Scheduler<Clock>::Scheduler(): m_queue(), m_mutex(), m_consumer_id(std::this_thread::get_id()) { } template<class Clock> Scheduler<Clock>::~Scheduler() { } template<class Clock> void Scheduler<Clock>::setThreadAsConsumer() { m_consumer_id = std::this_thread::get_id(); } template<class Clock> bool Scheduler<Clock>::isThisConsumerThread() const { return m_consumer_id == std::this_thread::get_id(); } template<class Clock> void Scheduler<Clock>::schedule(std::shared_ptr<Task> const& task, duration_t delay) { assert(task); m_queue.schedule(task, delay); } template<class Clock> void Scheduler<Clock>::schedule(std::shared_ptr<Task> && task, duration_t delay) { assert(task); m_queue.schedule(std::move(task), delay); } template<class Clock> void Scheduler<Clock>::schedule(std::function<void(void)> && func, duration_t delay) { schedule(std::make_shared<CallBack>(func), delay); } template<class Clock> void Scheduler<Clock>::defer(std::shared_ptr<Task> const& task) { assert(task); if (!isThisConsumerThread()) { schedule(task); } else { task->execute(); } } template<class Clock> void Scheduler<Clock>::defer(std::shared_ptr<Task> && task) { assert(task); if (!isThisConsumerThread()) { schedule(std::move(task)); } else { task->execute(); task.reset(); } } template<class Clock> void Scheduler<Clock>::defer(std::function<void(void)> && func) { if (!isThisConsumerThread()) { schedule(std::move(func)); } else { func(); } } template<class Clock> void Scheduler<Clock>::unschedule(std::shared_ptr<Task> const& task) { assert(task); m_queue.unschedule(task); } template<class Clock> void Scheduler<Clock>::process() { assert(std::this_thread::get_id() == m_consumer_id); std::lock_guard<std::mutex> lock(m_mutex); time_point_t process_time = clock_t::now(); m_queue.process(process_time); } template<class Clock> std::unique_lock<std::mutex> Scheduler<Clock>::lock() const { std::unique_lock<std::mutex> head_lock(m_mutex); return head_lock; } // ==================================================================================== // // QUEUE // // ==================================================================================== // template<class Clock> Scheduler<Clock>::Queue::Queue(): m_events(), m_commands(1024) { } template<class Clock> Scheduler<Clock>::Queue::~Queue() { } template<class Clock> void Scheduler<Clock>::Queue::schedule(std::shared_ptr<Task> const& task, duration_t delay) { assert(task); m_commands.push({task, clock_t::now() + delay }); } template<class Clock> void Scheduler<Clock>::Queue::schedule(std::shared_ptr<Task> && task, duration_t delay) { assert(task); m_commands.push({std::move(task), clock_t::now() + delay}); } template<class Clock> void Scheduler<Clock>::Queue::unschedule(std::shared_ptr<Task> const& task) { m_commands.push({task, clock_t::time_point::max()}); } template<class Clock> void Scheduler<Clock>::Queue::remove(Event const& event) { m_events.erase(std::remove_if(m_events.begin(), m_events.end(), [&event](Event const& e) { return e.m_task == event.m_task; }), m_events.end()); } template<class Clock> void Scheduler<Clock>::Queue::emplace(Event && event) { remove(event); auto event_it = m_events.begin(); while(event_it != m_events.end()) { if (event.m_time < event_it->m_time) { m_events.insert(event_it, std::move(event)); break; } ++event_it; } if (event_it == m_events.end()) { m_events.emplace_back(std::move(event)); } } template<class Clock> void Scheduler<Clock>::Queue::process(time_point_t process_time) { size_t command_size = m_commands.load_size(); for (size_t i = 0; i < command_size; ++i) { Command command; if (m_commands.pop(command)) { Event event(std::move(command.m_task), command.m_time); if (event.m_time != clock_t::time_point::max()) { emplace(std::move(event)); } else { remove(event); } } } m_events.erase(std::remove_if(m_events.begin(), m_events.end(), [&process_time](auto& event) { if (event.m_time <= process_time) { event.execute(); return true; } return false; }), m_events.end()); } // ==================================================================================== // // TASK // // ==================================================================================== // template<class Clock> Scheduler<Clock>::Task::Task() { } template<class Clock> Scheduler<Clock>::Task::~Task() { } // ==================================================================================== // // CALLBACK // // ==================================================================================== // template<class Clock> Scheduler<Clock>::CallBack::CallBack(std::function<void(void)> func): Task(), m_func(func) { } template<class Clock> Scheduler<Clock>::CallBack::~CallBack() { } template<class Clock> void Scheduler<Clock>::CallBack::execute() { m_func(); } // ==================================================================================== // // TIMER // // ==================================================================================== // template<class Clock> class Scheduler<Clock>::Timer::Task final : public Scheduler<Clock>::Task { public: // methods Task(Timer& timer): m_timer(timer) { } ~Task() { } void execute() override { m_timer.callBackInternal(); } private: // members Timer& m_timer; }; template<class Clock> Scheduler<Clock>::Timer::Timer(Scheduler & scheduler): m_scheduler(scheduler), m_task(new Task(*this)), m_period() { } template<class Clock> Scheduler<Clock>::Timer::~Timer() { stopTimer(); } template<class Clock> void Scheduler<Clock>::Timer::startTimer(duration_t period) { stopTimer(); m_period = period; m_scheduler.schedule(m_task, m_period); } template<class Clock> void Scheduler<Clock>::Timer::callBackInternal() { timerCallBack(); m_scheduler.schedule(m_task, m_period); } template<class Clock> void Scheduler<Clock>::Timer::stopTimer() { m_scheduler.unschedule(m_task); } // ==================================================================================== // // EVENT // // ==================================================================================== // template<class Clock> Scheduler<Clock>::Event::Event(std::shared_ptr<Task> && task, time_point_t time): m_task(std::move(task)), m_time(time) { } template<class Clock> Scheduler<Clock>::Event::Event(Event && other): m_task(std::move(other.m_task)), m_time(std::move(other.m_time)) { } template<class Clock> typename Scheduler<Clock>::Event& Scheduler<Clock>::Event::operator=(Event && other) { m_task = std::move(other.m_task); m_time = std::move(other.m_time); return *this; } template<class Clock> Scheduler<Clock>::Event::~Event() { } template<class Clock> void Scheduler<Clock>::Event::execute() { if (m_task){m_task->execute();} } }}
10,628
C++
.h
314
25.251592
102
0.465549
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,410
KiwiTool_Listeners.h
Musicoll_Kiwi/Modules/KiwiTool/KiwiTool_Listeners.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once #include <memory> #include <set> #include <vector> #include <mutex> namespace kiwi { namespace tool { // ================================================================================ // // LISTENERS // // ================================================================================ // //! @brief The listener set is a class that manages a list of listeners. //! @details Manages a list of listeners and allows to retrieve them easily and thread-safely. template <class ListenerClass> class Listeners { public: struct is_valid_listener : std::integral_constant<bool, !std::is_pointer<ListenerClass>::value && !std::is_reference<ListenerClass>::value > {}; using listener_t = typename std::remove_pointer<typename std::remove_reference<ListenerClass>::type>::type; using listener_ref_t = listener_t&; using listener_ptr_t = listener_t*; //! @brief Creates an empty listener set. Listeners() { static_assert(is_valid_listener::value, "Template parameter must not be a pointer or a reference"); } //! @brief Destructor. ~Listeners() noexcept { m_listeners.clear(); } //! @brief Add a listener. //! @details If the listener was allready present in the set, the function does nothing. //! @param listener The new listener to be added. //! @return True if success, otherwise false. bool add(listener_ref_t listener) noexcept { std::lock_guard<std::mutex> guard(m_mutex); bool insert_success = m_listeners.insert(&listener).second; return insert_success; } //! @brief Remove a listener. //! @details If the listener wasn't in the set, the function does nothing. //! @param listener The listener to be removed. //! @return True if success, false otherwise. bool remove(listener_ref_t listener) noexcept { std::lock_guard<std::mutex> guard(m_mutex); bool erase_success = m_listeners.erase(&listener); return erase_success; } //! @brief Returns the number of listeners. size_t size() const noexcept { std::lock_guard<std::mutex> guard(m_mutex); return m_listeners.size(); } //! @brief Returns true if there is no listener. bool empty() const noexcept { std::lock_guard<std::mutex> guard(m_mutex); return m_listeners.empty(); } //! @brief Remove all listeners. void clear() noexcept { std::lock_guard<std::mutex> guard(m_mutex); m_listeners.clear(); } //! @brief Returns true if the set contains a given listener. bool contains(listener_ref_t listener) const noexcept { return (m_listeners.find(&listener) != m_listeners.end()); } //! @brief Get the listeners. std::vector<listener_ptr_t> getListeners() { std::lock_guard<std::mutex> guard(m_mutex); return {m_listeners.begin(), m_listeners.end()}; } //! @brief Retrieve the listeners. std::vector<listener_ptr_t> getListeners() const { std::lock_guard<std::mutex> guard(m_mutex); return {m_listeners.begin(), m_listeners.end()}; } //! @brief Calls a given method for each listener of the set. //! @param fun The listener's method to call. //! @param arguments optional arguments. template<class T, class ...Args> void call(T fun, Args&& ...arguments) const { for(auto* listener : getListeners()) { (listener->*(fun))(arguments...); } } private: std::set<listener_ptr_t> m_listeners; mutable std::mutex m_mutex; }; }}
5,223
C++
.h
115
34.556522
116
0.535976
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,411
KiwiModel_DocumentManager.h
Musicoll_Kiwi/Modules/KiwiModel/KiwiModel_DocumentManager.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once #include <flip/History.h> #include <flip/HistoryStoreMemory.h> namespace kiwi { namespace model { // ================================================================================ // // DOCUMENT MANAGER // // ================================================================================ // class DocumentManager { public: //! @brief Constructor. DocumentManager(flip::DocumentBase& document); //! @brief Destructor. ~DocumentManager(); //! @brief Commit and push. //! @see startCommitGesture, endCommitGesture. static void commit(flip::Type& type, std::string action = std::string()); //! @brief Connect the DocumentManager to a remote server static void connect(flip::Type& type, const std::string host, uint16_t port, uint64_t session_id); //! @brief Pull changes from remote server static void pull(flip::Type& type); //! @brief Starts a commit gesture. //! @details Each call to this function must be followed by a call to endCommitGesture. //! @see endCommitGesture, commitGesture static void startCommitGesture(flip::Type& type); //! @brief Commit a gesture. //! @param label The label of the current gesture. //! @see startCommitGesture, endCommitGesture. static void commitGesture(flip::Type& type, std::string label); //! @brief Ends a commit gesture. //! @details Each call to this function must be preceded by a call to startCommitGesture. //! @see startCommitGesture. static void endCommitGesture(flip::Type& type); //! @brief Returns true if the document is currently commiting a gesture. static bool isInCommitGesture(flip::Type& type); //! @brief Returns true if there is an action to undo. bool canUndo(); //! @brief Returns the label of the last undo action. std::string getUndoLabel(); //! @brief Undo the last action. void undo(); //! @brief Returns true if there is an action to redo. bool canRedo(); //! @brief Returns the label of the next redo action. std::string getRedoLabel(); //! @brief Redo the next action. void redo(); //! @brief Returns the object's pointer or nullptr if not found in document. template<class T> T* get(flip::Ref const& ref) { return m_document.object_ptr<T>(ref); } private: //! @brief Commmits and pushes a transaction void commit(std::string label); //! @brief Pulls transactions stacked by a socket's process void pull(); //! @brief Pushes a trasactions stacked by a socket's process void push(); //! @brief Starts a commit gesture. void startCommitGesture(); //! @brief Commit a gesture. void commitGesture(std::string label); //! @brief Ends a commit gesture. void endCommitGesture(); class Session; private: flip::DocumentBase& m_document; flip::History<flip::HistoryStoreMemory> m_history; std::unique_ptr<Session> m_session = nullptr; private: DocumentManager() = delete; DocumentManager(const DocumentManager& rhs) = delete; DocumentManager(DocumentManager&& rhs) = delete; DocumentManager& operator =(const DocumentManager& rhs) = delete; DocumentManager& operator =(DocumentManager&& rhs) = delete; bool operator ==(DocumentManager const& rhs) const = delete; bool operator !=(DocumentManager const& rhs) const = delete; }; // ================================================================================ // // SESSION // // ================================================================================ // //! @brief The Session is used internally by the DocumentManager to //! handle the gesture commits. //! @details A session manages its own transaction stack, //! and squash each new transaction into a single one. //! @see DocumentManager::startCommitGesture, DocumentManager::commitGesture, DocumentManager::endCommitGesture, DocumentManager::isInCommitGesture class DocumentManager::Session { public: Session(flip::DocumentBase& document); virtual ~Session(); //! @brief Starts a change void start(); //! @brief Commits a change without a transaction label void commit(); //! @brief Commits a change with a transaction label void commit(std::string label); //! @brief Clear history void end(flip::History<flip::HistoryStoreMemory>* master_history = nullptr); //! @brief Reverts all changes void revert(); private: flip::DocumentBase& m_document; flip::History<flip::HistoryStoreMemory> m_history; flip::Transaction m_tx; }; }}
6,437
C++
.h
126
40.484127
151
0.565006
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,412
KiwiModel_Error.h
Musicoll_Kiwi/Modules/KiwiModel/KiwiModel_Error.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once namespace kiwi { namespace model { // ==================================================================================== // // ERROR // // ==================================================================================== // //! @brief A generic exception for engine failures. class Error : public std::runtime_error { public: //! @brief The std::string constructor. explicit Error(std::string const& message) : std::runtime_error(message) {} //! @brief The const char* constructor. explicit Error(const char* message) : std::runtime_error(std::string(message)) {} //! @brief The destructor. virtual inline ~Error() noexcept = default; }; }}
1,797
C++
.h
35
43.971429
95
0.475825
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,413
KiwiModel_Def.h
Musicoll_Kiwi/Modules/KiwiModel/KiwiModel_Def.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once #define KIWI_MODEL_VERSION_STRING "v4.0.3"
943
C++
.h
16
54.75
91
0.561326
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,414
KiwiModel_Point.h
Musicoll_Kiwi/Modules/KiwiModel/KiwiModel_Point.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once #include "flip/Object.h" #include "flip/Float.h" namespace kiwi { namespace model { //! @brief A simple data structure that represent a point with two floating-point numbers. class Point : public flip::Object { public: // methods Point() = default; ~Point() = default; Point(double x, double y); double getX() const; double getY() const; void setX(double x); void setY(double y); void setPosition(double x, double y); public: // internal static void declare(); public: // members flip::Float m_x, m_y; }; }}
1,641
C++
.h
37
35.675676
95
0.564777
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,415
KiwiModel_PatcherUser.h
Musicoll_Kiwi/Modules/KiwiModel/KiwiModel_PatcherUser.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once #include "KiwiModel_Patcher.h" #include "KiwiModel_PatcherView.h" namespace kiwi { namespace model { // ================================================================================ // // PATCHER USER // // ================================================================================ // //! @brief Represents and stores informations about a user of a patcher document. class Patcher::User : public flip::Object { public: // methods //! @brief Constructor. User(); //! @brief Destructor. ~User() = default; //! @brief Add a new View. View& addView(); //! @brief Remove a View. flip::Collection<Patcher::View>::iterator removeView(View const& view); //! @brief Get views. flip::Collection<Patcher::View> const& getViews() const noexcept; //! @brief Get views. flip::Collection<Patcher::View>& getViews() noexcept; //! @brief Get the number of active views. size_t getNumberOfViews() const noexcept; //! @brief Get the User id uint64_t getId() const; public: // internal methods //! @brief flip declare method static void declare(); private: // members flip::Collection<Patcher::View> m_views; friend Patcher; }; } }
2,650
C++
.h
53
37.415094
95
0.48467
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,416
KiwiModel_Factory.h
Musicoll_Kiwi/Modules/KiwiModel/KiwiModel_Factory.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once #include <typeinfo> #include <vector> #include <memory> #include <algorithm> #include <KiwiModel/KiwiModel_ObjectClass.h> #include <KiwiModel/KiwiModel_Object.h> #include <KiwiModel/KiwiModel_DataModel.h> namespace kiwi { namespace model { // ================================================================================ // // OBJECT FACTORY // // ================================================================================ // //! @brief The model Object's factory class Factory { public: // methods //! @brief isValidObject type traits //! @details To be considered as valid an object must: //! - not be abstract. //! - inherit from model::Object. //! - be constructible with flip::Default. //! - be constructible with a string and a vector of atoms. template<typename TModel> struct isValidObject { enum { value = std::is_base_of<model::Object, TModel>::value && !std::is_abstract<TModel>::value && std::is_constructible<TModel, flip::Default &>::value }; }; //! @brief Adds an object model into the Factory. //! @details The function throw if the object has already been added. //! The name you pass in parameter will be used and stored in the DataModel, //! thus if you pass a different name later, this will imply a breaking change in the DataModel. //! @param name The name of the object (must not be empty and not already used by another object or alias name in the Factory). template<class TModel> static void add(std::unique_ptr<ObjectClass> object_class, flip::Class<TModel> & data_model) { static_assert(isValidObject<TModel>::value, "Not a valid Object"); std::string object_name = object_class->getName(); assert(std::string(data_model.name()) == object_class->getModelName()); assert(!object_name.empty() && "Registring object with invalid name"); assert(DataModel::has<TModel>() && "Registering object without declaring its data model"); // check if the name match the name of another object in the factory. if(has(object_name)) { throw std::runtime_error("The \"" + object_name + "\" object is already in the factory"); } // check aliases duplicates std::set<std::string> const& aliases = object_class->getAliases(); auto duplicate_aliases = std::find_if(aliases.begin(), aliases.end(), [](std::string const& alias) { return Factory::has(alias); }); if (duplicate_aliases != aliases.end()) { throw std::runtime_error(object_name + "Adding twice the same alias"); } ObjectClass::mold_maker_t mold_maker = [](model::Object const& object, flip::Mold& mold) { mold.make(static_cast<TModel const&>(object), false); }; object_class->setMoldMaker(mold_maker); ObjectClass::mold_caster_t mold_caster = [](flip::Mold const& mold) { flip::Default d; auto object_uptr = std::make_unique<TModel>(d); mold.cast<TModel>(static_cast<TModel&>(*(object_uptr.get()))); return object_uptr; }; object_class->setMoldCaster(mold_caster); object_class->setTypeId(typeid(TModel).hash_code()); m_object_classes.emplace_back(std::move(object_class)); } //! @brief Creates a new Object with a name and arguments. //! @details This function will throw if the object name does not exist. //! @param name The name of the Object. //! @param args A list of arguments as a vector of Atom. //! @return A ptr to a model::Object. static std::unique_ptr<model::Object> create(std::vector<tool::Atom> const& args); //! @brief Creates a new Object from a flip::Mold. //! @details This function will throw if the object name does not exist. //! @param name The name of the Object to create. //! @param mold The flip::Mold from which to create the object. //! @return A ptr to a model::Object. static std::unique_ptr<model::Object> create(std::string const& name, flip::Mold const& mold); //! @brief Make a mold of this object. //! @details This function will throw if the object does not exist. //! @param object The Object to copy. //! @param mold The flip::Mold from which to create the object. //! @return A ptr to a model::Object. static void copy(model::Object const& object, flip::Mold& mold); //! @brief Returns a ptr to an object class thas has this name or alias name. //! @details This method returns nullptr if the name is not found. //! @param name The name or an alias name of the class. //! @param ignore_aliases Default to false, pass true to ignore aliases. //! @return A ptr to an ObjectClassBase. static ObjectClass const* getClassByName(std::string const& name, const bool ignore_aliases = false); //! @brief Returns the object's class filtering by type id's hash code. static ObjectClass const* getClassByTypeId(size_t type_id); //! @brief Returns true if a given string match a registered object class name. //! @param name The name of the object class to find. //! @return true if the object class has been added, otherwise false. static bool has(std::string const& name); //! @brief Gets the names of the objects that has been added to the Factory. //! @param ignore_aliases Default to false, you may pass true to exclude them. //! @param ignore_internals Default to true, you may pass false to include them. //! @return A vector of object class names. static std::vector<std::string> getNames(const bool ignore_aliases = false, const bool ignore_internals = true); //! @internal Returns the corresponding model name. Since flip only ascii-7 characters //! can be used in the datamodel, we define a bijection between name and model name. static std::string toModelName(std::string const& name); //! @internal Returns the corresponding model name. Since flip only ascii-7 characters //! can be used in the datamodel, we define a bijection between name and model name. static std::string toKiwiName(std::string const& name); private: // members static std::vector<std::unique_ptr<ObjectClass>> m_object_classes; private: // deleted methods Factory() = delete; ~Factory() = delete; }; } }
9,143
C++
.h
147
44.632653
140
0.536608
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,417
KiwiModel_PatcherValidator.h
Musicoll_Kiwi/Modules/KiwiModel/KiwiModel_PatcherValidator.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once #include "flip/DocumentValidator.h" #include "KiwiModel_PatcherUser.h" namespace kiwi { namespace model { // ================================================================================ // // PATCHERVALIDATOR // // ================================================================================ // class PatcherValidator : public flip::DocumentValidator<Patcher> { public: // methods PatcherValidator() = default; ~PatcherValidator() = default; // @brief Validate the model before a transaction can be executed. virtual void validate (Patcher& patcher) override; private: // methods //! @brief Carry out checks once a object is removed. void objectRemoved(Object const& object, Patcher const& patcher) const; //! @brief Carry out checks once a link is created. void linkAdded(Link const& link) const; private: // deleted methods PatcherValidator(PatcherValidator const& other) = delete; PatcherValidator(PatcherValidator && other) = delete; PatcherValidator& operator=(PatcherValidator const& other) = delete; PatcherValidator& operator=(PatcherValidator && other) = delete; }; } }
2,405
C++
.h
44
44.454545
95
0.526997
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,418
KiwiModel_Link.h
Musicoll_Kiwi/Modules/KiwiModel/KiwiModel_Link.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once #include "KiwiModel_Object.h" namespace kiwi { namespace model { // ================================================================================ // // LINK // // ================================================================================ // //! @brief The Link is used to create a connection between two objects. //! @details The Link holds a reference to the sender Object, to the receiver Object //! and inlet and outlet indexes. class Link : public flip::Object { public: // methods //! @brief Constructs a Link. //! @details Constructs a Link with given origin and destination Object pointers //! and IO indexes. //! @param from The sender Object. //! @param outlet The sender outlet index. //! @param to The receiver Object. //! @param inlet The receiver inlet index. Link(model::Object const& from, const size_t outlet, model::Object const& to, const size_t inlet); //! @brief Destructor. ~Link() = default; //! @brief Gets the Object that sends messages. model::Object const& getSenderObject() const; //! @brief Gets the Object that receives messages. model::Object const& getReceiverObject() const; //! @brief Checks if the sender object is still in document. bool isSenderValid() const; //! @brief Checks if the sender object is still in document. bool isReceiverValid() const; //! @brief Returns the sender outlet index. size_t getSenderIndex() const; //! @brief Returns the receiver inlet index. size_t getReceiverIndex() const; //! Returns true if it is a signal link. bool isSignal() const; public: // internal methods //! @internal flip Default constructor Link(flip::Default&) {} //! @internal flip static declare method static void declare(); private: // members flip::ObjectRef<model::Object> m_sender; flip::ObjectRef<model::Object> m_receiver; flip::Int m_index_outlet; flip::Int m_index_inlet; private: // deleted methods Link(Link const&) = delete; Link(Link&&) = delete; Link& operator=(Link const&) = delete; Link& operator=(Link&&) = delete; }; } }
3,872
C++
.h
71
40.802817
111
0.507793
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,419
KiwiModel_Patcher.h
Musicoll_Kiwi/Modules/KiwiModel/KiwiModel_Patcher.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once #include "KiwiModel_Link.h" namespace kiwi { namespace model { // ================================================================================ // // PATCHER // // ================================================================================ // //! @brief The Patcher manages a set of Object and Link class Patcher : public flip::Object { public: // methods class User; class View; using Objects = flip::Array<model::Object>; using Links = flip::Array<model::Link>; using Users = flip::Collection<User>; //! @brief Default constructor. Patcher(); //! @brief Destructor. ~Patcher(); //! @brief Adds an object to the patcher model. //! @param The object to add in the text. //! @return A reference to the object added. model::Object& addObject(std::unique_ptr<model::Object> && object); //! @brief Replaces an object by another one. //! @details This function will rewire the new object. //! @return A reference to the newly added object. model::Object& replaceObject(model::Object const& old_object, std::unique_ptr<model::Object> && object); //! @brief create an Object from a flip::Mold. model::Object& addObject(std::string const& name, flip::Mold const& mold); //! @brief Constructs and add a Link to the Patcher. //! @details Constructs a Link with given origin and destination Object //! and IO indexes then adds it in the Patcher. //! @param from The Object that sends messages. //! @param outlet The sending outlet index. //! @param to The Object that receives messages. //! @param inlet The receiving inlet index. //! @return A link or nullptr if the link can't be created model::Link* addLink(model::Object const& from, const size_t outlet, model::Object const& to, const size_t inlet); //! @brief Removes an object from the Patcher. //! @details This will also remove all links connected to this object. //! @param object The Object to remove. void removeObject(model::Object const& object, Patcher::View* view = nullptr); //! @brief Removes a link from the Patcher. //! @param link The Link to remove. void removeLink(model::Link const& link, Patcher::View* view = nullptr); //! @brief Returns true if an Object has been added, removed or changed. bool objectsChanged() const noexcept; //! @brief Returns true if a Link has been added, removed or changed. bool linksChanged() const noexcept; //! @brief Returns true if a User has been added, removed or changed. bool usersChanged() const noexcept; //! @brief Gets the objects. Objects const& getObjects() const noexcept; //! @brief Gets the objects. Objects& getObjects() noexcept; //! @brief Gets the links. Links const& getLinks() const noexcept; //! @brief Gets the links. Links& getLinks() noexcept; //! @brief Gets the users. Users const& getUsers() const noexcept; //! @brief Gets the users. Users& getUsers() noexcept; //! @brief Returns true if current user is already in added to the document. bool hasSelfUser() const; //! @brief Returns the current User. //! @details The function will look for a User that match //! the current user id of the document, if it's not found, the User will be created, //! therefore, do not use this method while observing the model. //! @return The current User. User& useSelfUser(); public: // signals enum { Signal_USER_CONNECT = 0, Signal_USER_DISCONNECT, Signal_GET_CONNECTED_USERS, Signal_RECEIVE_CONNECTED_USERS, Signal_STACK_OVERFLOW, Signal_STACK_OVERFLOW_CLEAR, }; // from server to client flip::Signal<uint64_t> signal_user_connect; // from server to client flip::Signal<uint64_t> signal_user_disconnect; // from client to server flip::Signal<> signal_get_connected_users; // from server to client flip::Signal<std::vector<uint64_t>> signal_receive_connected_users; // used by the engine when a stack-overflow is detected flip::Signal<std::vector<flip::Ref>> signal_stack_overflow; // used by the view to clear stack-overflow flip::Signal<> signal_stack_overflow_clear; public: // internal methods //! @internal flip static declare method static void declare(); private: // methods Objects::const_iterator findObject(model::Object const& object) const; Objects::iterator findObject(model::Object const& object); Links::const_iterator findLink(model::Link const& object) const; Links::iterator findLink(model::Link const& object); //! @internal Returns true if the link can be created. bool canConnect(model::Object const& from, const size_t outlet, model::Object const& to, const size_t inlet) const; private: // members Objects m_objects; Links m_links; Users m_users; private: // deleted methods Patcher(Patcher const&) = delete; Patcher(Patcher&&) = delete; Patcher& operator=(Patcher const&) = delete; Patcher& operator=(Patcher&&) = delete; }; } }
7,866
C++
.h
136
40.941176
117
0.530358
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,420
KiwiModel_PatcherView.h
Musicoll_Kiwi/Modules/KiwiModel/KiwiModel_PatcherView.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once #include "KiwiModel_PatcherUser.h" #include "KiwiModel_Point.h" #include "KiwiModel_Bounds.h" namespace kiwi { namespace model { // ================================================================================ // // PATCHER VIEW // // ================================================================================ // //! @brief The Patcher::View class holds the informations about a view of a Patcher. class Patcher::View : public flip::Object { public: // methods //! @brief Constructor. View(); //! @brief Destructor. ~View(); //! @brief Return the parent Patcher object Patcher& getPatcher(); //! @brief Set the lock status. void setLock(bool locked); //! @brief Returns true if the view is locked. bool getLock() const noexcept; //! @brief Returns true if the lock status changed. bool lockChanged() const noexcept; //! @brief Set zoom factor. void setZoomFactor(double zoom_factor); //! @brief Returns the current zoom factor. double getZoomFactor() const noexcept; //! @brief Returns true if the zoom factor changed. bool zoomFactorChanged() const noexcept; // ================================================================================ // // SELECTION // // ================================================================================ // //! @brief Return the selected Objects. std::vector<model::Object*> getSelectedObjects(); //! @brief Return the selected Links. std::vector<model::Link*> getSelectedLinks(); //! @brief Return true if the given Object is selected in this view. bool isSelected(model::Object const& object) const; //! @brief Return true if the given Link is selected in this view. bool isSelected(model::Link const& link) const; //! @brief Returns true if selection has changed. bool selectionChanged() const; //! @brief Select an Object. void selectObject(model::Object& object); //! @brief Select a Link. void selectLink(model::Link& object); //! @brief Unselect an Object. void unselectObject(model::Object& object); //! @brief Unselect a Link. void unselectLink(model::Link& object); //! @brief Unselect all objects and links void unselectAll(); //! @brief Select all objects and links void selectAll(); //! @brief Returns the bounds of the view relative to the screen. Bounds const& getScreenBounds() const; //! @brief Sets the bounds of the view relative to the screen. void setScreenBounds(double x, double y, double width, double height); //! @brief Returns the view position. Point const& getViewPosition() const; //! @brief Sets the view position. void setViewPosition(double x, double y); public: // internal methods //! @internal flip Default constructor. View(flip::Default&) {}; //! @internal flip declare method static void declare(); private: // nested classes // ================================================================================ // // PATCHER VIEW OBJECT // // ================================================================================ // //! @internal A model::Object reference wrapper. struct Object : public flip::Object { public: // methods Object() = default; ~Object() = default; Object(model::Object& object); model::Object* get() const; public: // internal methods //! @internal flip declare method static void declare(); private: // members flip::ObjectRef<model::Object> m_ref; }; // ================================================================================ // // PATCHER VIEW LINK // // ================================================================================ // //! @internal A model::Link reference wrapper. struct Link : public flip::Object { public: // methods Link() = default; ~Link() = default; Link(model::Link& link); model::Link* get() const; public: // internal methods //! @internal flip declare method static void declare(); private: // members flip::ObjectRef<model::Link> m_ref; }; private: // members flip::Collection<View::Object> m_selected_objects; flip::Collection<View::Link> m_selected_links; flip::Bool m_is_locked; flip::Float m_zoom_factor; Bounds m_screen_bounds; Point m_view_position; }; } }
7,368
C++
.h
130
39.246154
99
0.444275
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,421
KiwiModel_Bounds.h
Musicoll_Kiwi/Modules/KiwiModel/KiwiModel_Bounds.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once #include "flip/Object.h" #include "flip/Float.h" namespace kiwi { namespace model { //! @brief A simple data structure that represent a bounds with 4 floating-point numbers. class Bounds : public flip::Object { public: // methods Bounds() = default; ~Bounds() = default; Bounds(double x, double y, double width, double height); double getX() const; double getY() const; double getWidth() const; double getHeight() const; void setX(double x); void setY(double y); void setWidth(double width); void setHeight(double height); void setPosition(double x, double y); void setSize(double width, double height); public: // internal static void declare(); public: // members flip::Float m_x, m_y, m_width, m_height; }; }}
1,891
C++
.h
42
36.190476
94
0.577302
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,422
KiwiModel_ObjectClass.h
Musicoll_Kiwi/Modules/KiwiModel/KiwiModel_ObjectClass.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once #include <functional> #include <set> #include <string> #include <flip/Class.h> #include <flip/Mold.h> #include <KiwiTool/KiwiTool_Parameter.h> #include <KiwiTool/KiwiTool_Atom.h> namespace kiwi { namespace model { class Object; class Factory; // ================================================================================ // // PARAMETER CLASS // // ================================================================================ // //! @brief This is a parameter static informations. //! @details Attributes and Parameters share the same static representation. class ParameterClass { public: // classes enum class Type { Attribute, // Attributes are saved/collaborative but are not invariant. Parameter // Parameters are not collaborative. }; public: // methods //! @brief Constructor. ParameterClass(tool::Parameter::Type type); //! @brief Destructor. ~ParameterClass(); //! @brief Sets the attributes type. Only used by factory. ParameterClass::Type getType() const; //! @brief Returns the parameter's data type. tool::Parameter::Type getDataType() const; private: // methods //! @brief Sets the attributes type. Only used by factory. void setType(Type param_type); private: // members Type m_type; tool::Parameter::Type m_data_type; friend class ObjectClass; private: // deleted methods ParameterClass() = delete; ParameterClass(ParameterClass const& other) = delete; ParameterClass(ParameterClass && other) = delete; ParameterClass& operator=(ParameterClass const& other) = delete; ParameterClass& operator=(ParameterClass && other) = delete; }; // ================================================================================ // // OBJECTC LASS // // ================================================================================ // //! @brief The static representation of an object. class ObjectClass { public: // classes. //! @brief The construction method. using ctor_t = std::function<std::unique_ptr<model::Object>(std::vector<tool::Atom> const&)>; //! @brief A list of flags that defines the object's behavior. enum class Flag { Internal, //! Internal objects do not appears in object list. DefinedSize //! If the object has a predefined size. }; private: // classes //! @brief The object's copy prototype. using mold_maker_t = std::function<void(model::Object const&, flip::Mold&)>; //! @brief The object paste prototype. using mold_caster_t = std::function<std::unique_ptr<model::Object>(flip::Mold const&)>; public:// methods //! @brief The ObjectClass constructor. //! @details Used in the object declaration. ObjectClass(std::string const& name, ctor_t ctor); //! @brief Destructor. ~ObjectClass(); //! @brief Retrieves the object's class name. std::string const& getName() const; //! @brief Retrieves object's data model name. std::string const& getModelName() const; //! @brief Returns true if this object class has aliases. bool hasAlias() const noexcept; //! @brief Returns a set of aliases for this object. std::set<std::string> const& getAliases() const noexcept; //! @brief Returns true if this class has this alias name. bool hasAlias(std::string const& alias) const noexcept; //! @brief Adds a creator name alias to the class. void addAlias(std::string const& alias); //! @brief Adds an attribute to the class definition. void addAttribute(std::string const& name, std::unique_ptr<ParameterClass> param_class); //! @brief Returns true if attributes exists. bool hasAttribute(std::string const& name) const; //! @brief Returns an attributes static definition. //! @details Throws if no attributes refered by name. ParameterClass const& getAttribute(std::string const& name) const; //! @brief Adds a parameter to the class definition. void addParameter(std::string name, std::unique_ptr<ParameterClass> param_class); //! @brief Returns true if parameter exists. bool hasParameter(std::string const& name) const; //! @brief Returns a parameter's static definition. //! @details Throws if no parameter refered by name. ParameterClass const& getParameter(std::string const& name) const; //! @brief Gets the list of parameters static definition. std::map<std::string, std::unique_ptr<ParameterClass>> const& getParameters() const; //! @brief Adds the flag to object static definition. void setFlag(Flag const& flag); //! @brief Checks if the flag is set. bool hasFlag(Flag const& flag) const; private: // methods //! @brief Sets the mold maker function. void setMoldMaker(mold_maker_t maker); // @brief Sets the mold caster function. void setMoldCaster(mold_caster_t caster); //! @brief Sets the type_id's hash code of the class. Used by factory. void setTypeId(size_t); //! @brief Creates and returns a new Object with a vector of Atom as parameter. //! @param args A vector of Atom. //! @return A new model::Object. std::unique_ptr<model::Object> create(std::vector<tool::Atom> const& args) const; //! @brief Copy the content an object instance into a flip::Mold. //! @param object The object instance. //! @param mold The The flip::Mold where to copy object instance data. void moldMake(model::Object const& object, flip::Mold& mold) const; //! @brief Creates and returns a new Object from a flip::Mold. //! @param mold The The flip::Mold from which to retrieve object instance data. //! @return A new model::Object. std::unique_ptr<model::Object> moldCast(flip::Mold const& mold) const; private: // members std::string m_name; std::string m_model_name; std::set<std::string> m_aliases; std::map<std::string, std::unique_ptr<ParameterClass>> m_params; ctor_t m_ctor; std::set<Flag> m_flags; mold_maker_t m_mold_maker; mold_caster_t m_mold_caster; size_t m_type_id; friend class Factory; private: // deleted methods. ObjectClass() = delete; ObjectClass(ObjectClass const& other) = delete; ObjectClass(ObjectClass && other) = delete; ObjectClass& operator=(ObjectClass const& other) = delete; ObjectClass& operator=(ObjectClass && other) = delete; }; }}
8,935
C++
.h
157
45.159236
102
0.557
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,423
KiwiModel_Object.h
Musicoll_Kiwi/Modules/KiwiModel/KiwiModel_Object.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once //! @todo Clean flip headers below, use only needed one in this file // ---- Flip headers ---- // #include "flip/Bool.h" #include "flip/Int.h" #include "flip/Float.h" #include "flip/String.h" #include "flip/Array.h" #include "flip/Collection.h" #include "flip/Object.h" #include "flip/ObjectRef.h" #include "flip/Enum.h" #include "flip/Signal.h" #include <KiwiTool/KiwiTool_Atom.h> #include <KiwiTool/KiwiTool_Parameter.h> #include <KiwiTool/KiwiTool_Listeners.h> #include <KiwiModel/KiwiModel_ObjectClass.h> #include <KiwiModel/KiwiModel_Error.h> #include <mutex> #include <algorithm> #include <exception> #include <set> #include <map> namespace kiwi { namespace model { class Factory; // ================================================================================ // // INLET/OUTLET // // ================================================================================ // //! @brief Class that represent a type of pin. //! @details This class is a flip object wrapper on an enum. It's needed for putting the type //! into a flip::Array. class PinType : public flip::Object { public: // classes enum class IType { Control, Signal }; public: // methods // @brief Constructor of type. PinType(IType type); //! @brief Comprison operator. bool operator<(PinType const& other) const; //! @brief Equality comparator. Consistent with comparison operator. bool operator==(PinType const& other) const; public: // internal methods //! @internal Flip default constructor. PinType(flip::Default&); //! @internal Flip declarator. static void declare(); private: // methods //! @brief Returns the type or the previous type if the Type is deleted. //! @details During document changed phase the type can be tagged as removed. IType getType() const; private: flip::Enum<IType> m_type; }; //! @brief Class that represent an inlet able to have multiple types. class Inlet : public flip::Object { public: //! @brief Initializes the Inlet with multiple types. Inlet(std::set<PinType> types); //! @brief The destructor. ~Inlet() = default; //! @brief Checks if the inlet is compatible with type. bool hasType(PinType type) const; public: // internal methods //! @internal Flip default constructor. Inlet(flip::Default&); //! @internal Flip declarator. static void declare(); private: flip::Array<PinType> m_types; }; //! @brief Class that represent a certain outlet having only one type. class Outlet : public flip::Object { public: //! @brief Initializes the Inlet with one type. Outlet(PinType type); //! @brief The destructor. ~Outlet() = default; // @brief Returns the type of the outlet. PinType const& getType() const; public: // internal methods //! @internal Flip default constructor. Outlet(flip::Default&); //! @internal Flip declarator. static void declare(); private: PinType m_type; }; // ================================================================================ // // OBJECT // // ================================================================================ // //! @brief The Object is a base class for kiwi objects. //! @details objects can be instantiated in a Patcher. class Object : public flip::Object { public: // classes using SignalKey = uint32_t; class Listener { public: //! @brief Destructor virtual ~Listener() = default; //! @brief Called when a parameter has changed; virtual void modelParameterChanged(std::string const& name, tool::Parameter const& param) = 0; //! @brief Called when an attribute has changed. virtual void modelAttributeChanged(std::string const& name, tool::Parameter const& param) = 0; }; //! @brief an error that object can throw to notify a problem. //! @todo Check if object's id shall be added to error. class Error : public model::Error { public: // methods //! @brief Constructor. Error(std::string const& message):model::Error(message) {} //! @brief Destructor. ~Error() = default; }; public: // methods //! @brief Constructor. Object(); //! @brief Destructor. virtual ~Object() = default; //! @brief Returns the arguments of the object. std::vector<tool::Atom> const& getArguments() const; //! @brief Returns a list of changed attributes. //! @details Use this function in the observation to check which values shall //! be updated. std::set<std::string> getChangedAttributes() const; //! @brief Retrieve one of the object's attributes. tool::Parameter const& getAttribute(std::string const& name) const; //! @brief Sets one of the object's attribute. void setAttribute(std::string const& name, tool::Parameter const& param); //! @brief Returns one of the object's parameters. tool::Parameter const& getParameter(std::string const& name) const; //! @brief Sets one of the object's parameter. void setParameter(std::string const& name, tool::Parameter const& param); //! @brief Writes the parameter into data model. //! @details If the parameter is saved this function will be called at every attempt to //! modify the parameter. Never called for non saved parameters. virtual void writeAttribute(std::string const& name, tool::Parameter const& paramter); //! @brief Reads the model to initialize a parameter. //! @details Saved parameters may infos from the data model. virtual void readAttribute(std::string const& name, tool::Parameter & parameter) const; //! @brief Checks the data model to see if a parameter has changed. //! @details Only called for saved parameters. Default returns false. virtual bool attributeChanged(std::string const& name) const; //! @brief Adds a listener of object's parameters. void addListener(Listener& listener) const; //! @brief Removes listenere from list. void removeListener(Listener& listener) const; //! @brief Returns the name of the Object. std::string getName() const; //! @brief Returns the object's static definition. ObjectClass const& getClass() const; //! @brief Returns the text of the Object. std::string getText() const; //! @brief Returns the inlets of the Object. flip::Array<Inlet> const& getInlets() const; //! @brief Returns the inlets at index Inlet const& getInlet(size_t index) const; //! @brief Returns the number of inlets. size_t getNumberOfInlets() const; //! @brief Returns true if the inlets changed. bool inletsChanged() const noexcept; //! @brief Returns the number of outlets. flip::Array<Outlet> const& getOutlets() const; //! @brief Returns the outlets at corresponding index. Outlet const& getOutlet(size_t index) const; //! @brief Returns the number of outlets. size_t getNumberOfOutlets() const; //! @brief Returns true if the outlets changed. bool outletsChanged() const noexcept; //! @brief Sets the x/y graphical position of the object. void setPosition(double x, double y); //! @brief Returns true if the object's position changed. bool positionChanged() const noexcept; //! @brief Returns true if the object's size changed. bool sizeChanged() const noexcept; //! @brief Returns true if the position or the size of the object changed. bool boundsChanged() const noexcept; //! @brief Returns the x position. double getX() const noexcept; //! @brief Returns the y position. double getY() const noexcept; //! @brief Sets the width of the object. void setWidth(double new_width); //! @brief Sets the height of the object. void setHeight(double new_height); //! @brief Returns the object's width. double getWidth() const noexcept; //! @brief Returns the object's height. double getHeight() const noexcept; //! @brief Returns inlet or outlet description. virtual std::string getIODescription(bool is_inlet, size_t index) const; //! @brief Checks if the object has this flag set. bool hasFlag(ObjectClass::Flag flag) const; //! @brief Returns the object's signal referenced by this key. //! @details Throws an exception if no signal is referenced for key. template <class... Args> auto& getSignal(SignalKey key) const { flip::SignalBase& signal_base = *m_signals.at(key); return dynamic_cast<flip::Signal<Args...>&>(signal_base); } protected: //! @brief Adds a signal having singal key. template <class... Args> void addSignal(SignalKey key, model::Object& object) { m_signals.emplace(key, std::make_unique<flip::Signal<Args...>>(key, object)); } //! @brief Clear and replace all the object's inlets. void setInlets(flip::Array<Inlet> const& inlets); //! @brief Clear and replace all the object's outlets. void setOutlets(flip::Array<Outlet> const& outlets); //! @brief Adds an inlet at end of current inlet list. void pushInlet(std::set<PinType> type); //! @brief Adds an outlet at end of current outlet list. void pushOutlet(PinType type); public: // internal methods //! @internal flip Default constructor Object(flip::Default&); //! @internal flip static declare method static void declare(); private: // members flip::String m_text; flip::Array<Inlet> m_inlets; flip::Array<Outlet> m_outlets; flip::Float m_position_x; flip::Float m_position_y; flip::Float m_width; flip::Float m_height; mutable std::map<std::string, tool::Parameter> m_attributes; mutable std::map<std::string, tool::Parameter> m_parameters; mutable std::unique_ptr<std::vector<tool::Atom>> m_args = nullptr; std::map<SignalKey, std::unique_ptr<flip::SignalBase>> m_signals; mutable tool::Listeners<Listener> m_listeners; friend class Factory; private: // deleted methods Object(Object const&) = delete; Object(model::Object&&) = delete; model::Object& operator=(model::Object const&) = delete; model::Object& operator=(model::Object&&) = delete; }; } }
14,844
C++
.h
269
38.717472
112
0.534791
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,424
KiwiModel_DataModel.h
Musicoll_Kiwi/Modules/KiwiModel/KiwiModel_DataModel.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once #include <functional> #include <flip/DataModel.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Objects.h> namespace kiwi { namespace model { //! @brief The Patcher data model. class DataModel : public flip::DataModel<DataModel> { public: // methods //! @brief Declare objects. static void declareObjects(); //! @brief Initializes the model. //! @details By default will declare all objects. //! Can be overriden to declare custom objects or only a few objects. static void init(std::function<void(void)> declare_object = &DataModel::declareObjects); public: // members static bool initialised; }; } }
1,731
C++
.h
37
38.27027
101
0.577019
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,425
KiwiModel_Converter.h
Musicoll_Kiwi/Modules/KiwiModel/KiwiModel_Converters/KiwiModel_Converter.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once #include <KiwiModel/KiwiModel_Converters/KiwiModel_ConverterBase.h> namespace kiwi { namespace model { // ================================================================================ // // KIWI CONVERTER // // ================================================================================ // //! @brief Converts a document's backend representation to meet current version representation. class Converter { public: // methods //! @brief Returns the current version of the converter. static std::string const& getLatestVersion(); //! @brief Returns true if a given version can be converted from. static bool canConvertToLatestFrom(std::string const& version); //! @brief Tries converting current data model version. //! @details Returns true if the conversion was successful, false otherwise. Call this function //! after reading from data provider. static bool process(flip::BackEndIR& backend); private: // methods Converter(); ~Converter(); static Converter& use(); using converters_t = std::vector<std::unique_ptr<ConverterBase>>; converters_t& converters(); template<class T> bool addConverter(); private: // variables converters_t m_converters; }; }}
2,368
C++
.h
44
46.181818
103
0.557162
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,426
KiwiModel_ConverterBase.h
Musicoll_Kiwi/Modules/KiwiModel/KiwiModel_Converters/KiwiModel_ConverterBase.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once #include <flip/BackEndIR.h> namespace kiwi { namespace model { // ================================================================================ // // CONVERTER // // ================================================================================ // struct ConverterBase { ConverterBase(std::string const& from_version, std::string const& to_version) : v_from(from_version) , v_to(to_version) {} virtual ~ConverterBase() = default; bool process(flip::BackEndIR& backend) { if(backend.version == v_from) { if(operator()(backend)) { backend.complete_conversion(v_to); return true; } } return false; } const std::string v_from; const std::string v_to; protected: virtual bool operator () (flip::BackEndIR& backend) const = 0; }; }}
2,027
C++
.h
46
34.913043
90
0.462758
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,427
KiwiModel_Less.h
Musicoll_Kiwi/Modules/KiwiModel/KiwiModel_Objects/KiwiModel_Less.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once #include <KiwiModel/KiwiModel_Object.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Operator.h> namespace kiwi { namespace model { // ================================================================================ // // OBJECT LESS // // ================================================================================ // class Less : public Operator { public: Less(flip::Default& d) : Operator(d) {} Less(std::vector<tool::Atom> const& args); static void declare(); static std::unique_ptr<Object> create(std::vector<tool::Atom> const& args); }; }}
1,657
C++
.h
30
48.066667
91
0.486731
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,428
KiwiModel_DivideTilde.h
Musicoll_Kiwi/Modules/KiwiModel/KiwiModel_Objects/KiwiModel_DivideTilde.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once #include <KiwiModel/KiwiModel_Objects/KiwiModel_OperatorTilde.h> namespace kiwi { namespace model { // ================================================================================ // // OBJECT /~ // // ================================================================================ // class DivideTilde : public OperatorTilde { public: static void declare(); static std::unique_ptr<Object> create(std::vector<tool::Atom> const& args); DivideTilde(flip::Default& d): OperatorTilde(d){}; DivideTilde(std::vector<tool::Atom> const& args); }; }}
1,651
C++
.h
29
49.586207
91
0.488312
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,429
KiwiModel_DelaySimpleTilde.h
Musicoll_Kiwi/Modules/KiwiModel/KiwiModel_Objects/KiwiModel_DelaySimpleTilde.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once #include <KiwiModel/KiwiModel_Object.h> namespace kiwi { namespace model { // ================================================================================ // // OBJECT DELAYSIMPLETILDE~ // // ================================================================================ // class DelaySimpleTilde : public model::Object { public: static void declare(); static std::unique_ptr<Object> create(std::vector<tool::Atom> const& args); DelaySimpleTilde(flip::Default& d): model::Object(d){}; DelaySimpleTilde(std::vector<tool::Atom> const& args); std::string getIODescription(bool is_inlet, size_t index) const override; }; }}
1,802
C++
.h
30
50.033333
95
0.490964
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,430
KiwiModel_SigTilde.h
Musicoll_Kiwi/Modules/KiwiModel/KiwiModel_Objects/KiwiModel_SigTilde.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once #include <KiwiModel/KiwiModel_Object.h> namespace kiwi { namespace model { // ================================================================================ // // OBJECT SIG~ // // ================================================================================ // class SigTilde : public model::Object { public: static void declare(); static std::unique_ptr<Object> create(std::vector<tool::Atom> const& args); SigTilde(flip::Default& d): model::Object(d){}; SigTilde(std::vector<tool::Atom> const& args); std::string getIODescription(bool is_inlet, size_t index) const override; }; }}
1,710
C++
.h
30
49.233333
91
0.489924
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,431
KiwiModel_OSCReceive.h
Musicoll_Kiwi/Modules/KiwiModel/KiwiModel_Objects/KiwiModel_OSCReceive.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once #include <KiwiModel/KiwiModel_Object.h> namespace kiwi { namespace model { // ================================================================================ // // OSC.receive // // ================================================================================ // class OSCReceive : public model::Object { public: //! @brief flip Default Constructor. OSCReceive(flip::Default& d) : model::Object(d) {} //! @brief Constructor. OSCReceive(std::vector<tool::Atom> const& args); std::string getIODescription(bool is_inlet, size_t index) const override; //! @brief Declaration method. static void declare(); //! @brief The object's creation method. static std::unique_ptr<Object> create(std::vector<tool::Atom> const& args); }; }}
1,886
C++
.h
34
47.441176
91
0.499432
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,432
KiwiModel_DacTilde.h
Musicoll_Kiwi/Modules/KiwiModel/KiwiModel_Objects/KiwiModel_DacTilde.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once #include <KiwiModel/KiwiModel_Object.h> namespace kiwi { namespace model { // ================================================================================ // // OBJECT DAC~ // // ================================================================================ // //! @todo Check better way to get routes. class DacTilde : public model::Object { public: static void declare(); static std::unique_ptr<Object> create(std::vector<tool::Atom> const& arsg); DacTilde(std::vector<tool::Atom> const& args); DacTilde(flip::Default& d): model::Object(d){} std::vector<size_t> parseArgsAsChannelRoutes(std::vector<tool::Atom> const& args) const; std::string getIODescription(bool is_inlet, size_t index) const override; }; }}
1,864
C++
.h
32
50.15625
97
0.506358
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,433
KiwiModel_Bang.h
Musicoll_Kiwi/Modules/KiwiModel/KiwiModel_Objects/KiwiModel_Bang.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once #include <KiwiModel/KiwiModel_Object.h> namespace kiwi { namespace model { // ================================================================================ // // OBJECT BANG // // ================================================================================ // class Bang : public model::Object { public: // enum enum Signal : SignalKey { TriggerBang, FlashBang }; public: // methods static void declare(); static std::unique_ptr<Object> create(std::vector<tool::Atom> const& args); Bang(flip::Default& d); Bang(std::vector<tool::Atom> const& args); std::string getIODescription(bool is_inlet, size_t index) const override; }; }}
1,834
C++
.h
36
42.166667
91
0.48102
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,434
KiwiModel_Receive.h
Musicoll_Kiwi/Modules/KiwiModel/KiwiModel_Objects/KiwiModel_Receive.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once #include <KiwiModel/KiwiModel_Object.h> namespace kiwi { namespace model { // ================================================================================ // // OBJECT RECEIVE // // ================================================================================ // class Receive : public model::Object { public: // methods Receive(flip::Default& d) : model::Object(d) {} Receive(std::vector<tool::Atom> const& args); std::string getIODescription(bool is_inlet, size_t index) const override; static void declare(); static std::unique_ptr<Object> create(std::vector<tool::Atom> const& args); }; }}
1,723
C++
.h
30
49.533333
91
0.492173
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,435
KiwiModel_Clip.h
Musicoll_Kiwi/Modules/KiwiModel/KiwiModel_Objects/KiwiModel_Clip.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once #include <KiwiModel/KiwiModel_Object.h> namespace kiwi { namespace model { // ================================================================================ // // CLIP // // ================================================================================ // class Clip : public Object { public: static void declare(); static std::unique_ptr<Object> create(std::vector<tool::Atom> const& args); Clip(flip::Default& d): Object(d){}; Clip(std::vector<tool::Atom> const& args); std::string getIODescription(bool is_inlet, size_t index) const override; }; }}
1,682
C++
.h
30
48.366667
91
0.481102
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,436
KiwiModel_Send.h
Musicoll_Kiwi/Modules/KiwiModel/KiwiModel_Objects/KiwiModel_Send.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once #include <KiwiModel/KiwiModel_Object.h> namespace kiwi { namespace model { // ================================================================================ // // SEND // // ================================================================================ // class Send : public model::Object { public: static void declare(); static std::unique_ptr<Object> create(std::vector<tool::Atom> const& args); Send(flip::Default& d) : model::Object(d) {} Send(std::vector<tool::Atom> const& args); std::string getIODescription(bool is_inlet, size_t index) const override; }; }}
1,652
C++
.h
30
48.866667
90
0.49192
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,437
KiwiModel_Pipe.h
Musicoll_Kiwi/Modules/KiwiModel/KiwiModel_Objects/KiwiModel_Pipe.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once #include <KiwiModel/KiwiModel_Object.h> namespace kiwi { namespace model { // ================================================================================ // // OBJECT PIPE // // ================================================================================ // class Pipe : public model::Object { public: // methods static void declare(); static std::unique_ptr<Object> create(std::vector<tool::Atom> const& args); Pipe(flip::Default& d) : model::Object(d) {}; Pipe(std::vector<tool::Atom> const& args); std::string getIODescription(bool is_inlet, size_t index) const override; }; }}
1,711
C++
.h
30
49.266667
91
0.487099
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,438
KiwiModel_Objects.h
Musicoll_Kiwi/Modules/KiwiModel/KiwiModel_Objects/KiwiModel_Objects.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once #include <KiwiModel/KiwiModel_Objects/KiwiModel_NewBox.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_ErrorBox.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Print.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Receive.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Slider.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Plus.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Times.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Delay.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Metro.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Pipe.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Bang.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Toggle.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_AdcTilde.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_DacTilde.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_OscTilde.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Loadmess.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_SigTilde.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_TimesTilde.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_PlusTilde.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_MeterTilde.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_DelaySimpleTilde.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Message.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_NoiseTilde.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_PhasorTilde.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_SahTilde.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_SnapshotTilde.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Trigger.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_LineTilde.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Minus.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Divide.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Equal.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Less.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Greater.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Different.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Pow.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Modulo.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_MinusTilde.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_DivideTilde.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_LessTilde.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_GreaterTilde.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_EqualTilde.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_DifferentTilde.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_LessEqual.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_LessEqualTilde.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_GreaterEqual.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_GreaterEqualTilde.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Comment.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Pack.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Unpack.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Random.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Scale.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Select.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Number.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_NumberTilde.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Hub.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Mtof.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Send.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Gate.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Switch.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_GateTilde.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_SwitchTilde.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Float.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_ClipTilde.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Clip.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_SfPlayTilde.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_SfRecordTilde.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_FaustTilde.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Route.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_OSCReceive.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_OSCSend.h>
5,155
C++
.h
85
58.211765
91
0.78478
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,439
KiwiModel_LessEqual.h
Musicoll_Kiwi/Modules/KiwiModel/KiwiModel_Objects/KiwiModel_LessEqual.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once #include <KiwiModel/KiwiModel_Object.h> #include <KiwiModel/KiwiModel_Objects/KiwiModel_Operator.h> namespace kiwi { namespace model { // ================================================================================ // // OBJECT LESSEQUAL // // ================================================================================ // class LessEqual : public Operator { public: LessEqual(flip::Default& d) : Operator(d) {} LessEqual(std::vector<tool::Atom> const& args); static void declare(); static std::unique_ptr<Object> create(std::vector<tool::Atom> const& args); }; }}
1,672
C++
.h
30
48.566667
91
0.494872
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,440
KiwiModel_GreaterEqualTilde.h
Musicoll_Kiwi/Modules/KiwiModel/KiwiModel_Objects/KiwiModel_GreaterEqualTilde.h
/* ============================================================================== 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 : [email protected] ============================================================================== */ #pragma once #include <KiwiModel/KiwiModel_Objects/KiwiModel_OperatorTilde.h> namespace kiwi { namespace model { // ================================================================================ // // OBJECT >=~ // // ================================================================================ // class GreaterEqualTilde : public OperatorTilde { public: static void declare(); static std::unique_ptr<Object> create(std::vector<tool::Atom> const& args); GreaterEqualTilde(flip::Default& d): OperatorTilde(d){}; GreaterEqualTilde(std::vector<tool::Atom> const& args); }; }}
1,670
C++
.h
29
50.241379
92
0.493906
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