text:
/*
 ==============================================================================

 VirtualKeyboard.h
 Created: 14 Mar 2019 4:50:31pm
 Author:  Vincenzo

 ==============================================================================
 */

#include "../../../../JuceLibraryCode/JuceHeader.h"
#include "KeyboardComponent.h"

using namespace VirtualKeyboard;

Keyboard::Keyboard()
    : keyPositioner(this)
{
    setName("VirtualKeyboard");
    addMouseListener(this, true);
    setWantsKeyboardFocus(true);

    initializeKeys();
    reset();

    setSize(1000, 250);
    setOpaque(true);
}

Keyboard::Keyboard(ValueTree keyboardNodeIn, Mode* modeIn, NoteMap* inputFilterMapIn)
    : keyPositioner(this)
{
    setName("VirtualKeyboard");
    addMouseListener(this, true);
    setWantsKeyboardFocus(true);

    initializeKeys(); // todo: load keyboard size
    restoreNode(keyboardNodeIn, true, true);

    if (modeIn)
        mode = modeIn;

    applyMode(mode);

    setSize(1000, 250);
    setOpaque(true);
}

Keyboard::~Keyboard()
{
    if (externalKeyboardToDisplay)
        externalKeyboardToDisplay->removeListener(this);
}

//===============================================================================================

void Keyboard::restoreNode(ValueTree pianoNodeIn, bool reinitializeKeys, bool resetIfInvalid)
{
    if (pianoNodeIn.hasType(IDs::pianoNode))
    {
        pianoNode = pianoNodeIn;
        DBG("RESTORING KEYBOARD NODE: " + pianoNode.toXmlString());

        showNoteNumbers = pianoNode[IDs::pianoKeysShowNoteNumbers];
        orientationSelected = pianoNode[IDs::keyboardOrientation];
        keyPlacementSelected = pianoNode[IDs::keyboardKeysStyle];
        highlightSelected = pianoNode[IDs::keyboardHighlightStyle];
        lastKeyClicked = pianoNode[IDs::pianoLastKeyClicked];
        keySizeRatio = (float) pianoNode[IDs::pianoWHRatio];

        keyPositioner.setKeyPlacement(keyPlacementSelected);

        // safeguard
        if (keySizeRatio < 0.01)
            keySizeRatio = 0.25f;

        if (reinitializeKeys)
        {
            // TODO: keyboard key editing
            pianoNode.removeChild(pianoNode.getChildWithName(IDs::pianoKeyTreeNode), nullptr);
            // unpack key data
            //keyTreeNode = pianoNode.getOrCreateChildWithName(IDs::pianoKeyTreeNode, nullptr);

            //if (keyTreeNode.getNumChildren() == keys.size())
            //{
            //    for (auto key : keys)
            //        key->applyParameters(keyTreeNode.getChild(key->keyNumber));
            //}
            //else
            //{
            //    keyTreeNode.removeAllChildren(nullptr);

            initializeKeys();

            //for (auto key : keys)
            //{
            //    keyTreeNode.addChild(key->node, key->keyNumber, nullptr);
            //}
            //}
        }
    }
    else
    {
        DBG("Invalid Piano Node.");
        if (resetIfInvalid)
        {
            reset();
            DBG("Keyboard is reset.");
        }
    }
}

void Keyboard::reset()
{
    pianoNode = ValueTree(IDs::pianoNode);

    setUIMode(UIMode::playMode);
    setOrientation(Orientation::horizontal);
    setKeyStyle(KeyPlacementType::nestedRight);
    setHighlightStyle(HighlightStyle::full);
    setVelocityBehavior(VelocityStyle::linear);
    setScrollingStyle(ScrollingStyle::smooth);

    setShowNoteLabels(false);
    setShowNoteNumbers(false);
    setShowFilteredNumbers(false);

    setMidiChannelOut(1);
    setVelocityFixed(1);
    setInputVelocityScaled(false);

    setKeySizeRatio(0.25f);
    setKeyOrderSizeScalar(1);

    keyOnColorsByChannel.resize(16);
    keyOnColorsByChannel.fill(Colour());

    mode = &modeDefault;
    applyMode(mode);
}

void Keyboard::initializeKeys(int size)
{
    keys.clear();

    for (int i = 0; i < size; i++)
    {
        Key* key = keys.add(new Key(i));
        addAndMakeVisible(key);
        key->showNoteNumber = showNoteNumbers; // hacky ?
        key->highlightStyleId = highlightSelected;
    }

    keyColorsIndividual.resize(keys.size());

    keysOn = Array<int>();
    keysByMouseTouch = Array<int>();
}

//===============================================================================================

void Keyboard::paint(juce::Graphics& g)
{
    g.fillAll(getLookAndFeel().findColour(ResizableWindow::backgroundColourId));
}

void Keyboard::paintOverChildren(juce::Graphics& g)
{
    g.setColour(Colours::black);
    g.drawRect(getLocalBounds(), 1);
}

void Keyboard::resized()
{
    keyPositioner.parentResized();

    keyWidth = keyPositioner.getKeyWidth();
    keyHeight = getHeight();

    keyPositioner.setLayerKeysWidthRatio(layerKeysWidthRatio);
    keyPositioner.setLayerKeysHeightRatio(layerKeysHeightRatio);

    for (int i = 0; i < keys.size(); i++)
    {
        Key* key = keys[i];
        keyPositioner.resizeKey(*key);
    }

    float keyOrder1Width = keyWidth * layerKeysWidthRatio;
    float adjacentStyleStepWidth;

    // Place Keys
    Array<int>& modeKeys = keysOrder.getReference(0);
    for (int i = 0; i < numOrder0Keys; i++)
    {
        Key& modeKey = *keys[modeKeys[i]];

        int keyX = (keyWidth + keyPositioner.getKeyGap() - 1) * i;
        modeKey.setTopLeftPosition(keyX, 0);

        if (modeKey.step > 1)
        {
            adjacentStyleStepWidth = keyOrder1Width / (modeKey.step - 1);

            for (int s = 1; s < modeKey.step; s++)
            {
                Key* stepKey = keys[modeKey.keyNumber + s];

                if (s > 1 && keyPlacementSelected == KeyPlacementType::nestedRight)
                {
                    keyX = modeKey.getX() + keyWidth + (keys[modeKey.keyNumber + 1]->getWidth() / 2) - stepKey->getWidth();
                }
                else if (stepKey->step > 2 && keyPlacementSelected == KeyPlacementType::adjacent)
                {
                    keyX = modeKey.getX() + keyWidth - (keyOrder1Width / 2) + (stepKey->order - 1) * adjacentStyleStepWidth;
                }
                else
                {
                    keyX = modeKey.getX() + keyWidth - stepKey->getWidth() / 2;
                }

                stepKey->setTopLeftPosition(keyX, 0);
            }
        }
    }
}

//===============================================================================================

void Keyboard::mouseMove(const MouseEvent& e)
{
    Key* key = getKeyFromPositionMouseEvent(e);

    if (uiModeSelected != UIMode::editMode)
    {
        if (key)
        {
            lastKeyOver = key->keyNumber;
        }
    }

    else
    {
        if (key)
        {
            lastKeyOver = key->keyNumber;
            setMouseCursor(MouseCursor::CrosshairCursor);
        }
        else
        {
            setMouseCursor(MouseCursor::NormalCursor);
        }
    }
}

void Keyboard::mouseExit(const MouseEvent& e)
{
    if (uiModeSelected != UIMode::editMode)
    {
        int touchIndex = e.source.getIndex();
        if (keysByMouseTouch[touchIndex] > 0)
        {
            Key* key = keys[keysByMouseTouch[touchIndex]];

            if (!e.source.isDragging())
            {
                triggerKey(key->keyNumber, false);
                keysByMouseTouch.set(touchIndex, -1);
            }
        }

        Key* key = keys[lastKeyOver];
        key->repaint();
    }
}

void Keyboard::mouseDown(const MouseEvent& e)
{
    Key* key = getKeyFromPositionMouseEvent(e);
    bool triggerNote = false;

    if (uiModeSelected == UIMode::editMode)
    {
        if (key)
        {
            if (e.mods.isRightButtonDown() || getProperties()[IDs::pianoKeyColorReset])
            {
                if (e.mods.isShiftDown())
                    keyColorsOrders.set(key->order, Colour());

                else if (e.mods.isCtrlDown())
                    keyColorsIndividual.set(key->keyNumber, Colour());

                else
                {
                    if (keyColorsIndividual[key->keyNumber].isOpaque())
                        keyColorsIndividual.set(key->keyNumber, Colour());

                    keyColorsDegrees.set(key->scaleDegree, Colour());
                }
            }

            else if (e.mods.isCtrlDown() || (int)getProperties()[IDs::pianoKeyPaintType] == 2)
            {
                keyColorsIndividual.set(key->keyNumber, Colour::fromString(getProperties()[IDs::colorSelected].toString()));
            }

            else if (e.mods.isShiftDown() || (int)getProperties()[IDs::pianoKeyPaintType] == 1)
            {
                if (getKeyDegreeColor(key->scaleDegree).isOpaque())
                    keyColorsDegrees.set(key->scaleDegree, Colour());

                else if (getKeyColor(key->keyNumber).isOpaque())
                    keyColorsIndividual.set(key->keyNumber, Colour());

                keyColorsOrders.set(key->order, Colour::fromString(getProperties()[IDs::colorSelected].toString()));
            }

            else
            {
                if (keyColorsIndividual[key->keyNumber].isOpaque())
                    keyColorsIndividual.set(key->keyNumber, Colour());

                keyColorsDegrees.set(key->scaleDegree, Colour::fromString(getProperties()[IDs::colorSelected].toString()));
            }

            updateKeyColors();
        }
    }
    else if (uiModeSelected == UIMode::mapMode)
    {
        if (key)
        {
            if (e.mods.isRightButtonDown())
            {
                bool allPeriods = true;

                if (e.mods.isCtrlDown())
                    allPeriods = false;

                manualMappingHelper->prepareKeyToMap(key->keyNumber, false);
                highlightKey(key->keyNumber);

                DBG("Preparing to map key: " + String(key->keyNumber));
            }
            else
            {
                triggerNote = true;
            }
        }

        if (!key || !isMouseOver(true))
        {
            highlightKey(manualMappingHelper->getVirtualKeyToMap(), false);
            manualMappingHelper->cancelKeyMap();
        }
    }

    if (uiModeSelected == UIMode::playMode || triggerNote)
    {
        if (key)
        {
            if (e.mods.isShiftDown() && !e.mods.isAltDown() && key->isClicked)
            {
                // note off
                lastKeyClicked = key->keyNumber;
                triggerKey(key->keyNumber, false);
            }
            else
            {
                // need to implement a velocity class
                triggerKey(key->keyNumber);
                lastKeyClicked = key->keyNumber;
                keysByMouseTouch.set(e.source.getIndex(), key->keyNumber);

                if (e.mods.isAltDown())
                {
                    isolateLastNote();
                }
            }
        }
    }
}

void Keyboard::mouseDrag(const MouseEvent& e)
{
    if (uiModeSelected != UIMode::editMode && !e.mods.isRightButtonDown())
    {
        Key* key = getKeyFromPositionMouseEvent(e);

        if (key)
        {
            //bool alreadyDown = false;
            int touchIndex = e.source.getIndex();
            int keyIndex = keysByMouseTouch[touchIndex];

            if (key->keyNumber != keyIndex)
            {
                if (!e.mods.isShiftDown())
                    triggerKey(keyIndex, false);

                triggerKey(key->keyNumber);
                lastKeyClicked = key->keyNumber;
                keysByMouseTouch.set(touchIndex, key->keyNumber);
            }
        }
    }

}

void Keyboard::mouseUp(const MouseEvent& e)
{
    if (uiModeSelected != UIMode::editMode)
    {
        int touchIndex = e.source.getIndex();
        int keyIndex = keysByMouseTouch[touchIndex];

        if (keyIndex > 0)
        {
            Key* key = keys[keyIndex];

            if (key)// && mappingHelper->getVirtualKeyToMap() != key->keyNumber)
            {
                keysByMouseTouch.set(touchIndex, -1);

                if (!shiftHeld)
                {
                    triggerKey(key->keyNumber, false);
                }
            }
        }
    }
}

//===============================================================================================

bool Keyboard::keyStateChanged(bool isKeyDown)
{
    if (!KeyPress::isKeyCurrentlyDown(KeyPress::upKey) && upHeld)
    {
        upHeld = false;
        return true;
    }

    if (!KeyPress::isKeyCurrentlyDown(KeyPress::downKey) && downHeld)
    {
        downHeld = false;
        return true;
    }

    if (!KeyPress::isKeyCurrentlyDown(KeyPress::leftKey) && leftHeld)
    {
        leftHeld = false;
        return true;
    }

    if (!KeyPress::isKeyCurrentlyDown(KeyPress::rightKey) && rightHeld)
    {
        rightHeld = false;
        return true;
    }

    if (!KeyPress::isKeyCurrentlyDown(KeyPress::spaceKey) && spaceHeld)
    {
        spaceHeld = false;
        return true;
    }

    return false;
}

bool Keyboard::keyPressed(const KeyPress& key)
{
    if (KeyPress::isKeyCurrentlyDown(KeyPress::upKey) && !upHeld)
    {
        upHeld = true;
        if (uiModeSelected != UIMode::editMode)
        {
            if (shiftHeld && keysOn.size() > 0)
            {
                transposeKeysOnChromatically(1);
                repaint();
            }
        }
        return true;
    }

    if (KeyPress::isKeyCurrentlyDown(KeyPress::downKey) && !downHeld)
    {
        downHeld = true;
        if (uiModeSelected != UIMode::editMode)
        {
            if (shiftHeld && keysOn.size() > 0)
            {
                transposeKeysOnChromatically(-1);
                repaint();
            }
        }
        return true;
    }

    if (KeyPress::isKeyCurrentlyDown(KeyPress::leftKey) && !leftHeld)
    {
        leftHeld = true;
        if (uiModeSelected != UIMode::editMode)
        {
            if (shiftHeld && keysOn.size() > 0)
            {
                transposeKeysOnModally(-1);
            }
        }
        return true;
    }

    if (KeyPress::isKeyCurrentlyDown(KeyPress::rightKey) && !rightHeld)
    {
        rightHeld = true;
        if (uiModeSelected != UIMode::editMode)
        {
            if (shiftHeld && keysOn.size() > 0)
            {
                transposeKeysOnModally(1);
            }
        }
        return true;
    }

    if (KeyPress::isKeyCurrentlyDown(KeyPress::spaceKey) && !spaceHeld)
    {
        spaceHeld = true;
        if (uiModeSelected != UIMode::editMode)
        {
            if (shiftHeld && keysOn.size() > 0)
            {
                retriggerNotes();
            }
        }
        return true;
    }

    return false;
}

void Keyboard::modifierKeysChanged(const ModifierKeys& modifiers)
{
    if (!rightMouseHeld && modifiers.isRightButtonDown())
    {
        rightMouseHeld = true;
    }
    if (rightMouseHeld && !modifiers.isRightButtonDown())
    {
        rightMouseHeld = false;
    }

    if (!shiftHeld && modifiers.isShiftDown())
    {
        shiftHeld = true;
    }

    if (shiftHeld && !modifiers.isShiftDown())
    {
        shiftHeld = false;

        if (uiModeSelected != UIMode::editMode)
        {
            isolateLastNote();

            Key* key = keys[lastKeyClicked];

            if (!(key->isMouseOver() && key->isMouseButtonDownAnywhere()))
                triggerKey(lastKeyClicked, false);

        }
    }

    if (!altHeld && modifiers.isAltDown())
    {
        altHeld = true;
        if (uiModeSelected != UIMode::editMode)
        {
            isolateLastNote();
            repaint();
        }
    }

    else if (altHeld && !modifiers.isAltDown())
    {
        altHeld = false;
    }

    if (!ctrlHeld && modifiers.isCtrlDown())
    {
        ctrlHeld = true;
    }

    else if (ctrlHeld && !modifiers.isCtrlDown())
    {
        ctrlHeld = false;
    }
}

//===============================================================================================

//void Keyboard::timerCallback()
//{
    //if (hasDirtyKeys)
    //{
    //    for (auto key : *keys.get())
    //    {
    //        if (key->isDirty)
    //        {
    //            key->repaint();
    //        }
    //    }
    //}

    //hasDirtyKeys = false;
//}

//===============================================================================================

ValueTree Keyboard::getNode()
{
    return pianoNode;
}

Key* Keyboard::getKey(int keyNumIn)
{
    return keys[keyNumIn];
}

ValueTree Keyboard::getKeyNode(int keyNumIn)
{
    return keys[keyNumIn]->node;
}

Array<Key*> Keyboard::getKeysByOrder(int orderIn)
{
    Array<Key*> keysOut;
    Array<int> orderArray = keysOrder[orderIn];

    for (int i = 0; i < orderArray.size(); i++)
    {
        keysOut.add(keys[orderArray[i]]);
    }

    return keysOut;
}

Array<Key*> Keyboard::getKeysByScaleDegree(int degreeIn)
{
    Array<Key*> keysOut;
    Array<int> degreeArray = keysScaleDegree[degreeIn];

    for (int i = 0; i < degreeArray.size(); i++)
    {
        keysOut.add(keys[degreeArray[i]]);
    }

    return keysOut;
}

Array<Key*> Keyboard::getKeysByModalDegree(int degreeIn)
{
    Array<Key*> keysOut;
    Array<int> degreeArray = keysModalDegree[degreeIn];

    for (int i = 0; i < degreeArray.size(); i++)
    {
        keysOut.add(keys[degreeArray[i]]);
    }

    return keysOut;
}

int Keyboard::getLastKeyClicked()
{
    return lastKeyClicked;
}

Rectangle<int> Keyboard::getKeyArea(int midiNoteIn)
{
    // TODO
    return Rectangle<int>();
}

Rectangle<int> Keyboard::getKeyAreaRelative(int midiNoteIn)
{
    // TODO
    return Rectangle<int>();
}

int Keyboard::getKeyWidth()
{
    return keyWidth;
}

int Keyboard::getKeyHeight()
{
    return keyHeight;
}

int Keyboard::getPianoWidth(int heightIn)
{
    return numOrder0Keys  * (heightIn * keySizeRatio + keyPositioner.getKeyGap() - 1);
}

float Keyboard::getKeySizeRatio()
{
    return keySizeRatio;
}

Point<int> Keyboard::getKeyOrderSize(int orderIn)
{
    //TODO (use the scalar)
 return Point<int>();
}

Key* Keyboard::getKeyFromPosition(Point<int> posIn)
{
    Key* keyOut = nullptr;
    Component* c = getComponentAt(posIn);

    if (c != nullptr && c->getName().startsWith("Key"))
        keyOut = dynamic_cast<Key*>(c);

    return keyOut;
}

Key* Keyboard::getKeyFromPositionMouseEvent(const MouseEvent& e)
{
    Point<int> ep = Point<int>(e.getScreenX() - getScreenX(), e.getPosition().getY());
    return getKeyFromPosition(ep);
}

float Keyboard::getKeyVelocity(Key* keyIn, Point<int> posIn)
{
    //TODO
    return velocityFixed;
}

int Keyboard::getMidiChannelOut() const
{
    return midiChannelOut;
}

int Keyboard::getModeSize() const
{
    return mode->getModeSize();
}

//===============================================================================================

int Keyboard::getUIMode()
{
    return uiModeSelected;
}

int Keyboard::getOrientation()
{
    return orientationSelected;
}

int Keyboard::getKeyPlacementStyle()
{
    return keyPlacementSelected;
}

bool Keyboard::isShowingNoteNumbers()
{
    return showNoteNumbers;
}

bool Keyboard::isShowingFilteredNumbers()
{
    return showFilteredNoteNums;
}

bool Keyboard::isShowingNoteNames()
{
    return showNoteLabels;
}

int Keyboard::getHighlightStyle()
{
    return highlightSelected;
}

int Keyboard::getVelocityStyle()
{
    return velocitySelected;
}

float Keyboard::getVelocityFixed()
{
    return velocityFixed;
}

bool Keyboard::isInputVelocityScaled()
{
    return scaleMidiInputVelocity;
}

int Keyboard::getScrollingStyle()
{
    return scrollingSelected;
}

//===============================================================================================

void Keyboard::applyMode(Mode* modeIn, bool resize)
{
    mode = modeIn;

    if (mode == nullptr)
        mode = &modeDefault;

    keysOrder.clear();
    keysOrder.resize(mode->getMaxStep());

    int period = 0;

    for (int i = 0; i < keys.size(); i++)
    {
        Key* key = keys[i];
        period = i / mode->getScaleSize();

        key->order = mode->getOrder(i);
        key->scaleDegree = mode->getScaleDegree(i);
        key->modeDegree = mode->getModeDegree(i);
        key->step = mode->getNoteStep(i);

        keysOrder.getReference(key->order).add(key->keyNumber);
    }

    numOrder0Keys = keysOrder.getReference(0).size();
    keyPositioner.setNumModeKeys(numOrder0Keys);

    keysScaleDegree = mode->getNotesInScaleDegrees();
    keysModalDegree = mode->getNotesInModalDegrees();

    // add from back to front
    for (int o = 0; o < keysOrder.size(); o++)
    {
        Array<int>& orderArray = keysOrder.getReference(o);

        for (int keyNum = 0; keyNum < orderArray.size(); keyNum++)
        {
            Key* key = keys[(orderArray.getReference(keyNum))];
            //addAndMakeVisible(key);
            key->toFront(false);
        }
    }

    keyColorsOrders.resize(mode->getMaxStep());
    keyColorsDegrees.resize(mode->getScaleSize());

    // unpack color data
    ValueTree keyColorsNode = mode->modeNode.getOrCreateChildWithName(IDs::pianoKeyColorsNode, nullptr);

    keyColorsOrders.fill(Colour());
    for (auto layerColor : keyColorsNode.getChildWithName(IDs::pianoKeyColorsLayer))
    {
        keyColorsOrders.set(
            layerColor[IDs::pianoKeyColorsLayer],
            Colour::fromString(layerColor[IDs::pianoKeyColor].toString())
        );
    }

    keyColorsDegrees.fill(Colour());
    for (auto degreeColor : keyColorsNode.getChildWithName(IDs::pianoKeyColorsDegree))
    {
        keyColorsDegrees.set(
            degreeColor[IDs::pianoKeyColorsDegree],
            Colour::fromString(degreeColor[IDs::pianoKeyColor].toString())
        );
    }

    keyColorsIndividual.fill(Colour());
    for (auto keyColor : keyColorsNode.getChildWithName(IDs::pianoKeyColorsIndividual))
    {
        keyColorsIndividual.set(
            mode->fixedDegreeToNoteNumber(keyColor[IDs::pianoKeyColorsIndividual]),
            Colour::fromString(keyColor[IDs::pianoKeyColor].toString())
        );
    }

    keyOnColorsByChannel.fill(Colour());
    for (auto noteOnColor : keyColorsNode.getChildWithName(IDs::pianoKeyColorsNoteOn))
    {
        keyOnColorsByChannel.set(
            noteOnColor[IDs::pianoKeyColorsNoteOn],
            Colour::fromString(noteOnColor[IDs::pianoKeyColor].toString())
        );
    }

    updateKeyColors();

    if (resize)
        resized();
    else
        hasDirtyKeys = true;
}

void Keyboard::applyKeyData(ValueTree keyDataTreeIn)
{
    ValueTree keyNode;

    int numKeys = jmin(keys.size(), keyDataTreeIn.getNumChildren());

    for (int i = 0; i < numKeys; i++)
    {
        Key* key = keys[i];
        key->applyParameters(keyDataTreeIn.getChild(i));
    }
}

void Keyboard::displayKeyboardState(MidiKeyboardState* keyboardStateIn)
{
    if (externalKeyboardToDisplay)
        externalKeyboardToDisplay->removeListener(this);

    externalKeyboardToDisplay = keyboardStateIn;

    if (externalKeyboardToDisplay)
        externalKeyboardToDisplay->addListener(this);
}

//===============================================================================================

void Keyboard::setUIMode(int uiModeIn)
{
    if (uiModeSelected == UIMode::editMode && uiModeIn != uiModeSelected)
        updateKeyColors();

    uiModeSelected = uiModeIn;
    pianoNode.setProperty(IDs::pianoUIMode, uiModeSelected, nullptr);
 }

void Keyboard::setOrientation(int orientationIn)
{
    orientationSelected = orientationIn;
    pianoNode.setProperty(IDs::keyboardOrientation, orientationSelected, nullptr);

    // do stuff
}

void Keyboard::setNumRows(int numRowsIn)
{
    numRows = jlimit(1, 16, numRowsIn);
    pianoNode.setProperty(IDs::keyboardNumRows, numRows, nullptr);
    applyMode(mode);
}

void Keyboard::setKeyStyle(int placementIn)
{
    keyPlacementSelected = placementIn;
    keyPositioner.setKeyPlacement(keyPlacementSelected);
    pianoNode.setProperty(IDs::keyboardKeysStyle, keyPlacementSelected, nullptr);
}

void Keyboard::setHighlightStyle(int styleIn)
{
    highlightSelected = styleIn;
    pianoNode.setProperty(IDs::keyboardHighlightStyle, highlightSelected, nullptr);

    for (auto key : keys)
    {
        key->highlightStyleId = highlightSelected;
        key->repaint();
    }
}

void Keyboard::setVelocityBehavior(int behaviorNumIn, bool scaleInputVelocity)
{
    velocitySelected = behaviorNumIn;
    pianoNode.setProperty(IDs::pianoVelocityBehavior, velocitySelected, nullptr);

    scaleMidiInputVelocity = scaleInputVelocity;
    pianoNode.setProperty(IDs::pianoVelocityScaleInput, scaleMidiInputVelocity, nullptr);
}

void Keyboard::setScrollingStyle(int scrollingStyleIn)
{
    scrollingSelected = scrollingStyleIn;
    pianoNode.setProperty(IDs::keyboardScrollingStyle, scrollingSelected, nullptr);

    // do stuff?
}

void Keyboard::setMidiChannelOut(int midiChannelOutIn)
{
    midiChannelOut = jlimit(1, 16, midiChannelOutIn);
    pianoNode.setProperty(IDs::keyboardMidiChannel, midiChannelOut, nullptr);
}

void Keyboard::setVelocityFixed(float velocityIn)
{
    velocityFixed = velocityIn;
    pianoNode.setProperty(IDs::pianoVelocityValue, velocityFixed, nullptr);
}

void Keyboard::setInputVelocityScaled(bool shouldBeScaled)
{
    scaleMidiInputVelocity = shouldBeScaled;
    pianoNode.setProperty(IDs::pianoVelocityScaleInput, scaleMidiInputVelocity, nullptr);
}

void Keyboard::setShowNoteNumbers(bool shouldShowNumbers)
{
    showNoteNumbers = shouldShowNumbers;
    pianoNode.setProperty(IDs::pianoKeysShowNoteNumbers, showNoteNumbers, nullptr);

    for (int i = 0; i < keys.size(); i++)
    {
        Key* key = keys[i];
        key->showNoteNumber = shouldShowNumbers;
        key->repaint();
    }
}

void Keyboard::setShowFilteredNumbers(bool shouldShowNumbers)
{
    showFilteredNoteNums = shouldShowNumbers;
    pianoNode.setProperty(IDs::pianoKeysShowFilteredNotes, showFilteredNoteNums, nullptr);
}

void Keyboard::setShowNoteLabels(bool shouldShowPitchNames)
{
    showNoteLabels = shouldShowPitchNames;
    pianoNode.setProperty(IDs::keyboardShowsNoteLabels, showNoteLabels, nullptr);
}

void Keyboard::setLastKeyClicked(int keyNumIn)
{
    lastKeyClicked = keyNumIn;
    pianoNode.setProperty(IDs::pianoLastKeyClicked, lastKeyClicked, nullptr);
}

void Keyboard::setInputNoteMap(NoteMap& noteMapIn)
{
    noteMapOnDisplay = noteMapIn;
}

//===============================================================================================

void Keyboard::setMappingHelper(MappingHelper* mappingHelperIn)
{
    manualMappingHelper = mappingHelperIn;
}

void Keyboard::highlightKey(int keyNumberIn, bool highlightOn)
{
    if (keyNumberIn < 0 || keyNumberIn >= keys.size())
        return;

    if (highlightOn)
        highlightedKeys.add(keys[keyNumberIn]);
    else
        highlightedKeys.removeAllInstancesOf(keys[keyNumberIn]);
}

//===============================================================================================

Array<Colour>* Keyboard::getKeyIndividualColours()
{
    return &keyColorsIndividual;
}

Colour Keyboard::getKeyColor(int keyNumIn)
{
    Colour c;

    if (keyNumIn >= 0 && keyNumIn < keys.size())
    {
        Key* key = keys[keyNumIn];

        if (keyColorsIndividual[key->keyNumber].isOpaque()) // need to fix this for switching modes
            c = keyColorsIndividual[key->keyNumber];

        else if (keyColorsDegrees[key->scaleDegree].isOpaque())
            c = keyColorsDegrees[key->scaleDegree];

        else if (keyColorsOrders[key->order].isOpaque())
            c = keyColorsOrders[key->order];

        else
            c = colorsDefaultOrders[key->order];
    }

  return c;
}

Array<Colour>* Keyboard::getKeyLayerColours()
{
    return &keyColorsOrders;
}

Colour Keyboard::getKeyLayerColor(int orderIn)
{
    Colour c;

    if (keyColorsOrders[orderIn].isOpaque())
            c = keyColorsOrders[orderIn];

    else
        c = colorsDefaultOrders[orderIn];

    return c;
}

Array<Colour>* Keyboard::getKeyDegreeColours()
{
    return &keyColorsDegrees;
}

Colour Keyboard::getKeyDegreeColor(int degIn)
{
    Colour c;

    if (keyColorsDegrees[degIn].isOpaque())
            c = keyColorsDegrees[degIn];

    else // this deg->order conversion is probably wrong
        c = colorsDefaultOrders[mode->getOrder(degIn)];

    return c;
}

Array<Colour>* Keyboard::getKeyNoteOnColours()
{
    return &keyOnColorsByChannel;
}

void Keyboard::updateKeyColors(bool writeToNode)
{
    for (int i = 0; i < keys.size(); i++)
    {
        Key* key = keys[i];
         key->setDisplayColor(getKeyColor(i));
    }

    if (writeToNode)
    {
        ValueTree keyColorsNode = mode->modeNode.getOrCreateChildWithName(IDs::pianoKeyColorsNode, nullptr);

        ValueTree layersColorNode = ValueTree(IDs::pianoKeyColorsLayer);
        for (int i = 0; i < keyColorsOrders.size(); i++)
        {
            if (keyColorsOrders[i].isOpaque())
            {
                ValueTree node(IDs::pianoKeyColor);
                node.setProperty(IDs::pianoKeyColorsLayer, i, nullptr);
                node.setProperty(IDs::pianoKeyColor, keyColorsOrders[i].toString(), nullptr);
                layersColorNode.appendChild(node, nullptr);
            }
        }
        keyColorsNode.getOrCreateChildWithName(IDs::pianoKeyColorsLayer, nullptr).copyPropertiesAndChildrenFrom(layersColorNode, nullptr);

        ValueTree degreesColorNode = ValueTree(IDs::pianoKeyColorsDegree);
        for (int i = 0; i < keyColorsDegrees.size(); i++)
        {
            if (keyColorsDegrees[i].isOpaque())
            {
                ValueTree node(IDs::pianoKeyColor);
                node.setProperty(IDs::pianoKeyColorsDegree, i, nullptr);
                node.setProperty(IDs::pianoKeyColor, keyColorsDegrees[i].toString(), nullptr);
                degreesColorNode.appendChild(node, nullptr);
            }
        }
        keyColorsNode.getOrCreateChildWithName(IDs::pianoKeyColorsDegree, nullptr).copyPropertiesAndChildrenFrom(degreesColorNode, nullptr);

        ValueTree individualColorNode = ValueTree(IDs::pianoKeyColorsIndividual);
        for (int i = 0; i < keyColorsIndividual.size(); i++)
        {
            if (keyColorsIndividual[i].isOpaque())
            {
                ValueTree node(IDs::pianoKeyColor);
                node.setProperty(IDs::pianoKeyColorsIndividual, mode->getFixedDegree(i), nullptr);
                node.setProperty(IDs::pianoKeyColor, keyColorsIndividual[i].toString(), nullptr);
                individualColorNode.appendChild(node, nullptr);
            }
        }
        keyColorsNode.getOrCreateChildWithName(IDs::pianoKeyColorsIndividual, nullptr).copyPropertiesAndChildrenFrom(individualColorNode, nullptr);

        ValueTree keyOnColorNode = ValueTree(IDs::pianoKeyColorsNoteOn);
        for (int i = 0; i < 16; i++)
        {
            if (keyOnColorsByChannel[i].isOpaque())
            {
                ValueTree node(IDs::pianoKeyColor);
                node.setProperty(IDs::pianoKeyColorsNoteOn, i, nullptr);
                node.setProperty(IDs::pianoKeyColor, keyOnColorsByChannel[i].toString(), nullptr);
                keyOnColorNode.appendChild(node, nullptr);
            }
        }
        keyColorsNode.getOrCreateChildWithName(IDs::pianoKeyColorsNoteOn, nullptr).copyPropertiesAndChildrenFrom(keyOnColorNode, nullptr);
    }
}

void Keyboard::resetLayerColors()
{
    keyColorsOrders.fill(Colour());
}

void Keyboard::resetDegreeColors()
{
    keyColorsDegrees.fill(Colour());
}

void Keyboard::resetKeyColors()
{
    resetLayerColors();
    resetDegreeColors();
    keyColorsIndividual.fill(Colour());

    updateKeyColors();
}

//===============================================================================================

void Keyboard::setKeyDegreeColor(int scaleDegreeIn, Colour colourIn)
{
    int degree = totalModulus(scaleDegreeIn, mode->getScaleSize());
    keyColorsDegrees.set(degree, colourIn);
}

void Keyboard::setKeyLayerColor(int layerNumIn, Colour colourIn)
{
    int layer = totalModulus(layerNumIn, mode->getMaxStep());
    keyColorsOrders.set(layer, colourIn);
}

void Keyboard::setKeyColor(int keyNumIn, Colour colourIn)
{
    int keyNum = totalModulus(keyNumIn, keys.size());
    keyColorsIndividual.set(keyNum, colourIn);
}

//===============================================================================================

void Keyboard::setKeySizeRatio(float keySizeRatioIn, bool resizeSelf)
{
    keySizeRatio = keySizeRatioIn;
    pianoNode.setProperty(IDs::pianoWHRatio, keySizeRatio, nullptr);

    if (resizeSelf)
        setSize(getPianoWidth(getHeight()), getHeight());
}

void Keyboard::setKeyWidthSize(int widthSizeIn)
{
    // do stuff
}

void Keyboard::setKeyOrderSizeScalar(float scalarIn)
{
    // do stuff
}

//===============================================================================================

void Keyboard::allNotesOff()
{
    MidiKeyboardState::allNotesOff(midiChannelOut);

    for (int i = 0; i < keys.size(); i++)
    {
        triggerKey(i, false);
    }
}

void Keyboard::isolateLastNote()
{
    if (lastKeyClicked >= 0 && lastKeyClicked < 128)
    {
        for (int i = 0; i < keys.size(); i++)
        {
            if (i != lastKeyClicked)
                triggerKey(i, false);
        }
    }
}

void Keyboard::retriggerNotes()
{
    Array<int> retrigger = Array<int>(keysOn);
    triggerKeys(retrigger, false, 0);
    triggerKeys(retrigger, true, 0.7f);
}

void Keyboard::triggerKey(int keyNumberIn, bool doNoteOn, float velocity)
{
    if (keyNumberIn < 0 || keyNumberIn >= keys.size())
        return;

    Key* key = keys[keyNumberIn];

    if (doNoteOn)
    {
        noteOn(midiChannelOut, keyNumberIn, velocity);
        key->isClicked = true;
        keysOn.addIfNotAlreadyThere(keyNumberIn);
    }
    else
    {
        noteOff(midiChannelOut, keyNumberIn, 0);
        key->isClicked = false;
        keysOn.removeAllInstancesOf(keyNumberIn);
    }

    key->repaint();
}

void Keyboard::triggerKeys(Array<int> keyNumbers, bool doNoteOn, float velocity)
{
    for (auto keyNum : keyNumbers)
    {
        triggerKey(keyNum, doNoteOn, velocity);
    }
}

int Keyboard::getOrderOfNotesOn()
{
    float orderSum = 0;
    int orderDetected;

    for (int i = 0; i < keysOn.size(); i++)
    {
        Key* key = keys[keysOn[i]];
        orderSum += (key->order + 1);
    }

    orderDetected = orderSum / keysOn.size();

    if (orderDetected == (int)orderDetected)
        orderDetected -= 1;
    else
        orderDetected = -1;

    return orderDetected;
}

int Keyboard::transposeKeyModally(int keyNumIn, int stepsIn)
{
    if (keyNumIn < 0 || keyNumIn >= keys.size())
        return -1;

    Key* key = keys[keyNumIn];
    Array<int> orderArray = keysOrder[key->order];
    int newKey = -1;

    for (int i = 0; i < orderArray.size(); i++)
    {
        if (key->keyNumber == orderArray.getUnchecked(i))
        {
            newKey = i;
            break;
        }
    }

    newKey += stepsIn;

    if (newKey >= 0 && newKey < orderArray.size())
        return orderArray[newKey];
    else
        return -1;
}

int Keyboard::transposeKeyChromatically(int keyNumIn, int stepsIn)
{
    int newKey = keyNumIn + stepsIn;

    if (newKey >= 0 && newKey <= keys.size())
        return newKey;
    else
        return -1;
}

void Keyboard::transposeKeysOnModally(int modalStepsIn, bool needsSameOrder, bool useLastClickedRoot)
{
    int keyRoot;
    int rootOrder;

    int newKey;
    Array<int> oldKeys = Array<int>(keysOn);
    Array<int> newKeys;

    if (needsSameOrder)
    {
        rootOrder = keys[keysOn[0]]->order;

        if (rootOrder != getOrderOfNotesOn())
            return;

        for (int i = 0; i < oldKeys.size(); i++)
        {
            newKey = transposeKeyModally(oldKeys[i], modalStepsIn);

            if (newKey > -1)
                newKeys.add(newKey);
        }
    }

    else
    {
        int stepsToUse; // TODO: implement this so that the chord quality is retained

        if (useLastClickedRoot)
        {
            keyRoot = lastKeyClicked;
        }
        else // find lowest key
        {
            keyRoot = keys.size();

            for (int i = 0; i < keysOn.size(); i++)
            {
                if (keysOn[i] < keyRoot)
                    keyRoot = keysOn[i];
            }
        }

        rootOrder = keys[keyRoot]->order;

        for (int i = 0; i < oldKeys.size(); i++)
        {
            newKey = transposeKeyModally(oldKeys[i], modalStepsIn);

            if (newKey > -1)
                newKeys.add(newKey);
        }
    }

    // TODO: implement velocities further
    lastKeyClicked = transposeKeyModally(lastKeyClicked, modalStepsIn);
    triggerKeys(oldKeys, false);
    triggerKeys(newKeys);
}

void Keyboard::transposeKeysOnChromatically(int stepsIn)
{
    Array<int> oldKeys = Array<int>(keysOn);
    Array<int> newKeys;
    int keyNum;
    int newKey;

    float velocity;

    for (int i = 0; i < oldKeys.size(); i++)
    {
        keyNum = oldKeys.getUnchecked(i);

        Key* key = keys[keyNum];
        velocity = key->velocity;

        newKey = transposeKeyChromatically(keyNum, stepsIn);

        if (newKey > -1)
            newKeys.add(newKey);
    }

    // TODO: implement velocities further
    lastKeyClicked = transposeKeyChromatically(lastKeyClicked, stepsIn);
    triggerKeys(oldKeys, false);
    triggerKeys(newKeys);
}

//===============================================================================================

void Keyboard::handleNoteOn(MidiKeyboardState* source, int midiChannel, int midiNote, float velocity)
{
    int keyTriggered = midiNote;

    Key* key = keys[keyTriggered];

    key->exPressed = true;

    Colour keyOnColour = keyOnColorsByChannel[midiChannel];
    if (!keyOnColour.isOpaque())
        keyOnColour = key->color.contrasting(0.75f);

    key->exInputColor = keyOnColour;
    key->isDirty = true;

    hasDirtyKeys = true;
}

void Keyboard::handleNoteOff(MidiKeyboardState* source, int midiChannel, int midiNote, float velocity)
{
    int keyTriggered = midiNote;
    Key* key = keys[keyTriggered];
    key->exPressed = false;
    key->isDirty = true;
    hasDirtyKeys = true;
}


text:
/*
  ==============================================================================

    VirtualKeyboardGrid.cpp
    Created: 17 Apr 2019 2:12:23pm
    Author:  Vincenzo

  ==============================================================================
*/

#include "VirtualKeyboardGrid.h"

using namespace VirtualKeyboard;

KeyboardPositioner::KeyboardPositioner(Component* parentIn, int numModeKeysIn)
    : parent(parentIn)
{
    setNumModeKeys(numModeKeysIn);
}

void KeyboardPositioner::parentResized()
{
    keyWidth = (parent->getWidth() - keyGap) / numModeKeys;
}

float KeyboardPositioner::getKeyWidth() const
{
    return keyWidth;
}

int KeyboardPositioner::getKeyGap() const
{
    return keyGap;
}

void KeyboardPositioner::setNumModeKeys(int numKeysIn)
{
    numModeKeys = numKeysIn;
    parentResized();
}

void KeyboardPositioner::setKeyGap(int keyGapIn)
{
    keyGap = keyGapIn;
    parentResized();
}

void KeyboardPositioner::setKeyPlacement(int keyPlacementTypeIn)
{
    keyPlacement = keyPlacementTypeIn;
}

void KeyboardPositioner::setLayerKeysWidthRatio(float widthRatioIn)
{
    baseWidthRatio = widthRatioIn;
}

void KeyboardPositioner::setLayerKeysHeightRatio(float heightRatioIn)
{
    baseHeightRatio = heightRatioIn;
}

void KeyboardPositioner::resizeKey(Key& key)
{
    float spread = 4; // TODO make setter
    float height, width;

    if (key.order == 0)
    {
        height = 1;
        width = 1;
    }
    else
    {
        float stepHeight = baseHeightRatio + (key.step - 2) / 100.0f * spread;
        width = baseWidthRatio;

        switch (keyPlacement)
        {
            case(KeyPlacementType::flat):
            {
                height = stepHeight - stepHeight * (key.order - 1) / (float)key.step * 1.125f;
                break;
            }

            case(KeyPlacementType::adjacent):
            {
                height = stepHeight;
                width /= (key.step - 1) * 0.9f; // mode keys of step 1 will not be in this else condition

                if (key.step == 2)
                    width *= 0.75f;

                break;
            }

            default: // nested keys
            {
                height = stepHeight - stepHeight * (key.order - 1) / (key.step * 1.08f);
                width -= (key.order - 1) * 0.1f;
                break;
            }
        }
    }

    key.setSize(width * keyWidth, height * parent->getHeight());
}

void KeyboardPositioner::placeKey(Key& key)
{

}

repo_name: vsicurella/SuperVirtualKeyboard

mime_type: text/x-c


text:
/*
  ==============================================================================

  ModeInfoDialog.h
  Vincenzo Sicurella

  ==============================================================================
*/

#pragma once

#include "../../../JuceLibraryCode/JuceHeader.h"
#include "../../CommonFunctions.h"
#include "../../Structures/Mode.h"

class ModeInfoDialog  : public Component,
                        public ChangeBroadcaster,
                        public TextEditor::Listener,
                        public Button::Listener,
                        public Slider::Listener
{
public:
    //==============================================================================
    ModeInfoDialog (Mode* modeIn);
    ~ModeInfoDialog();

    //==============================================================================

    void commitMode();

    void textEditorTextChanged(TextEditor& textEditor) override;
    void textEditorEscapeKeyPressed(TextEditor& textEditor) override {};
    void textEditorReturnKeyPressed(TextEditor& textEditor) override {};
    void textEditorFocusLost(TextEditor& textEditor) override {};

    void paint (Graphics& g) override;
    void resized() override {};
    void buttonClicked (Button* buttonThatWasClicked) override;
    void sliderValueChanged (Slider* sliderThatWasMoved) override;

private:
    Mode* modeOriginal;
    Mode modeWorking;
    ValueTree modeNode;

    int lastRotateAmt = 0;

    //==============================================================================
    std::unique_ptr<TextEditor> familyBox;
    std::unique_ptr<TextEditor> stepsBox;
    std::unique_ptr<TextEditor> infoBox;
    std::unique_ptr<Label> familyNameLbl;
    std::unique_ptr<Label> stepsLbl;
    std::unique_ptr<Label> intervalSizesLbl;
    std::unique_ptr<Label> nameLabel;
    std::unique_ptr<Label> modeSizeLbl;
    std::unique_ptr<Label> scaleSizeLbl;
    std::unique_ptr<ToggleButton> defaultNameBtn;
    std::unique_ptr<Label> infoLbl;
    std::unique_ptr<TextEditor> nameBox;
    std::unique_ptr<TextButton> saveButton;
    std::unique_ptr<Slider> rotateSld;
    std::unique_ptr<Label> modeRotateLbl;
    std::unique_ptr<Label> scaleSizeReadout;
    std::unique_ptr<Label> modeSizeReadout;
    std::unique_ptr<Label> intervalSizeReadout;
    std::unique_ptr<TextButton> closeButton;

    //==============================================================================
    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ModeInfoDialog)
};


text:
/*
  ==============================================================================

  ModeInfoDialog.cpp
  Vincenzo Sicurella

  ==============================================================================
*/

#include "ModeInfoDialog.h"

//==============================================================================
ModeInfoDialog::ModeInfoDialog (Mode* modeIn)
    : modeOriginal(modeIn), modeWorking(Mode(modeIn->modeNode)), modeNode(modeWorking.modeNode)
{
    familyBox.reset (new TextEditor ("Family Box"));
    addAndMakeVisible (familyBox.get());
    familyBox->setMultiLine (false);
    familyBox->setReturnKeyStartsNewLine (false);
    familyBox->setReadOnly (false);
    familyBox->setScrollbarsShown (true);
    familyBox->setCaretVisible (true);
    familyBox->setPopupMenuEnabled (true);
    familyBox->setText (TRANS("Meantone"));

    familyBox->setBounds (8, 168, 192, 24);

    stepsBox.reset (new TextEditor ("Steps Box"));
    addAndMakeVisible (stepsBox.get());
    stepsBox->setMultiLine (false);
    stepsBox->setReturnKeyStartsNewLine (false);
    stepsBox->setReadOnly (true);
    stepsBox->setScrollbarsShown (true);
    stepsBox->setCaretVisible (false);
    stepsBox->setPopupMenuEnabled (true);
    stepsBox->setText (TRANS("2 2 1 2 2 2 1"));

    stepsBox->setBounds (8, 40, 192, 24);

    infoBox.reset (new TextEditor ("Info Box"));
    addAndMakeVisible (infoBox.get());
    infoBox->setMultiLine (true);
    infoBox->setReturnKeyStartsNewLine (false);
    infoBox->setReadOnly (false);
    infoBox->setScrollbarsShown (true);
    infoBox->setCaretVisible (true);
    infoBox->setPopupMenuEnabled (true);
    infoBox->setText (TRANS("Ever hear of it?"));

    infoBox->setBounds (8, 336, 320, 128);

    familyNameLbl.reset (new Label ("Family Name Label",
                                    TRANS("Temperament Family:\n")));
    addAndMakeVisible (familyNameLbl.get());
    familyNameLbl->setFont (Font (15.00f, Font::plain).withTypefaceStyle ("Regular"));
    familyNameLbl->setJustificationType (Justification::centredLeft);
    familyNameLbl->setEditable (false, false, false);
    familyNameLbl->setColour (TextEditor::textColourId, Colours::black);
    familyNameLbl->setColour (TextEditor::backgroundColourId, Colour (0x00000000));

    familyNameLbl->setBounds (8, 136, 150, 24);

    stepsLbl.reset (new Label ("Steps Label",
                               TRANS("Steps:\n")));
    addAndMakeVisible (stepsLbl.get());
    stepsLbl->setFont (Font (15.00f, Font::plain).withTypefaceStyle ("Regular"));
    stepsLbl->setJustificationType (Justification::centredLeft);
    stepsLbl->setEditable (false, false, false);
    stepsLbl->setColour (TextEditor::textColourId, Colours::black);
    stepsLbl->setColour (TextEditor::backgroundColourId, Colour (0x00000000));

    stepsLbl->setBounds (8, 8, 56, 24);

    intervalSizesLbl.reset (new Label ("Interval Sizes Label",
                                       TRANS("Interval Sizes:")));
    addAndMakeVisible (intervalSizesLbl.get());
    intervalSizesLbl->setFont (Font (15.00f, Font::plain).withTypefaceStyle ("Regular"));
    intervalSizesLbl->setJustificationType (Justification::centredLeft);
    intervalSizesLbl->setEditable (false, false, false);
    intervalSizesLbl->setColour (TextEditor::textColourId, Colours::black);
    intervalSizesLbl->setColour (TextEditor::backgroundColourId, Colour (0x00000000));

    intervalSizesLbl->setBounds (8, 272, 95, 24);

    nameLabel.reset (new Label ("Name Label",
                                TRANS("Mode Name:")));
    addAndMakeVisible (nameLabel.get());
    nameLabel->setFont (Font (15.00f, Font::plain).withTypefaceStyle ("Regular"));
    nameLabel->setJustificationType (Justification::centredLeft);
    nameLabel->setEditable (false, false, false);
    nameLabel->setColour (TextEditor::textColourId, Colours::black);
    nameLabel->setColour (TextEditor::backgroundColourId, Colour (0x00000000));

    nameLabel->setBounds (9, 73, 96, 24);

    modeSizeLbl.reset (new Label ("Mode Size Label",
                                  TRANS("Mode Size:")));
    addAndMakeVisible (modeSizeLbl.get());
    modeSizeLbl->setFont (Font (15.00f, Font::plain).withTypefaceStyle ("Regular"));
    modeSizeLbl->setJustificationType (Justification::centredLeft);
    modeSizeLbl->setEditable (false, false, false);
    modeSizeLbl->setColour (TextEditor::textColourId, Colours::black);
    modeSizeLbl->setColour (TextEditor::backgroundColourId, Colour (0x00000000));

    modeSizeLbl->setBounds (8, 240, 80, 24);

    scaleSizeLbl.reset (new Label ("Scale Size Label",
                                   TRANS("Scale Size:")));
    addAndMakeVisible (scaleSizeLbl.get());
    scaleSizeLbl->setFont (Font (15.00f, Font::plain).withTypefaceStyle ("Regular"));
    scaleSizeLbl->setJustificationType (Justification::centredLeft);
    scaleSizeLbl->setEditable (false, false, false);
    scaleSizeLbl->setColour (TextEditor::textColourId, Colours::black);
    scaleSizeLbl->setColour (TextEditor::backgroundColourId, Colour (0x00000000));

    scaleSizeLbl->setBounds (8, 208, 71, 24);

    defaultNameBtn.reset (new ToggleButton ("Default Name Button"));
    addAndMakeVisible (defaultNameBtn.get());
    defaultNameBtn->setButtonText (TRANS("Use Default"));
    defaultNameBtn->addListener (this);
    defaultNameBtn->setToggleState (true, dontSendNotification);

    defaultNameBtn->setBounds (217, 105, 111, 24);

    infoLbl.reset (new Label ("Info Label",
                              TRANS("Info:")));
    addAndMakeVisible (infoLbl.get());
    infoLbl->setFont (Font (15.00f, Font::plain).withTypefaceStyle ("Regular"));
    infoLbl->setJustificationType (Justification::centredLeft);
    infoLbl->setEditable (false, false, false);
    infoLbl->setColour (TextEditor::textColourId, Colours::black);
    infoLbl->setColour (TextEditor::backgroundColourId, Colour (0x00000000));

    infoLbl->setBounds (8, 304, 40, 24);

    nameBox.reset (new TextEditor ("Name Box"));
    addAndMakeVisible (nameBox.get());
    nameBox->setMultiLine (false);
    nameBox->setReturnKeyStartsNewLine (false);
    nameBox->setReadOnly (false);
    nameBox->setScrollbarsShown (true);
    nameBox->setCaretVisible (true);
    nameBox->setPopupMenuEnabled (true);
    nameBox->setText (TRANS("Meantone[7] 12"));

    nameBox->setBounds (9, 105, 192, 24);

    saveButton.reset (new TextButton ("Save Button"));
    addAndMakeVisible (saveButton.get());
    saveButton->setButtonText (TRANS("Save"));
    saveButton->addListener (this);

    saveButton->setBounds (32, 488, 104, 24);

    rotateSld.reset (new Slider ("Rotate Slider"));
    addAndMakeVisible (rotateSld.get());
    rotateSld->setRange (-3, 4, 1);
    rotateSld->setSliderStyle (Slider::IncDecButtons);
    rotateSld->setTextBoxStyle (Slider::TextBoxLeft, false, 48, 20);
    rotateSld->addListener (this);

    rotateSld->setBounds (216, 40, 96, 24);

    modeRotateLbl.reset (new Label ("Mode Rotate Label",
                                    TRANS("Shift Mode:")));
    addAndMakeVisible (modeRotateLbl.get());
    modeRotateLbl->setFont (Font (15.00f, Font::plain).withTypefaceStyle ("Regular"));
    modeRotateLbl->setJustificationType (Justification::centredLeft);
    modeRotateLbl->setEditable (false, false, false);
    modeRotateLbl->setColour (TextEditor::textColourId, Colours::black);
    modeRotateLbl->setColour (TextEditor::backgroundColourId, Colour (0x00000000));

    modeRotateLbl->setBounds (216, 8, 103, 24);

    scaleSizeReadout.reset (new Label ("Scale Size Readout",
                                       TRANS("12\n")));
    addAndMakeVisible (scaleSizeReadout.get());
    scaleSizeReadout->setFont (Font (15.00f, Font::plain).withTypefaceStyle ("Regular"));
    scaleSizeReadout->setJustificationType (Justification::centredLeft);
    scaleSizeReadout->setEditable (false, false, false);
    scaleSizeReadout->setColour (TextEditor::textColourId, Colours::black);
    scaleSizeReadout->setColour (TextEditor::backgroundColourId, Colour (0x00000000));

    scaleSizeReadout->setBounds (88, 208, 31, 24);

    modeSizeReadout.reset (new Label ("Mode Size Readout",
                                      TRANS("7")));
    addAndMakeVisible (modeSizeReadout.get());
    modeSizeReadout->setFont (Font (15.00f, Font::plain).withTypefaceStyle ("Regular"));
    modeSizeReadout->setJustificationType (Justification::centredLeft);
    modeSizeReadout->setEditable (false, false, false);
    modeSizeReadout->setColour (TextEditor::textColourId, Colours::black);
    modeSizeReadout->setColour (TextEditor::backgroundColourId, Colour (0x00000000));

    modeSizeReadout->setBounds (88, 240, 103, 24);

    intervalSizeReadout.reset (new Label ("Interval Size Readout",
                                          TRANS("7, 5")));
    addAndMakeVisible (intervalSizeReadout.get());
    intervalSizeReadout->setFont (Font (15.00f, Font::plain).withTypefaceStyle ("Regular"));
    intervalSizeReadout->setJustificationType (Justification::centredLeft);
    intervalSizeReadout->setEditable (false, false, false);
    intervalSizeReadout->setColour (TextEditor::textColourId, Colours::black);
    intervalSizeReadout->setColour (TextEditor::backgroundColourId, Colour (0x00000000));

    intervalSizeReadout->setBounds (104, 272, 143, 24);

    closeButton.reset (new TextButton ("closeButton"));
    addAndMakeVisible (closeButton.get());
    closeButton->setButtonText (TRANS("Close"));
    closeButton->addListener (this);

    closeButton->setBounds (192, 488, 104, 24);

    rotateSld->setIncDecButtonsMode(Slider::IncDecButtonMode::incDecButtonsDraggable_Horizontal);

    familyBox->addListener(this);

    stepsBox->setText(modeWorking.getStepsString());
    familyBox->setText(modeWorking.getFamily());

    nameBox->setText(modeWorking.getName());
    nameBox->setEnabled(false);

    defaultNameBtn->setClickingTogglesState(true);
    if (modeWorking.getName() != modeWorking.getDescription())
        defaultNameBtn->setToggleState(false, sendNotification);

    scaleSizeReadout->setText(String(modeWorking.getScaleSize()), dontSendNotification);
    modeSizeReadout->setText(String(modeWorking.getModeSize()), dontSendNotification);

    intervalSizeReadout->setText(arrayToString(modeWorking.getIntervalSizeCount()), dontSendNotification);

    infoBox->setText(modeWorking.getInfo());

    if (modeWorking.getModeSize() > 1)
        rotateSld->setRange(-(modeWorking.getModeSize() - 1), modeWorking.getModeSize() - 1, 1);
    else
        rotateSld->setEnabled(false);

    setSize (340, 525);
}

ModeInfoDialog::~ModeInfoDialog()
{
    removeAllChangeListeners();

    familyBox = nullptr;
    stepsBox = nullptr;
    infoBox = nullptr;
    familyNameLbl = nullptr;
    stepsLbl = nullptr;
    intervalSizesLbl = nullptr;
    nameLabel = nullptr;
    modeSizeLbl = nullptr;
    scaleSizeLbl = nullptr;
    defaultNameBtn = nullptr;
    infoLbl = nullptr;
    nameBox = nullptr;
    saveButton = nullptr;
    rotateSld = nullptr;
    modeRotateLbl = nullptr;
    scaleSizeReadout = nullptr;
    modeSizeReadout = nullptr;
    intervalSizeReadout = nullptr;
    closeButton = nullptr;
}

//==============================================================================
void ModeInfoDialog::paint (Graphics& g)
{
    g.fillAll (Colour (0xff323e44));
}

void ModeInfoDialog::buttonClicked (Button* buttonThatWasClicked)
{
    if (buttonThatWasClicked == defaultNameBtn.get())
    {
        if (defaultNameBtn->getToggleState())
        {
            nameBox->setEnabled(false);
            modeWorking.setFamily(familyBox->getText());
            modeNode.setProperty(IDs::family, familyBox->getText(), nullptr);
            nameBox->setText(modeWorking.getDescription());
        }
        else
        {
            nameBox->setEnabled(true);
        }
    }
    else if (buttonThatWasClicked == saveButton.get())
    {
        commitMode();
        sendChangeMessage();
        getParentComponent()->exitModalState(0);
    }
    else if (buttonThatWasClicked == closeButton.get())
    {
        getParentComponent()->exitModalState(0);
    }
}

void ModeInfoDialog::sliderValueChanged (Slider* sliderThatWasMoved)
{
    if (sliderThatWasMoved == rotateSld.get())
    {
        modeWorking.rotate(lastRotateAmt - sliderThatWasMoved->getValue());
        lastRotateAmt = sliderThatWasMoved->getValue();

        modeNode.setProperty(IDs::stepString, modeWorking.getStepsString(), nullptr);
        stepsBox->setText(modeWorking.getStepsString());
    }
}

void ModeInfoDialog::textEditorTextChanged(TextEditor& textEditor)
{
    if (textEditor.getName() == familyBox->getName())
    {
        if (defaultNameBtn->getToggleState())
        {
            modeWorking.setFamily(familyBox->getText());
            nameBox->setText(modeWorking.getDescription());
        }
    }

}

void ModeInfoDialog::commitMode()
{
    modeNode.setProperty(IDs::modeName, nameBox->getText(), nullptr);
    modeNode.setProperty(IDs::family, familyBox->getText(), nullptr);
    modeNode.setProperty(IDs::modeInfo, infoBox->getText(), nullptr);

    modeOriginal->restoreNode(modeNode);
}


text:
/*
  ==============================================================================

    ExportKbmDialog.h
    Created: 24 Oct 2020 4:47:57pm
    Author:  Vincenzo

  ==============================================================================
*/

#pragma once

#include <JuceHeader.h>
#include "../Components/LabelledComponent.h"
#include "../../File IO/KbmWriter.h"

//==============================================================================
/*
*/
class ExportKbmDialog  : public Component
{
public:
    ExportKbmDialog(ValueTree mappingNodeIn, const Mode& modeInput, const Mode& modeOutput, const ModeMapper& mapperIn)
        : mappingNode(mappingNodeIn), inputMode(modeInput), outputMode(modeOutput), mapper(mapperIn)
    {
        if (!mappingNode.isValid())
            mappingNode = ValueTree(IDs::midiMapNode);

        refNoteSld = new Slider(Slider::SliderStyle::IncDecButtons, Slider::TextBoxLeft);
        refNoteSld->setRange(0, 127, 1);
        refNoteSld->setTextBoxStyle(Slider::TextBoxLeft, false, 48, 24);
        refNoteSldLabel.reset(new LabelledComponent(*refNoteSld, "Tuning Reference MIDI Note:"));
        addAndMakeVisible(refNoteSldLabel.get());

        refFreqEditor = new TextEditor("ReferenceFreqEditor");
        refFreqEditor->setInputRestrictions(0, "123456890.");
        refFreqEditLabel.reset(new LabelledComponent(*refFreqEditor, "Tuning Reference Frequency:"));
        addAndMakeVisible(refFreqEditLabel.get());

        autoFreqButton.reset(new TextButton("AutoFreqButton", "Use a standard tuning frequency based on selected MIDI note."));
        autoFreqButton->setButtonText("Auto");
        autoFreqButton->onClick = [&]() { refFreqEditor->setText(String(getStdFrequency(refNoteSld->getValue()))); };
        addAndMakeVisible(autoFreqButton.get());

        saveButton.reset(new TextButton("SaveButton"));
        saveButton->setButtonText("Save");
        saveButton->onClick = [&]() { ExportKbmDialog::saveAndClose(); };
        addAndMakeVisible(saveButton.get());

        cancelButton.reset(new TextButton("CancelButton"));
        cancelButton->setButtonText("Cancel");
        cancelButton->onClick = [&]() { delete getParentComponent(); };
        addAndMakeVisible(cancelButton.get());

        if (mappingNode.hasProperty(IDs::tuningRootNote))
            refNoteSld->setValue((int)mappingNode[IDs::tuningRootNote]);
        else
            refNoteSld->setValue(69);

        if (mappingNode.hasProperty(IDs::tuningRootFreq))
            refFreqEditor->setText(mappingNode[IDs::tuningRootFreq].toString());
        else
            refFreqEditor->setText("440.0");
    }

    ~ExportKbmDialog() override
    {
    }

    void paint (juce::Graphics& g) override
    {
        g.fillAll (getLookAndFeel().findColour (juce::ResizableWindow::backgroundColourId));   // clear the background

        g.setColour (juce::Colours::grey);
        g.drawRect (getLocalBounds(), 1);   // draw an outline around the component
    }

    void resized() override
    {
        refNoteSldLabel->setComponentSize(88, 24);
        refNoteSldLabel->setTopLeftPosition(0, 8);
        refFreqEditLabel->setComponentSize(80, 24);
        refFreqEditLabel->setTopLeftPosition(0, refNoteSldLabel->getBottom() + 8);

        autoFreqButton->setBounds(refFreqEditLabel->getRight() + 4, refFreqEditLabel->getY(), 44, 24);

        double unit = proportionOfWidth(1 / 17.0f);
        saveButton->setBounds(unit * 2, getHeight() - 40, unit * 5, 36);
        cancelButton->setBounds(unit * 10, saveButton->getY(), unit * 5, 36);
    }

    void saveAndClose()
    {
        bool success = false;

        File initialDirectory;
        if (mappingNode.hasProperty(IDs::kbmFileLocation) && File::isAbsolutePath(mappingNode[IDs::kbmFileLocation].toString()))
            initialDirectory = File(mappingNode[IDs::kbmFileLocation]);

        FileChooser chooser("Save KBM file...", initialDirectory, "*.kbm");

        if (chooser.browseForFileToSave(true))
        {
            KbmWriter kbm = KbmWriter::fromModes(
                &inputMode, &outputMode, mapper, 0, 127, -1,
                refNoteSld->getValue(), refFreqEditor->getText().getDoubleValue()
            );

            if (kbm.writeTo(chooser.getResult()))
            {
                success = true;
                mappingNode.setProperty(IDs::tuningRootNote, refNoteSld->getValue(), nullptr);
                mappingNode.setProperty(IDs::tuningRootFreq, refFreqEditor->getText().getDoubleValue(), nullptr);
                mappingNode.setProperty(IDs::kbmFileLocation, chooser.getResult().getParentDirectory().getFullPathName(), nullptr);
            }
        }

        if (!success)
        {
            AlertWindow::showMessageBox(AlertWindow::AlertIconType::WarningIcon, "File Write Error", "Could not write .kbm file", "Ok", this);
        }

        delete getParentComponent();
    }

private:

    ValueTree mappingNode;

    const Mode& inputMode;
    const Mode& outputMode;
    const ModeMapper& mapper;

    std::unique_ptr<LabelledComponent> refNoteSldLabel;
    Slider* refNoteSld;

    std::unique_ptr<LabelledComponent> refFreqEditLabel;
    TextEditor* refFreqEditor;

    std::unique_ptr<TextButton> autoFreqButton;
    std::unique_ptr<TextButton> saveButton;
    std::unique_ptr<TextButton> cancelButton;

    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ExportKbmDialog)
};


text:
/*
  ==============================================================================

  Created with Projucer version: 5.4.4

  ------------------------------------------------------------------------------

  The Projucer is part of the JUCE library.
  Copyright (c) 2017 - ROLI Ltd.

  ==============================================================================
*/

#pragma once

#include "../../../JuceLibraryCode/JuceHeader.h"

#include "../../CommonFunctions.h"
#include "../../Structures/ModeMapper.h"
#include "../Components/ReferencedComboBox.h"

//==============================================================================

class MapByOrderDialog  : public Component,
                          public ComboBox::Listener,
                          public Slider::Listener
{
public:
    //==============================================================================
    MapByOrderDialog (ModeMapper* modeMapperIn, Mode* mode1In, Mode* mode2In);
    ~MapByOrderDialog();

    //==============================================================================

    void paint (Graphics& g) override;
    void resized() override;
    void comboBoxChanged (ComboBox* comboBoxThatHasChanged) override;
    void sliderValueChanged (Slider* sliderThatWasMoved) override;

private:

    ModeMapper* modeMapper;
    Mode* mode1;
    Mode* mode2;

    int boxW = 10;
    int boxH = 8;

    //==============================================================================
    std::unique_ptr<ComboBox> mode1OrderBox;
    std::unique_ptr<ComboBox> mode2OrderBox;
    std::unique_ptr<Label> orderSelectionLbl;
    std::unique_ptr<Slider> orderOffsetSld1;
    std::unique_ptr<Slider> orderOffsetSld2;
    std::unique_ptr<Label> offsetLabel;
    std::unique_ptr<Label> inputLabel;
    std::unique_ptr<Label> outputLabel;

    //==============================================================================
    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MapByOrderDialog)
};


text:
/*
  ==============================================================================

  Created with Projucer version: 5.4.4

  ------------------------------------------------------------------------------

  The Projucer is part of the JUCE library.
  Copyright (c) 2017 - ROLI Ltd.

  ==============================================================================
*/

#include "MapByOrderDialog.h"

//==============================================================================
MapByOrderDialog::MapByOrderDialog (ModeMapper* modeMapperIn, Mode* mode1In, Mode* mode2In)
    : modeMapper(modeMapperIn)
{

    mode1OrderBox.reset (new ComboBox ("Mode 1 Order Box"));
    addAndMakeVisible (mode1OrderBox.get());
    mode1OrderBox->setEditableText (false);
    mode1OrderBox->setJustificationType (Justification::centredLeft);
    mode1OrderBox->setTextWhenNothingSelected (String());
    mode1OrderBox->setTextWhenNoChoicesAvailable (TRANS("(no choices)"));
    mode1OrderBox->addListener (this);

    mode1OrderBox->setBounds (76, 25, 63, 24);

    mode2OrderBox.reset (new ComboBox ("Mode 2 Order Box"));
    addAndMakeVisible (mode2OrderBox.get());
    mode2OrderBox->setEditableText (false);
    mode2OrderBox->setJustificationType (Justification::centredLeft);
    mode2OrderBox->setTextWhenNothingSelected (String());
    mode2OrderBox->setTextWhenNoChoicesAvailable (TRANS("(no choices)"));
    mode2OrderBox->addListener (this);

    mode2OrderBox->setBounds (156, 25, 63, 24);

    orderSelectionLbl.reset (new Label ("Order Label",
                                        TRANS("Layer:")));
    addAndMakeVisible (orderSelectionLbl.get());
    orderSelectionLbl->setFont (Font (15.00f, Font::plain).withTypefaceStyle ("Regular"));
    orderSelectionLbl->setJustificationType (Justification::centredLeft);
    orderSelectionLbl->setEditable (false, false, false);
    orderSelectionLbl->setColour (TextEditor::textColourId, Colours::black);
    orderSelectionLbl->setColour (TextEditor::backgroundColourId, Colour (0x00000000));

    orderSelectionLbl->setBounds (20, 24, 48, 24);

    orderOffsetSld1.reset (new Slider ("Order Offset Slider 1"));
    addAndMakeVisible (orderOffsetSld1.get());
    orderOffsetSld1->setRange (0, 10, 1);
    orderOffsetSld1->setSliderStyle (Slider::IncDecButtons);
    orderOffsetSld1->setTextBoxStyle (Slider::TextBoxAbove, false, 80, 30);
    orderOffsetSld1->addListener (this);

    orderOffsetSld1->setBounds (76, 66, 64, 56);

    orderOffsetSld2.reset (new Slider ("Order Offset Slider 2"));
    addAndMakeVisible (orderOffsetSld2.get());
    orderOffsetSld2->setRange (0, 10, 1);
    orderOffsetSld2->setSliderStyle (Slider::IncDecButtons);
    orderOffsetSld2->setTextBoxStyle (Slider::TextBoxAbove, false, 80, 30);
    orderOffsetSld2->addListener (this);

    orderOffsetSld2->setBounds (156, 66, 64, 56);

    offsetLabel.reset (new Label ("new label",
                            TRANS("Degree\n"
                            "Offsets:")));
    addAndMakeVisible (offsetLabel.get());
    offsetLabel->setFont (Font (15.00f, Font::plain).withTypefaceStyle ("Regular"));
    offsetLabel->setJustificationType (Justification::centredLeft);
    offsetLabel->setEditable (false, false, false);
    offsetLabel->setColour (TextEditor::textColourId, Colours::black);
    offsetLabel->setColour (TextEditor::backgroundColourId, Colour (0x00000000));
    offsetLabel->setBounds (12, 58, 64, 40);

    inputLabel.reset(new Label("Input Label", TRANS("In")));
    addAndMakeVisible(inputLabel.get());
    inputLabel->setJustificationType(Justification::centred);
    inputLabel->setBounds(mode1OrderBox->getX(), mode1OrderBox->getY() - 28, mode1OrderBox->getWidth(), 30);

    outputLabel.reset(new Label("Output Label", TRANS("Out")));
    addAndMakeVisible(outputLabel.get());
    outputLabel->setJustificationType(Justification::centred);
    outputLabel->setBounds(mode2OrderBox->getX(), mode2OrderBox->getY() - 28, mode2OrderBox->getWidth(), 30);

    mode1 = mode1In;
    mode2 = mode2In;

    mode1OrderBox->clear();
    mode2OrderBox->clear();

    for (int i = 0; i < mode1->getMaxStep(); i++)
        mode1OrderBox->addItem(String(i), i+1);

    for (int i = 0; i < mode2->getMaxStep(); i++)
        mode2OrderBox->addItem(String(i), i+1);

    mode1OrderBox->setSelectedId(modeMapper->getMode1OrderNum() + 1, dontSendNotification);
    mode2OrderBox->setSelectedId(modeMapper->getMode2OrderNum() + 1, dontSendNotification);
    orderOffsetSld1->setValue(modeMapper->getMode1OrderOffset(), dontSendNotification);
    orderOffsetSld2->setValue(modeMapper->getMode2OrderOffset(), dontSendNotification);

    setSize (250, 130);
}

MapByOrderDialog::~MapByOrderDialog()
{
    mode1OrderBox = nullptr;
    mode2OrderBox = nullptr;
    orderSelectionLbl = nullptr;
    orderOffsetSld1 = nullptr;
    orderOffsetSld2 = nullptr;
    offsetLabel = nullptr;
}

//==============================================================================
void MapByOrderDialog::paint (Graphics& g)
{
    g.fillAll (Colour (0xff323e44));
}

void MapByOrderDialog::resized()
{
}

void MapByOrderDialog::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
{
    if (comboBoxThatHasChanged == mode1OrderBox.get())
    {
        modeMapper->setMode1OrderNum(mode1OrderBox->getSelectedId()-1);
    }
    else if (comboBoxThatHasChanged == mode2OrderBox.get())
    {
        modeMapper->setMode2OrderNum(mode2OrderBox->getSelectedId()-1);
    }
}

void MapByOrderDialog::sliderValueChanged (Slider* sliderThatWasMoved)
{

    if (sliderThatWasMoved == orderOffsetSld1.get())
    {
        modeMapper->setMode1OrderOffset(orderOffsetSld1->getValue());
    }
    else if (sliderThatWasMoved == orderOffsetSld2.get())
    {
        modeMapper->setMode2OrderOffset(orderOffsetSld2->getValue());
    }
}


text:
Creative Commons Legal Code

CC0 1.0 Universal

    CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
    LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
    ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
    INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
    REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
    PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
    THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
    HEREUNDER.

Statement of Purpose

The laws of most jurisdictions throughout the world automatically confer
exclusive Copyright and Related Rights (defined below) upon the creator
and subsequent owner(s) (each and all, an "owner") of an original work of
authorship and/or a database (each, a "Work").

Certain owners wish to permanently relinquish those rights to a Work for
the purpose of contributing to a commons of creative, cultural and
scientific works ("Commons") that the public can reliably and without fear
of later claims of infringement build upon, modify, incorporate in other
works, reuse and redistribute as freely as possible in any form whatsoever
and for any purposes, including without limitation commercial purposes.
These owners may contribute to the Commons to promote the ideal of a free
culture and the further production of creative, cultural and scientific
works, or to gain reputation or greater distribution for their Work in
part through the use and efforts of others.

For these and/or other purposes and motivations, and without any
expectation of additional consideration or compensation, the person
associating CC0 with a Work (the "Affirmer"), to the extent that he or she
is an owner of Copyright and Related Rights in the Work, voluntarily
elects to apply CC0 to the Work and publicly distribute the Work under its
terms, with knowledge of his or her Copyright and Related Rights in the
Work and the meaning and intended legal effect of CC0 on those rights.

1. Copyright and Related Rights. A Work made available under CC0 may be
protected by copyright and related or neighboring rights ("Copyright and
Related Rights"). Copyright and Related Rights include, but are not
limited to, the following:

  i. the right to reproduce, adapt, distribute, perform, display,
     communicate, and translate a Work;
 ii. moral rights retained by the original author(s) and/or performer(s);
iii. publicity and privacy rights pertaining to a person's image or
     likeness depicted in a Work;
 iv. rights protecting against unfair competition in regards to a Work,
     subject to the limitations in paragraph 4(a), below;
  v. rights protecting the extraction, dissemination, use and reuse of data
     in a Work;
 vi. database rights (such as those arising under Directive 96/9/EC of the
     European Parliament and of the Council of 11 March 1996 on the legal
     protection of databases, and under any national implementation
     thereof, including any amended or successor version of such
     directive); and
vii. other similar, equivalent or corresponding rights throughout the
     world based on applicable law or treaty, and any national
     implementations thereof.

2. Waiver. To the greatest extent permitted by, but not in contravention
of, applicable law, Affirmer hereby overtly, fully, permanently,
irrevocably and unconditionally waives, abandons, and surrenders all of
Affirmer's Copyright and Related Rights and associated claims and causes
of action, whether now known or unknown (including existing as well as
future claims and causes of action), in the Work (i) in all territories
worldwide, (ii) for the maximum duration provided by applicable law or
treaty (including future time extensions), (iii) in any current or future
medium and for any number of copies, and (iv) for any purpose whatsoever,
including without limitation commercial, advertising or promotional
purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
member of the public at large and to the detriment of Affirmer's heirs and
successors, fully intending that such Waiver shall not be subject to
revocation, rescission, cancellation, termination, or any other legal or
equitable action to disrupt the quiet enjoyment of the Work by the public
as contemplated by Affirmer's express Statement of Purpose.

3. Public License Fallback. Should any part of the Waiver for any reason
be judged legally invalid or ineffective under applicable law, then the
Waiver shall be preserved to the maximum extent permitted taking into
account Affirmer's express Statement of Purpose. In addition, to the
extent the Waiver is so judged Affirmer hereby grants to each affected
person a royalty-free, non transferable, non sublicensable, non exclusive,
irrevocable and unconditional license to exercise Affirmer's Copyright and
Related Rights in the Work (i) in all territories worldwide, (ii) for the
maximum duration provided by applicable law or treaty (including future
time extensions), (iii) in any current or future medium and for any number
of copies, and (iv) for any purpose whatsoever, including without
limitation commercial, advertising or promotional purposes (the
"License"). The License shall be deemed effective as of the date CC0 was
applied by Affirmer to the Work. Should any part of the License for any
reason be judged legally invalid or ineffective under applicable law, such
partial invalidity or ineffectiveness shall not invalidate the remainder
of the License, and in such case Affirmer hereby affirms that he or she
will not (i) exercise any of his or her remaining Copyright and Related
Rights in the Work or (ii) assert any associated claims and causes of
action with respect to the Work, in either case contrary to Affirmer's
express Statement of Purpose.

4. Limitations and Disclaimers.

 a. No trademark or patent rights held by Affirmer are waived, abandoned,
    surrendered, licensed or otherwise affected by this document.
 b. Affirmer offers the Work as-is and makes no representations or
    warranties of any kind concerning the Work, express, implied,
    statutory or otherwise, including without limitation warranties of
    title, merchantability, fitness for a particular purpose, non
    infringement, or the absence of latent or other defects, accuracy, or
    the present or absence of errors, whether or not discoverable, all to
    the greatest extent permissible under applicable law.
 c. Affirmer disclaims responsibility for clearing rights of other persons
    that may apply to the Work or any use thereof, including without
    limitation any person's Copyright and Related Rights in the Work.
    Further, Affirmer disclaims responsibility for obtaining any necessary
    consents, permissions or other rights required for any use of the
    Work.
 d. Affirmer understands and acknowledges that Creative Commons is not a
    party to this document and has no duty or obligation with respect to
    this CC0 or use of the Work.

repo_name: kdeldycke/awesome-iam

mime_type: text/plain