text:
use std::io;
use std::mem;

use winapi::shared::minwindef::WORD;
use winapi::um::consoleapi::{GetConsoleMode, SetConsoleMode};
use winapi::um::wincon::{
    self, GetConsoleScreenBufferInfo, SetConsoleTextAttribute,
    CONSOLE_SCREEN_BUFFER_INFO, FOREGROUND_BLUE as FG_BLUE,
    FOREGROUND_GREEN as FG_GREEN, FOREGROUND_INTENSITY as FG_INTENSITY,
    FOREGROUND_RED as FG_RED,
};

use crate::{AsHandleRef, HandleRef};

const FG_CYAN: WORD = FG_BLUE | FG_GREEN;
const FG_MAGENTA: WORD = FG_BLUE | FG_RED;
const FG_YELLOW: WORD = FG_GREEN | FG_RED;
const FG_WHITE: WORD = FG_BLUE | FG_GREEN | FG_RED;

/// Query the given handle for information about the console's screen buffer.
///
/// The given handle should represent a console. Otherwise, an error is
/// returned.
///
/// This corresponds to calling [`GetConsoleScreenBufferInfo`].
///
/// [`GetConsoleScreenBufferInfo`]: https://docs.microsoft.com/en-us/windows/console/getconsolescreenbufferinfo
pub fn screen_buffer_info<H: AsHandleRef>(
    h: H,
) -> io::Result<ScreenBufferInfo> {
    unsafe {
        let mut info: CONSOLE_SCREEN_BUFFER_INFO = mem::zeroed();
        let rc = GetConsoleScreenBufferInfo(h.as_raw(), &mut info);
        if rc == 0 {
            return Err(io::Error::last_os_error());
        }
        Ok(ScreenBufferInfo(info))
    }
}

/// Set the text attributes of the console represented by the given handle.
///
/// This corresponds to calling [`SetConsoleTextAttribute`].
///
/// [`SetConsoleTextAttribute`]: https://docs.microsoft.com/en-us/windows/console/setconsoletextattribute
pub fn set_text_attributes<H: AsHandleRef>(
    h: H,
    attributes: u16,
) -> io::Result<()> {
    if unsafe { SetConsoleTextAttribute(h.as_raw(), attributes) } == 0 {
        Err(io::Error::last_os_error())
    } else {
        Ok(())
    }
}

/// Query the mode of the console represented by the given handle.
///
/// This corresponds to calling [`GetConsoleMode`], which describes the return
/// value.
///
/// [`GetConsoleMode`]: https://docs.microsoft.com/en-us/windows/console/getconsolemode
pub fn mode<H: AsHandleRef>(h: H) -> io::Result<u32> {
    let mut mode = 0;
    if unsafe { GetConsoleMode(h.as_raw(), &mut mode) } == 0 {
        Err(io::Error::last_os_error())
    } else {
        Ok(mode)
    }
}

/// Set the mode of the console represented by the given handle.
///
/// This corresponds to calling [`SetConsoleMode`], which describes the format
/// of the mode parameter.
///
/// [`SetConsoleMode`]: https://docs.microsoft.com/en-us/windows/console/setconsolemode
pub fn set_mode<H: AsHandleRef>(h: H, mode: u32) -> io::Result<()> {
    if unsafe { SetConsoleMode(h.as_raw(), mode) } == 0 {
        Err(io::Error::last_os_error())
    } else {
        Ok(())
    }
}

/// Represents console screen buffer information such as size, cursor position
/// and styling attributes.
///
/// This wraps a [`CONSOLE_SCREEN_BUFFER_INFO`].
///
/// [`CONSOLE_SCREEN_BUFFER_INFO`]: https://docs.microsoft.com/en-us/windows/console/console-screen-buffer-info-str
#[derive(Clone)]
pub struct ScreenBufferInfo(CONSOLE_SCREEN_BUFFER_INFO);

impl ScreenBufferInfo {
    /// Returns the size of the console screen buffer, in character columns and
    /// rows.
    ///
    /// This corresponds to `dwSize`.
    pub fn size(&self) -> (i16, i16) {
        (self.0.dwSize.X, self.0.dwSize.Y)
    }

    /// Returns the position of the cursor in terms of column and row
    /// coordinates of the console screen buffer.
    ///
    /// This corresponds to `dwCursorPosition`.
    pub fn cursor_position(&self) -> (i16, i16) {
        (self.0.dwCursorPosition.X, self.0.dwCursorPosition.Y)
    }

    /// Returns the character attributes associated with this console.
    ///
    /// This corresponds to `wAttributes`.
    ///
    /// See [`char info`] for more details.
    ///
    /// [`char info`]: https://docs.microsoft.com/en-us/windows/console/char-info-str
    pub fn attributes(&self) -> u16 {
        self.0.wAttributes
    }

    /// Returns the maximum size of the console window, in character columns
    /// and rows, given the current screen buffer size and font and the screen
    /// size.
    pub fn max_window_size(&self) -> (i16, i16) {
        (self.0.dwMaximumWindowSize.X, self.0.dwMaximumWindowSize.Y)
    }

    /// Returns the console screen buffer coordinates of the upper-left and
    /// lower-right corners of the display window.
    ///
    /// This corresponds to `srWindow`.
    pub fn window_rect(&self) -> SmallRect {
        SmallRect {
            left: self.0.srWindow.Left,
            top: self.0.srWindow.Top,
            right: self.0.srWindow.Right,
            bottom: self.0.srWindow.Bottom,
        }
    }
}

/// Defines the coordinates of the upper left and lower right corners of a rectangle.
///
/// This corresponds to [`SMALL_RECT`].
///
/// [`SMALL_RECT`]: https://docs.microsoft.com/en-us/windows/console/small-rect-str
pub struct SmallRect {
    pub left: i16,
    pub top: i16,
    pub right: i16,
    pub bottom: i16,
}

/// A Windows console.
///
/// This represents a very limited set of functionality available to a Windows
/// console. In particular, it can only change text attributes such as color
/// and intensity. This may grow over time. If you need more routines, please
/// file an issue and/or PR.
///
/// There is no way to "write" to this console. Simply write to
/// stdout or stderr instead, while interleaving instructions to the console
/// to change text attributes.
///
/// A common pitfall when using a console is to forget to flush writes to
/// stdout before setting new text attributes.
///
/// # Example
/// ```no_run
/// # #[cfg(windows)]
/// # {
/// use winapi_util::console::{Console, Color, Intense};
///
/// let mut con = Console::stdout().unwrap();
/// con.fg(Intense::Yes, Color::Cyan).unwrap();
/// println!("This text will be intense cyan.");
/// con.reset().unwrap();
/// println!("This text will be normal.");
/// # }
/// ```
#[derive(Debug)]
pub struct Console {
    kind: HandleKind,
    start_attr: TextAttributes,
    cur_attr: TextAttributes,
}

#[derive(Clone, Copy, Debug)]
enum HandleKind {
    Stdout,
    Stderr,
}

impl HandleKind {
    fn handle(&self) -> HandleRef {
        match *self {
            HandleKind::Stdout => HandleRef::stdout(),
            HandleKind::Stderr => HandleRef::stderr(),
        }
    }
}

impl Console {
    /// Get a console for a standard I/O stream.
    fn create_for_stream(kind: HandleKind) -> io::Result<Console> {
        let h = kind.handle();
        let info = screen_buffer_info(&h)?;
        let attr = TextAttributes::from_word(info.attributes());
        Ok(Console { kind: kind, start_attr: attr, cur_attr: attr })
    }

    /// Create a new Console to stdout.
    ///
    /// If there was a problem creating the console, then an error is returned.
    pub fn stdout() -> io::Result<Console> {
        Self::create_for_stream(HandleKind::Stdout)
    }

    /// Create a new Console to stderr.
    ///
    /// If there was a problem creating the console, then an error is returned.
    pub fn stderr() -> io::Result<Console> {
        Self::create_for_stream(HandleKind::Stderr)
    }

    /// Applies the current text attributes.
    fn set(&mut self) -> io::Result<()> {
        set_text_attributes(self.kind.handle(), self.cur_attr.to_word())
    }

    /// Apply the given intensity and color attributes to the console
    /// foreground.
    ///
    /// If there was a problem setting attributes on the console, then an error
    /// is returned.
    pub fn fg(&mut self, intense: Intense, color: Color) -> io::Result<()> {
        self.cur_attr.fg_color = color;
        self.cur_attr.fg_intense = intense;
        self.set()
    }

    /// Apply the given intensity and color attributes to the console
    /// background.
    ///
    /// If there was a problem setting attributes on the console, then an error
    /// is returned.
    pub fn bg(&mut self, intense: Intense, color: Color) -> io::Result<()> {
        self.cur_attr.bg_color = color;
        self.cur_attr.bg_intense = intense;
        self.set()
    }

    /// Reset the console text attributes to their original settings.
    ///
    /// The original settings correspond to the text attributes on the console
    /// when this `Console` value was created.
    ///
    /// If there was a problem setting attributes on the console, then an error
    /// is returned.
    pub fn reset(&mut self) -> io::Result<()> {
        self.cur_attr = self.start_attr;
        self.set()
    }

    /// Toggle virtual terminal processing.
    ///
    /// This method attempts to toggle virtual terminal processing for this
    /// console. If there was a problem toggling it, then an error returned.
    /// On success, the caller may assume that toggling it was successful.
    ///
    /// When virtual terminal processing is enabled, characters emitted to the
    /// console are parsed for VT100 and similar control character sequences
    /// that control color and other similar operations.
    pub fn set_virtual_terminal_processing(
        &mut self,
        yes: bool,
    ) -> io::Result<()> {
        let vt = wincon::ENABLE_VIRTUAL_TERMINAL_PROCESSING;

        let handle = self.kind.handle();
        let old_mode = mode(&handle)?;
        let new_mode = if yes { old_mode | vt } else { old_mode & !vt };
        if old_mode == new_mode {
            return Ok(());
        }
        set_mode(&handle, new_mode)
    }
}

/// A representation of text attributes for the Windows console.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
struct TextAttributes {
    fg_color: Color,
    fg_intense: Intense,
    bg_color: Color,
    bg_intense: Intense,
}

impl TextAttributes {
    fn to_word(&self) -> WORD {
        let mut w = 0;
        w |= self.fg_color.to_fg();
        w |= self.fg_intense.to_fg();
        w |= self.bg_color.to_bg();
        w |= self.bg_intense.to_bg();
        w
    }

    fn from_word(word: WORD) -> TextAttributes {
        TextAttributes {
            fg_color: Color::from_fg(word),
            fg_intense: Intense::from_fg(word),
            bg_color: Color::from_bg(word),
            bg_intense: Intense::from_bg(word),
        }
    }
}

/// Whether to use intense colors or not.
#[allow(missing_docs)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Intense {
    Yes,
    No,
}

impl Intense {
    fn to_bg(&self) -> WORD {
        self.to_fg() << 4
    }

    fn from_bg(word: WORD) -> Intense {
        Intense::from_fg(word >> 4)
    }

    fn to_fg(&self) -> WORD {
        match *self {
            Intense::No => 0,
            Intense::Yes => FG_INTENSITY,
        }
    }

    fn from_fg(word: WORD) -> Intense {
        if word & FG_INTENSITY > 0 {
            Intense::Yes
        } else {
            Intense::No
        }
    }
}

/// The set of available colors for use with a Windows console.
#[allow(missing_docs)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Color {
    Black,
    Blue,
    Green,
    Red,
    Cyan,
    Magenta,
    Yellow,
    White,
}

impl Color {
    fn to_bg(&self) -> WORD {
        self.to_fg() << 4
    }

    fn from_bg(word: WORD) -> Color {
        Color::from_fg(word >> 4)
    }

    fn to_fg(&self) -> WORD {
        match *self {
            Color::Black => 0,
            Color::Blue => FG_BLUE,
            Color::Green => FG_GREEN,
            Color::Red => FG_RED,
            Color::Cyan => FG_CYAN,
            Color::Magenta => FG_MAGENTA,
            Color::Yellow => FG_YELLOW,
            Color::White => FG_WHITE,
        }
    }

    fn from_fg(word: WORD) -> Color {
        match word & 0b111 {
            FG_BLUE => Color::Blue,
            FG_GREEN => Color::Green,
            FG_RED => Color::Red,
            FG_CYAN => Color::Cyan,
            FG_MAGENTA => Color::Magenta,
            FG_YELLOW => Color::Yellow,
            FG_WHITE => Color::White,
            _ => Color::Black,
        }
    }
}


text:
/*!
This crate provides a smattering of safe routines for parts of winapi. The
primary purpose of this crate is to serve as a dumping ground for various
utility functions that make interactions with winapi safe. This permits the
centralization of `unsafe` when dealing with Windows APIs, and thus makes it
easier to audit.

A key abstraction in this crate is the combination of the
[`Handle`](struct.Handle.html)
and
[`HandleRef`](struct.HandleRef.html)
types. Both represent a valid Windows handle to an I/O-like object, where
`Handle` is owned (the resource is closed when the handle is dropped) and
`HandleRef` is borrowed (the resource is not closed when the handle is
dropped). Many of the routines in this crate work on handles and accept
anything that can be safely converted into a `HandleRef`. This includes
standard library types such as `File`, `Stdin`, `Stdout` and `Stderr`.

Note that this crate is completely empty on non-Windows platforms.
*/

#[cfg(windows)]
pub use win::*;

/// Safe routines for dealing with the Windows console.
#[cfg(windows)]
pub mod console;
/// Safe routines for dealing with files and handles on Windows.
#[cfg(windows)]
pub mod file;
#[cfg(windows)]
mod win;

repo_name: BurntSushi/winapi-util

repo_language: Rust

mime_type: text/plain


text:
use std::io;
use std::mem;

use winapi::shared::minwindef::FILETIME;
use winapi::shared::winerror::NO_ERROR;
use winapi::um::errhandlingapi::GetLastError;
use winapi::um::fileapi::{
    GetFileInformationByHandle, GetFileType, BY_HANDLE_FILE_INFORMATION,
};
use winapi::um::winnt;

use crate::AsHandleRef;

/// Return various pieces of information about a file.
///
/// This includes information such as a file's size, unique identifier and
/// time related fields.
///
/// This corresponds to calling [`GetFileInformationByHandle`].
///
/// [`GetFileInformationByHandle`]: https://docs.microsoft.com/en-us/windows/desktop/api/fileapi/nf-fileapi-getfileinformationbyhandle
pub fn information<H: AsHandleRef>(h: H) -> io::Result<Information> {
    unsafe {
        let mut info: BY_HANDLE_FILE_INFORMATION = mem::zeroed();
        let rc = GetFileInformationByHandle(h.as_raw(), &mut info);
        if rc == 0 {
            return Err(io::Error::last_os_error());
        };
        Ok(Information(info))
    }
}

/// Returns the file type of the given handle.
///
/// If there was a problem querying the file type, then an error is returned.
///
/// This corresponds to calling [`GetFileType`].
///
/// [`GetFileType`]: https://docs.microsoft.com/en-us/windows/desktop/api/fileapi/nf-fileapi-getfiletype
pub fn typ<H: AsHandleRef>(h: H) -> io::Result<Type> {
    unsafe {
        let rc = GetFileType(h.as_raw());
        if rc == 0 && GetLastError() != NO_ERROR {
            return Err(io::Error::last_os_error());
        }
        Ok(Type(rc))
    }
}

/// Returns true if and only if the given file attributes contain the
/// `FILE_ATTRIBUTE_HIDDEN` attribute.
pub fn is_hidden(file_attributes: u64) -> bool {
    file_attributes & (winnt::FILE_ATTRIBUTE_HIDDEN as u64) > 0
}

/// Represents file information such as creation time, file size, etc.
///
/// This wraps a [`BY_HANDLE_FILE_INFORMATION`].
///
/// [`BY_HANDLE_FILE_INFORMATION`]: https://docs.microsoft.com/en-us/windows/desktop/api/fileapi/ns-fileapi-_by_handle_file_information
#[derive(Clone)]
pub struct Information(BY_HANDLE_FILE_INFORMATION);

impl Information {
    /// Returns file attributes.
    ///
    /// This corresponds to `dwFileAttributes`.
    pub fn file_attributes(&self) -> u64 {
        self.0.dwFileAttributes as u64
    }

    /// Returns true if and only if this file information has the
    /// `FILE_ATTRIBUTE_HIDDEN` attribute.
    pub fn is_hidden(&self) -> bool {
        is_hidden(self.file_attributes())
    }

    /// Return the creation time, if one exists.
    ///
    /// This corresponds to `ftCreationTime`.
    pub fn creation_time(&self) -> Option<u64> {
        filetime_to_u64(self.0.ftCreationTime)
    }

    /// Return the last access time, if one exists.
    ///
    /// This corresponds to `ftLastAccessTime`.
    pub fn last_access_time(&self) -> Option<u64> {
        filetime_to_u64(self.0.ftLastAccessTime)
    }

    /// Return the last write time, if one exists.
    ///
    /// This corresponds to `ftLastWriteTime`.
    pub fn last_write_time(&self) -> Option<u64> {
        filetime_to_u64(self.0.ftLastWriteTime)
    }

    /// Return the serial number of the volume that the file is on.
    ///
    /// This corresponds to `dwVolumeSerialNumber`.
    pub fn volume_serial_number(&self) -> u64 {
        self.0.dwVolumeSerialNumber as u64
    }

    /// Return the file size, in bytes.
    ///
    /// This corresponds to `nFileSizeHigh` and `nFileSizeLow`.
    pub fn file_size(&self) -> u64 {
        ((self.0.nFileSizeHigh as u64) << 32) | (self.0.nFileSizeLow as u64)
    }

    /// Return the number of links to this file.
    ///
    /// This corresponds to `nNumberOfLinks`.
    pub fn number_of_links(&self) -> u64 {
        self.0.nNumberOfLinks as u64
    }

    /// Return the index of this file. The index of a file is a purpotedly
    /// unique identifier for a file within a particular volume.
    pub fn file_index(&self) -> u64 {
        ((self.0.nFileIndexHigh as u64) << 32) | (self.0.nFileIndexLow as u64)
    }
}

/// Represents a Windows file type.
///
/// This wraps the result of [`GetFileType`].
///
/// [`GetFileType`]: https://docs.microsoft.com/en-us/windows/desktop/api/fileapi/nf-fileapi-getfiletype
#[derive(Clone)]
pub struct Type(u32);

impl Type {
    /// Returns true if this type represents a character file, which is
    /// typically an LPT device or a console.
    pub fn is_char(&self) -> bool {
        self.0 == ::winapi::um::winbase::FILE_TYPE_CHAR
    }

    /// Returns true if this type represents a disk file.
    pub fn is_disk(&self) -> bool {
        self.0 == ::winapi::um::winbase::FILE_TYPE_DISK
    }

    /// Returns true if this type represents a sock, named pipe or an
    /// anonymous pipe.
    pub fn is_pipe(&self) -> bool {
        self.0 == ::winapi::um::winbase::FILE_TYPE_PIPE
    }

    /// Returns true if this type is not known.
    ///
    /// Note that this never corresponds to a failure.
    pub fn is_unknown(&self) -> bool {
        self.0 == ::winapi::um::winbase::FILE_TYPE_UNKNOWN
    }
}

fn filetime_to_u64(t: FILETIME) -> Option<u64> {
    let v = ((t.dwHighDateTime as u64) << 32) | (t.dwLowDateTime as u64);
    if v == 0 {
        None
    } else {
        Some(v)
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<JUCERPROJECT id="yB68Dv" name="SuperVirtualKeyboard" projectType="audioplug"
              companyName="Everytone" companyEmail="sicurella12@gmail.com"
              pluginCharacteristicsValue="pluginEditorRequiresKeys,pluginProducesMidiOut,pluginWantsMidiIn"
              pluginVST3Category="Tools" pluginFormats="buildStandalone,buildVST,buildVST3"
              pluginAUMainType="'aumi'" version="0.03" displaySplashScreen="1"
              jucerFormatVersion="1">
  <MAINGROUP id="oAWhNL" name="SuperVirtualKeyboard">
    <GROUP id="{DEC1935A-4F72-85EF-022F-694C0238CC32}" name="Resources">
      <FILE id="w1tZ2V" name="FactoryModes.txt" compile="0" resource="1"
            file="Resources/FactoryModes.txt"/>
      <FILE id="jZ86Uv" name="SVK-Mockup-Icon.png" compile="0" resource="1"
            file="Resources/SVK-Mockup-Icon.png"/>
      <FILE id="SFEPrP" name="SVK-SuperPyth22-Preview.png" compile="0" resource="1"
            file="Resources/SVK-SuperPyth22-Preview.png"/>
    </GROUP>
    <GROUP id="{E6193C1C-4830-9051-F8B2-795EEC7393A3}" name="Source">
      <FILE id="jXtU8j" name="Constants.h" compile="0" resource="0" file="Source/Constants.h"/>
      <GROUP id="{BD1374F9-7E3C-2177-02A8-9052ECB56565}" name="Midi">
        <FILE id="p3n0GM" name="MidiProcessor.h" compile="0" resource="0" file="Source/Midi/MidiProcessor.h"/>
        <FILE id="fq1fV6" name="MidiProcessor.cpp" compile="1" resource="0"
              file="Source/Midi/MidiProcessor.cpp"/>
      </GROUP>
      <GROUP id="{D3D9BD2E-EBBF-50B0-2961-19C33D6AAA02}" name="File IO">
        <FILE id="tTU60E" name="AbletonMidiWriter.h" compile="0" resource="0"
              file="Source/File IO/AbletonMidiWriter.h"/>
        <FILE id="fi0keh" name="KbmWriter.h" compile="0" resource="0" file="Source/File IO/KbmWriter.h"/>
        <FILE id="IIylWS" name="ReaperWriter.cpp" compile="1" resource="0"
              file="Source/File IO/ReaperWriter.cpp"/>
        <FILE id="CWkeRo" name="ReaperWriter.h" compile="0" resource="0" file="Source/File IO/ReaperWriter.h"/>
      </GROUP>
      <GROUP id="{D5A25263-0D83-82C4-7DAC-24B92CE9D68C}" name="Structures">
        <FILE id="DkVoz7" name="MappingEditorBase.h" compile="0" resource="0"
              file="Source/Structures/MappingEditorBase.h"/>
        <FILE id="Nrr3qL" name="OwnedHashMap.h" compile="1" resource="0" file="Source/Structures/OwnedHashMap.h"/>
        <FILE id="YBCQwi" name="MappingHelper.cpp" compile="1" resource="0"
              file="Source/Structures/MappingHelper.cpp"/>
        <FILE id="DZVjmF" name="MappingHelper.h" compile="0" resource="0" file="Source/Structures/MappingHelper.h"/>
        <FILE id="x6boMo" name="ModeMapper.cpp" compile="1" resource="0" file="Source/Structures/ModeMapper.cpp"/>
        <FILE id="kIMFVq" name="ModeMapper.h" compile="0" resource="0" file="Source/Structures/ModeMapper.h"/>
        <FILE id="vATes6" name="NoteMap.cpp" compile="1" resource="0" file="Source/Structures/NoteMap.cpp"/>
        <FILE id="uK2AIM" name="NoteMap.h" compile="0" resource="0" file="Source/Structures/NoteMap.h"/>
        <FILE id="VyoYfT" name="FractionalGrid.cpp" compile="1" resource="0"
              file="Source/Structures/FractionalGrid.cpp"/>
        <FILE id="fljtTQ" name="FractionalGrid.h" compile="0" resource="0"
              file="Source/Structures/FractionalGrid.h"/>
        <FILE id="doFNva" name="Mode.cpp" compile="1" resource="0" file="Source/Structures/Mode.cpp"/>
        <FILE id="ZNc2fR" name="Mode.h" compile="0" resource="0" file="Source/Structures/Mode.h"/>
        <FILE id="ScqT7w" name="Preset.cpp" compile="1" resource="0" file="Source/Structures/Preset.cpp"/>
        <FILE id="nGJjJ7" name="Preset.h" compile="0" resource="0" file="Source/Structures/Preset.h"/>
        <FILE id="uMBTI9" name="MidiFilter.h" compile="0" resource="0" file="Source/Structures/MidiFilter.h"/>
        <FILE id="DYjSKl" name="MidiFilter.cpp" compile="1" resource="0" file="Source/Structures/MidiFilter.cpp"/>
      </GROUP>
      <GROUP id="{E30FAF37-2BCD-6C29-09AA-D5901B9BE7EA}" name="UI">
        <GROUP id="{7A0AD078-ADB6-88A8-9B33-1BEDF45D5BE3}" name="Components">
          <GROUP id="{27BD5BE9-AE8C-2637-CC5B-9D29EED4280E}" name="Settings">
            <FILE id="XBeAAR" name="MappingSettingsPanel.cpp" compile="1" resource="0"
                  file="Source/UI/Components/Settings/MappingSettingsPanel.cpp"/>
            <FILE id="hUTgqG" name="MappingSettingsPanel.h" compile="0" resource="0"
                  file="Source/UI/Components/Settings/MappingSettingsPanel.h"/>
            <FILE id="AeAfD0" name="ColourSettingsPanel.cpp" compile="1" resource="0"
                  file="Source/UI/Components/Settings/ColourSettingsPanel.cpp"/>
            <FILE id="fNQNUU" name="ColourSettingsPanel.h" compile="0" resource="0"
                  file="Source/UI/Components/Settings/ColourSettingsPanel.h"/>
            <FILE id="WAuZHP" name="DebugSettingsPanel.cpp" compile="1" resource="0"
                  file="Source/UI/Components/Settings/DebugSettingsPanel.cpp"/>
            <FILE id="WbGfKu" name="DebugSettingsPanel.h" compile="0" resource="0"
                  file="Source/UI/Components/Settings/DebugSettingsPanel.h"/>
            <FILE id="pVHdR9" name="SvkSettingsPanel.h" compile="0" resource="0"
                  file="Source/UI/Components/Settings/SvkSettingsPanel.h"/>
            <FILE id="KEkYN4" name="MidiSettingsPanel.cpp" compile="1" resource="0"
                  file="Source/UI/Components/Settings/MidiSettingsPanel.cpp"/>
            <FILE id="sinhC5" name="MidiSettingsPanel.h" compile="0" resource="0"
                  file="Source/UI/Components/Settings/MidiSettingsPanel.h"/>
            <FILE id="RbrLvj" name="GeneralSettingsPanel.cpp" compile="1" resource="0"
                  file="Source/UI/Components/Settings/GeneralSettingsPanel.cpp"/>
            <FILE id="TKlTxI" name="GeneralSettingsPanel.h" compile="0" resource="0"
                  file="Source/UI/Components/Settings/GeneralSettingsPanel.h"/>
            <FILE id="MN6Ieh" name="KeyboardSettingsPanel.cpp" compile="1" resource="0"
                  file="Source/UI/Components/Settings/KeyboardSettingsPanel.cpp"/>
            <FILE id="picLqI" name="KeyboardSettingsPanel.h" compile="0" resource="0"
                  file="Source/UI/Components/Settings/KeyboardSettingsPanel.h"/>
            <FILE id="ov612C" name="SettingsContainer.h" compile="0" resource="0"
                  file="Source/UI/Components/Settings/SettingsContainer.h"/>
          </GROUP>
          <GROUP id="{4D7D80DF-F732-5ABB-BC6A-A7DFBE3682D7}" name="VirtualKeyboard">
            <FILE id="zI44G5" name="KeyboardComponent.cpp" compile="1" resource="0"
                  file="Source/UI/Components/VirtualKeyboard/KeyboardComponent.cpp"/>
            <FILE id="kxFSq5" name="KeyboardComponent.h" compile="0" resource="0"
                  file="Source/UI/Components/VirtualKeyboard/KeyboardComponent.h"/>
            <FILE id="mtt2tt" name="KeyboardController.cpp" compile="1" resource="0"
                  file="Source/UI/Components/VirtualKeyboard/KeyboardController.cpp"/>
            <FILE id="EzMc1u" name="KeyboardController.h" compile="0" resource="0"
                  file="Source/UI/Components/VirtualKeyboard/KeyboardController.h"/>
            <FILE id="YGl0dL" name="KeyboardViewport.cpp" compile="1" resource="0"
                  file="Source/UI/Components/VirtualKeyboard/KeyboardViewport.cpp"/>
            <FILE id="Ig80c3" name="KeyboardViewport.h" compile="0" resource="0"
                  file="Source/UI/Components/VirtualKeyboard/KeyboardViewport.h"/>
            <FILE id="dM2sHw" name="VirtualKeyboardGraphics.cpp" compile="1" resource="0"
                  file="Source/UI/Components/VirtualKeyboard/VirtualKeyboardGraphics.cpp"/>
            <FILE id="nUaAvH" name="VirtualKeyboardGraphics.h" compile="0" resource="0"
                  file="Source/UI/Components/VirtualKeyboard/VirtualKeyboardGraphics.h"/>
            <FILE id="oU1eBt" name="VirtualKeyboardGrid.cpp" compile="1" resource="0"
                  file="Source/UI/Components/VirtualKeyboard/VirtualKeyboardGrid.cpp"/>
            <FILE id="I4oGg0" name="VirtualKeyboardGrid.h" compile="0" resource="0"
                  file="Source/UI/Components/VirtualKeyboard/VirtualKeyboardGrid.h"/>
            <FILE id="iTruVv" name="VirtualKeyboardKey.cpp" compile="1" resource="0"
                  file="Source/UI/Components/VirtualKeyboard/VirtualKeyboardKey.cpp"/>
            <FILE id="nrWH1a" name="VirtualKeyboardKey.h" compile="0" resource="0"
                  file="Source/UI/Components/VirtualKeyboard/VirtualKeyboardKey.h"/>
          </GROUP>
          <FILE id="Igtn8q" name="ColourLibraryComponent.cpp" compile="1" resource="0"
                file="Source/UI/Components/ColourLibraryComponent.cpp"/>
          <FILE id="WW9Jyf" name="ColourLibraryComponent.h" compile="0" resource="0"
                file="Source/UI/Components/ColourLibraryComponent.h"/>
          <FILE id="V4qizf" name="DirectoryBrowserComponent.h" compile="0" resource="0"
                file="Source/UI/Components/DirectoryBrowserComponent.h"/>
          <FILE id="zBGCOT" name="FocussedComponent.h" compile="0" resource="0"
                file="Source/UI/Components/FocussedComponent.h"/>
          <FILE id="bA5eBo" name="LabelledComponent.h" compile="0" resource="0"
                file="Source/UI/Components/LabelledComponent.h"/>
          <FILE id="EKbdHq" name="NoteMapEditor.cpp" compile="1" resource="0"
                file="Source/UI/Components/NoteMapEditor.cpp"/>
          <FILE id="HtSLNw" name="NoteMapEditor.h" compile="0" resource="0" file="Source/UI/Components/NoteMapEditor.h"/>
          <FILE id="ZR3ZGY" name="PluginControlComponent.cpp" compile="1" resource="0"
                file="Source/UI/Components/PluginControlComponent.cpp"/>
          <FILE id="dYHjg9" name="PluginControlComponent.h" compile="0" resource="0"
                file="Source/UI/Components/PluginControlComponent.h"/>
          <FILE id="gtGOgZ" name="ReferencedComboBox.cpp" compile="1" resource="0"
                file="Source/UI/Components/ReferencedComboBox.cpp"/>
          <FILE id="el2G9f" name="ReferencedComboBox.h" compile="0" resource="0"
                file="Source/UI/Components/ReferencedComboBox.h"/>
        </GROUP>
        <GROUP id="{47A64633-0278-4A78-4C12-7D9336B3BFC9}" name="Dialogs">
          <FILE id="XJJu6w" name="ExportKbmDialog.h" compile="0" resource="0"
                file="Source/UI/Dialogs/ExportKbmDialog.h"/>
          <FILE id="KNufAG" name="MapByOrderDialog.cpp" compile="1" resource="0"
                file="Source/UI/Dialogs/MapByOrderDialog.cpp"/>
          <FILE id="Pt2NrT" name="MapByOrderDialog.h" compile="0" resource="0"
                file="Source/UI/Dialogs/MapByOrderDialog.h"/>
          <FILE id="eRcvHJ" name="ModeInfoDialog.cpp" compile="1" resource="0"
                file="Source/UI/Dialogs/ModeInfoDialog.cpp"/>
          <FILE id="HsazKY" name="ModeInfoDialog.h" compile="0" resource="0"
                file="Source/UI/Dialogs/ModeInfoDialog.h"/>
        </GROUP>
        <FILE id="xP2S6O" name="PluginEditor.cpp" compile="1" resource="0"
              file="Source/UI/PluginEditor.cpp"/>
        <FILE id="gGW61u" name="PluginEditor.h" compile="0" resource="0" file="Source/UI/PluginEditor.h"/>
        <FILE id="cry3qn" name="VectorResources.h" compile="0" resource="0"
              file="Source/UI/VectorResources.h"/>
      </GROUP>
      <FILE id="ipy8hj" name="CommonFunctions.h" compile="0" resource="0"
            file="Source/CommonFunctions.h"/>
      <FILE id="qf8oNW" name="PluginIDs.h" compile="1" resource="0" file="Source/PluginIDs.h"/>
      <FILE id="iiiGEu" name="PluginModes.h" compile="0" resource="0" file="Source/PluginModes.h"/>
      <FILE id="h9Uluy" name="PluginState.cpp" compile="1" resource="0" file="Source/PluginState.cpp"/>
      <FILE id="OEUZCe" name="PluginState.h" compile="0" resource="0" file="Source/PluginState.h"/>
      <FILE id="FI8LwH" name="PluginProcessor.cpp" compile="1" resource="0"
            file="Source/PluginProcessor.cpp"/>
      <FILE id="M0F1cM" name="PluginProcessor.h" compile="0" resource="0"
            file="Source/PluginProcessor.h"/>
      <FILE id="RXVf6v" name="PluginSettings.cpp" compile="1" resource="0"
            file="Source/PluginSettings.cpp"/>
      <FILE id="a1oozu" name="PluginSettings.h" compile="0" resource="0"
            file="Source/PluginSettings.h"/>
      <FILE id="go0rYg" name="PresetManager.h" compile="0" resource="0" file="Source/PresetManager.h"/>
      <FILE id="CD8Pzj" name="PresetManager.cpp" compile="1" resource="0"
            file="Source/PresetManager.cpp"/>
    </GROUP>
    <FILE id="uIhRsv" name="README.md" compile="0" resource="1" file="README.md"/>
  </MAINGROUP>
  <EXPORTFORMATS>
    <XCODE_MAC targetFolder="Builds/MacOSX">
      <CONFIGURATIONS>
        <CONFIGURATION isDebug="1" name="Debug"/>
        <CONFIGURATION isDebug="0" name="Release"/>
      </CONFIGURATIONS>
      <MODULEPATHS>
        <MODULEPATH id="juce_audio_basics" path="../../../Programming-Resources/JUCE/modules"/>
        <MODULEPATH id="juce_audio_devices" path="../../../Programming-Resources/JUCE/modules"/>
        <MODULEPATH id="juce_audio_plugin_client" path="../../../Programming-Resources/JUCE/modules"/>
        <MODULEPATH id="juce_core" path="../../../Programming-Resources/JUCE/modules"/>
        <MODULEPATH id="juce_data_structures" path="../../../Programming-Resources/JUCE/modules"/>
        <MODULEPATH id="juce_events" path="../../../Programming-Resources/JUCE/modules"/>
        <MODULEPATH id="juce_graphics" path="../../../Programming-Resources/JUCE/modules"/>
        <MODULEPATH id="juce_gui_basics" path="../../../Programming-Resources/JUCE/modules"/>
        <MODULEPATH id="juce_audio_processors" path="../../../Programming-Resources/JUCE/modules"/>
        <MODULEPATH id="juce_gui_extra" path="../../../Programming-Resources/JUCE/modules"/>
        <MODULEPATH id="juce_audio_utils" path="../../../Programming-Resources/JUCE/modules"/>
        <MODULEPATH id="juce_audio_formats" path="../../../Programming-Resources/JUCE/modules"/>
      </MODULEPATHS>
    </XCODE_MAC>
    <LINUX_MAKE targetFolder="Builds/LinuxMakefile">
      <CONFIGURATIONS>
        <CONFIGURATION isDebug="1" name="Debug"/>
        <CONFIGURATION isDebug="0" name="Release"/>
      </CONFIGURATIONS>
      <MODULEPATHS>
        <MODULEPATH id="juce_audio_basics" path="../../../Programming-Resources/JUCE/modules"/>
        <MODULEPATH id="juce_audio_devices" path="../../../Programming-Resources/JUCE/modules"/>
        <MODULEPATH id="juce_audio_plugin_client" path="../../../Programming-Resources/JUCE/modules"/>
        <MODULEPATH id="juce_core" path="../../../Programming-Resources/JUCE/modules"/>
        <MODULEPATH id="juce_data_structures" path="../../../Programming-Resources/JUCE/modules"/>
        <MODULEPATH id="juce_events" path="../../../Programming-Resources/JUCE/modules"/>
        <MODULEPATH id="juce_graphics" path="../../../Programming-Resources/JUCE/modules"/>
        <MODULEPATH id="juce_gui_basics" path="../../../Programming-Resources/JUCE/modules"/>
        <MODULEPATH id="juce_audio_processors" path="../../../Programming-Resources/JUCE/modules"/>
        <MODULEPATH id="juce_gui_extra" path="../../../Programming-Resources/JUCE/modules"/>
        <MODULEPATH id="juce_audio_utils" path="../../../Programming-Resources/JUCE/modules"/>
        <MODULEPATH id="juce_audio_formats" path="../../../Programming-Resources/JUCE/modules"/>
      </MODULEPATHS>
    </LINUX_MAKE>
    <VS2019 targetFolder="Builds/VisualStudio2019">
      <CONFIGURATIONS>
        <CONFIGURATION isDebug="1" name="Debug"/>
        <CONFIGURATION isDebug="0" name="Release"/>
      </CONFIGURATIONS>
      <MODULEPATHS>
        <MODULEPATH id="juce_gui_extra" path="../../juce"/>
        <MODULEPATH id="juce_gui_basics" path="../../juce"/>
        <MODULEPATH id="juce_graphics" path="../../juce"/>
        <MODULEPATH id="juce_events" path="../../juce"/>
        <MODULEPATH id="juce_data_structures" path="../../juce"/>
        <MODULEPATH id="juce_core" path="../../juce"/>
        <MODULEPATH id="juce_audio_utils" path="../../juce"/>
        <MODULEPATH id="juce_audio_processors" path="../../juce"/>
        <MODULEPATH id="juce_audio_plugin_client" path="../../juce"/>
        <MODULEPATH id="juce_audio_formats" path="../../juce"/>
        <MODULEPATH id="juce_audio_devices" path="../../juce"/>
        <MODULEPATH id="juce_audio_basics" path="../../juce"/>
      </MODULEPATHS>
    </VS2019>
  </EXPORTFORMATS>
  <MODULES>
    <MODULE id="juce_audio_basics" showAllCode="1" useLocalCopy="0" useGlobalPath="1"/>
    <MODULE id="juce_audio_devices" showAllCode="1" useLocalCopy="0" useGlobalPath="1"/>
    <MODULE id="juce_audio_formats" showAllCode="1" useLocalCopy="0" useGlobalPath="1"/>
    <MODULE id="juce_audio_plugin_client" showAllCode="1" useLocalCopy="0"
            useGlobalPath="1"/>
    <MODULE id="juce_audio_processors" showAllCode="1" useLocalCopy="0" useGlobalPath="1"/>
    <MODULE id="juce_audio_utils" showAllCode="1" useLocalCopy="0" useGlobalPath="1"/>
    <MODULE id="juce_core" showAllCode="1" useLocalCopy="0" useGlobalPath="1"/>
    <MODULE id="juce_data_structures" showAllCode="1" useLocalCopy="0" useGlobalPath="1"/>
    <MODULE id="juce_events" showAllCode="1" useLocalCopy="0" useGlobalPath="1"/>
    <MODULE id="juce_graphics" showAllCode="1" useLocalCopy="0" useGlobalPath="1"/>
    <MODULE id="juce_gui_basics" showAllCode="1" useLocalCopy="0" useGlobalPath="1"/>
    <MODULE id="juce_gui_extra" showAllCode="1" useLocalCopy="0" useGlobalPath="1"/>
  </MODULES>
  <LIVE_SETTINGS>
    <WINDOWS/>
    <OSX/>
    <LINUX/>
  </LIVE_SETTINGS>
  <JUCEOPTIONS JUCE_VST3_CAN_REPLACE_VST2="0" JUCE_STRICT_REFCOUNTEDPOINTER="1"/>
</JUCERPROJECT>

repo_name: vsicurella/SuperVirtualKeyboard

mime_type: text/x-c


text:
# SuperVirtualKeyboard

LATEST VERSION: Alpha 2020-10-?? (v0.03)

![SuperVirtualKeyboard Preview](/Resources/SVK-SuperPyth22-Preview.png)

## SUMMARY:

Super Virtual Keyboard is a MIDI-controller plugin that allows you to explore different keyboard layouts with the intention of making microtonal scales easier to digest and compose with.

*This plugin does not yet offer retuning capabilities, so you will have to alter your synth's tuning.*

## FEATURES:
* Select a scale from a large selection of mode presets then click the keys on the keyboard to play.

* Set custom colors for keys by scale degree, key layer (like all white vs all black), or individual keys, which can be saved and reloaded with your scale. Click "Edit Colors", select the color, and then click the key you want to change the color of.
  * No key modifiers will paint all keys of the same scale degree
  * Shift will paint all belonging to the same layer
  * Control will only paint the clicked key.
  * Right-clicking, with respective modifiers, resets the key(s) to a default color.

* If you don't have a midi controller, here are some features you can take advantage of:
  * Hold "Shift" to hold down notes, "Alt" for "Mono Legato" mode, and "Space" to retrigger held notes.
  * Use "Up" & "Down" keys on held notes to transpose by one interval, or "Left" & "Right" keys to transpose by one modal step.

* Save your layout as a text file that Reaper can load as "MIDI Note Names" so that you can see the layout in Reaper's piano roll!
  * View and Edit information about your mode in the "View Mode Info" dialog in the "Edit" menu
  * Save and load your custom scales and midi mappings!

* Use the mapping function to remap your midi piano keyboard to a microtonal scale. To enable, open the dropdown box on the top left and choose "Auto Mapping". This will reveal some more controls, as well as a mapping style.
  * The first scale selection box on the right represents what scale you're mapping from, the input scale, which should be your hardware MIDI keyboard's layout. This will probably be the standard layout, Meantone[7] 12. The second scale under it is the output scale, the scale you will be remapping to.
  * The "Mode to Mode" style will map your MIDI keyboard's white keys to the white keys of the selected scale and will approxmate closest degrees on the chromatic keys.
  * The "Mode to Scale" style will map your full chromatic MIDI keyboard to the selected scale's white keys. This if useful if your output scale's mode size is equal to your input scale's size (the MIDI keyboard's scale size, which is usually 12).
    * For example, Meantone[12] 31 (in 31-EDO) works great on a standard midi keyboard, which creates a chromatic layout from 31-EDO.
    * Superpyth[12] 22 and Pajara[12] 22 are other interesting ones to play around with in this mode.
  * The "by Layers" style will allow you to map a certain layer of keys (layer 1 = diatonic white keys, order 2 = pentatonic black keys) to a certain layer of keys in the output scale.
    * An example would be making a the scale pattern "7 7 7 7 7" which is 35-EDO, and then mapping your input white keys the 7-EDO output white keys, and your black keys to one of the 5-EDO subsets.

### New in version 0.03:
1. Improved preset structure and recalling, however *new preset format is incompatible with older presets*
   * Modes may still load
   * I can add support for old presets upon request
   * The new preset structure includes versioning which make backwards-compatibility more feasible
1. Basic manual mapping
1. Basic KBM file export
1. New Settings menu
   * Reintroduced key color features
   * Adjacent key placement style
   * Key highlighting options
   * Fixed period shifting and transposition
   * MIDI Device selection for standalone app
   * Note mapping editor
1. Simpler and improved GUI
1. Smoothed window resizing

### To do:
* Allow piano keys to be triggered by computer keyboard keys
* Add note names
* Add tuning capability (??)
* Add preset tags and improve preset browsing and management
* Advanced key shape customization
* Change keyboard orientation
* Graphics shading & other niceties
* Different methods of scale creating
* More...

### Known Bugs:
 - More...


text:
2 2 2 1, Dicot; MOS from 2\7
2 1 2 1 1, Mavila; MOS from 3\7, a pentatonic scale with inverse sized intervals to the 5EDO/12EDO pentatonic
2 1 2 2 1, Father; MOS from 3\8
2 2 2 2 1, Bug; MOS from 2\9
1 1 2 1 1 1 2, Mavila; MOS from 4\9, the anti-diatonic scale in 9EDO
1 2 1 2 1 2 1, Dicot; MOS from 3\10
2 2 2 2 2 1, Machine; MOS from 2\11, in the 2.7.9.11 subgroup
2 1 2 1 2 1 2, Orgone; MOS from 3\11, in the 2.7.11 subgroup, features otonal triad 8:11:14 and it's utonal inverse
2 1 1 2 1 1 2 1, Mechanism; MOS from 4\11, near the the Sensi temperament
1 1 3 1 1 1 3, Joan; MOS from 5\11, near the Mavila temperament
2 2 3 2 3, Pentatonic; MOS from 5\12, the familiar 5-note subscale in the Meantone family
2 2 1 2 2 2 1, Meantone; MOS from 5\12, has been the foundation for Western harmony for centuries
3 1 3 1 3 1, Augmented; Symmetrical scale with a period of 4\12 or 400 cents.
2 1 2 1 2 1 2 1, Diminished; Symmetrical scale with a period of 3\12 or 300 cents
2 1 2 2 1 3 1, HarmMinor; The popular Harmonic Minor scale
2 2 2 2 2 2 1, Glacial; MOS from 2\13
2 1 2 1 2 1 2 1 1, Orwell; MOS from 3\13, not considered suitable for accurate Orwell
2 1 1 2 1 1 2 1 1 1, Sephiroth; MOS from 4\13
2 2 1 2 2 1 2 1, Father; MOS from 5\13
4 1 1 4 1 1 1, Thuja; MOS from 6\13, the generator is close to a tritone or 11/8
2 2 2 2 1 2 2 1, Hedgehog; MODMOS from 2\7, close to the Porcupine temperament
1 2 1 2 1 2 1 2 2, Titanium; MOS from 3\14
1 1 3 1 1 3 1 3, Sidi; MOS from 5\14
2 2 2 2 2 2 2 1, Porcupine; MOS from 2\15, a popular temperament that features 3 consecutive major triads followed by 3 consecutive minor triads
3 1 3 1 3 1 3, Hanson; MOS from 4\15, also known as Keemun or Orgone
4 1 1 1 4 1 1 1 1, Progress; MOS from 7\15, has a 7 note MOS sub scale or can be extended to 11 and 13 notes
4 1 4 1 4 1, Augmented; Symmetrical scale with a period of 4\15, MOS of 3\4
2 2 1 2 2 1 2 2 1, Triforce; Symmetrical scale with a period of 5\15, MOS of 2\5
2 1 2 1 2 1 2 1 2 1, Blackwood; Named after Easley Blackwood, but also known as Blacksmith. This symmetrical scale features major and minor triads on every other tonic.
3 3 1 3 3 3, Gorgo; MOS from 3\16
3 1 1 3 1 1 3 1 1 1, Magic; MOS from 5\16 where the generator is close to a major third. Not an optimal Magic tuning.
2 2 3 2 2 2 3, Mavila; MOS from 7\16, this acts as an "anti-diatonic" scale with small and large intervals being swapped, due to the generator being a sharp 4/3
2 2 2 1 2 2 2 2 1, Mavila; MOS from 7\16, a good temperment for xenharmony
2 1 2 1 2 2 1 2 1 2, Lemba; Symmetrical scale with a period of 8\16, MOS of 3\8
3 1 3 1 3 1 3 1, Diminished; Symmetrical scale with a period of 4\16, MOS of 3\4
2 2 2 2 2 2 2 2 1, Bleu; MOS from 2\17
3 3 3 3 3 2, Machine; MOS from 3\17
1 2 1 2 1 2 1 2 1 2 2, Machine; MOS from 3\17
3 1 3 1 3 1 3 1 1, Huxley; MOS from 4\17
3 2 3 2 3 2 2, Maqamic; MOS from 5\17, a temperment that supports intervals used in Maqam music
2 2 1 2 2 1 2 2 2 1, Maqamic; MOS from 5\17, a temperment that supports intervals used in Maqam music
4 1 1 4 1 1 4 1, Skwares; MOS from 6\17, close to Magic but with a much wider major third generator
3 3 1 3 3 3 1, Superpyth; MOS from 7\17, close to Meantone but a bit skewed. The thirds are closer to a Pythagorean major third 81/64 rather than a 5-limit third of 5/4.
1 2 1 2 1 1 2 1 2 1 2 1, Superpyth; MOS from 7\17, close to Meantone but a bit skewed. The thirds are closer to a Pythagorean major third 81/64 rather than a 5-limit third of 5/4.
5 1 1 1 5 1 1 1 1, Progress; MOS from 8\17
2 3 2 3 2 3 3, Amity; MOS from 3\18
3 3 1 3 3 1 3 1, Father; MOS from 5\18
2 5 2 2 5 2, Rice; Symmetrical scale with a period of 9\18, MOS of 2\9
4 4 1 4 4 1, Bicycle; Symmetrical scale with a period of 9\18, MOS of 4\9
2 2 2 2 1 2 2 2 2 1, Biggie; Symmetrical scale with a period of 9\18
2 2 2 2 2 2 2 2 2 1, Negri; MOS from 2\19.
3 3 3 3 3 3 1, Deutone; MOS from 3\19
3 3 1 3 1 3 1 3 1, Godzilla; MOS from 4\19
4 1 4 1 4 1 4, Hanson; MOS from 5\19
4 1 1 4 1 1 4 1 1 1, Magic; MOS from 6\19, good tuning for the Magic temperament
2 3 2 2 3 2 3 2, Sensi; MOS from 7\19
3 3 2 3 3 3 2, Meantone; MOS from 8\19, this is a nice meantone temperament with a flatter fifth than 12-edo (at ~695c) but with major thirds closer to 5/4 (at ~379)
5 1 1 1 1 5 1 1 1 1 1, Liese; MOS from 9\19, this tempermament splits the third harmonic 3/1 into three sections of 10/7
3 3 3 3 3 3 2, Wilson; MOS from 3\20, also known as "Grumpy"
1 1 1 4 1 1 1 4 1 1 4, Nigerian; MOS from 7\20
2 2 2 3 2 2 2 2 3, Mavila; MOS from 9\20, not an optimal tuning for this temperament.
3 1 3 1 3 1 3 1 3 1, Blackwood; Symmetrical scale that features alternating major and minor triads
2 2 2 2 2 2 2 2 2 2 1, Miracle; MOS from 2\21.
3 1 3 1 3 1 3 1 3 1 1, Gorgo; MOS from 4\21
4 1 4 1 4 1 4 1 1, Subklei; MOS from 5\21
3 3 2 3 3 2 3 2, Tridec; MOS from 8\21
2 2 2 1 2 2 2 1 2 2 2 1, August; Symmetrical scale with a period of 2\21, MOS of 2\7
3 3 1 3 3 1 3 3 1, Oodako; Symmetrical scale with period of 3\21, MOS of 3\7
2 1 2 1 2 1 2 1 2 1 2 1 2 1, Whitewood; Symmetrical scale with a period of 3\21
3 3 3 3 3 3 3 1, Porcupine; MOS from 3\22
3 2 3 2 3 2 3 2 2, Orwell; MOS from 5\22, good tuning for this temperament
5 1 1 5 1 1 5 1 1 1, Magic; MOS from 7\22, good tuning for this temperament
4 4 1 4 4 4 1, Superpyth; MOS from 9\22 and close to Meantone but skewed. The thirds are closer to a Pythagorean major third 81/64 rather than a 5-limit third of 5/4.
3 1 3 1 1 3 1 3 1 3 1 1, Superpyth; MOS from 9\22 and close to Meantone but skewed. The thirds are closer to a Pythagorean major third 81/64 rather than a 5-limit third of 5/4.
2 2 2 2 3 2 2 2 2 3, Pajara; Symmetrical scale with period of 11\22, MOS of 2\11
2 2 2 2 2 1 2 2 2 2 2 1, Pajara; Symmetrical scale with period of 11\22, MOS of 2\11
2 2 2 3 2 2 2 2 2 3, Pajara MODMOS; Pentachordal scale from the Pajara MOS
2 2 2 2 1 2 2 2 2 2 2 1, Pajara MODMOS; Pentachordal scale from the Pajara MOS
3 3 3 2 3 3 3 2, Hedgehog; Symmetrical scale from with a period of 11\22, MOS of 3\11
3 1 3 1 3 3 1 3 1 3, Astrology; Symmetrical scale with period of 11\12, MOS of 4\11
1 4 1 4 1 1 4 1 4 1, Doublewide; Symmetrical scale with period of 11\12, MOS of 5\11
2 2 2 2 2 2 2 2 2 2 2 1, Ripple; MOS from 2\23, a quasi-equal 12-tone scale
3 3 3 3 3 3 3 2, Totem; MOS from 3\23, also known as "Grumpy"
1 3 1 3 1 3 1 3 1 3 3, Hemismate; MOS from 4\23
2 3 2 3 2 3 2 3 3, Superpelog; MOS from 5\23
1 1 4 1 1 4 1 1 4 1 4, Mish; MOS from 6\23
3 2 2 3 2 2 3 2 2 2, Sephiroth; MOS from 7\23
1 1 1 5 1 1 1 5 1 1 5, Wesley; MOS from 8\23
4 4 1 4 4 1 4 1, Father; MOS from 9\23, also considered "Uncle"
3 3 3 1 3 3 3 3 1, Mavila; MOS from 10\23
5 5 4 5 5, Godzilla
5 3 5 3 5 3, Triforce
4 4 2 4 4 4 2, Meantone
4 3 4 3 4 3 3, Mohajira
4 4 3 4 4 4 3, Meantone
2 3 2 2 3 2 3 2 2 3 2, Orgone
2 2 2 2 2 3 2 2 2 2 2 3, Injera
5 5 1 5 5 5 1, Superpyth
2 2 2 2 2 2 2 2 2 2 2 2 2 2 3, Valentine; MOS from 2\31. A quasi-equal 15 tone scale.
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 1, Valentine; MOS from 2\31. A quasi-equal 16 tone scale.
3 3	3 3	3 3 3 3 3 3 1, Miracle; MOS from 3\31, an interval named "secor".
2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 1, Miracle; MOS from 3\31, also known as "Blackjack"
1 3 1 3 1 3 1 3 1 3 1 3 1 3 3, Nusecond; MOS from 4\31, a neutral second.
4 1 4 1 4 1 4 1 4 1 4 1 1, Hemithirds; MOS from 5\31.
6 6 6 6 6 1, Mothra; MOS from 6\31
5 1 5 1 5 1 5 1 5 1 1, Mothra; MOS from 6\31
4 3 4 3 4 3 4 3 3, Orwell; MOS from 7\31. The Orwell temperament divides the twelth into 7-equal steps, does well in 7-limit and decent 11-limit.
1 3 3 1 3 3 1 3 3 1 3 3 3, Orwell; MOS from 7\31. The Orwell temperament divides the twelth into 7-equal steps, does well in 7-limit and decent 11-limit.
1 7 1 7 1 7 7, Myna; MOS from 8\31, a good 6/5 approximation.
5 4 5 4 5 4 4, Mohajira; MOS from 9\31, a neutral third.
1 4 4 1 4 4 1 4 4 4, Mohajira; MOS from 9\31, a neutral third.
9 1 9 1 9 1 1, Wurshmidt; MOS from 10\31, very close to 5\4 but not flat enough to generate the Magic Temperament.
2 2 7 2 2 7 2 7, Squares; MOS from 11\31, a supermajor third, similar to the sixth degree in 17edo.
5 5 2 5 5 2 5 2, Semisept; MOS from 12\31.
5 5 3 5 5 5 3, Meantone; MOS from 13\31, and very close to quarter-comma meantone. This has a slightly flatter fifth than 12-edo (at ~697) but nearly spot-on 5/4 major thirds.
3 2 3 2 3 3 2 3 2 3 2 3, Meantone; MOS from 13\31, and very close to quarter-comma meantone. This has a slightly flatter fifth than 12-edo (at ~697) but nearly spot-on 5/4 major thirds.
3 3 8 3 3 3 8, Casablanca; MOS from 14\31
5 3 3 3 5 3 3 3 3, Casablanca; MOS from 14\31
9 1 1 1 1 1 1 9 1 1 1 1 1 1 1, Tritonic; MOS from 15\31
7 7 3 7 7 7 3, Schismatic
4 3 4 3 3 4 3 4 3 4 3 3, Schismatic
3 1 3 1 3 1 3 1 3 1 3 1 3 1 3 1 3 1 3 1 1, Magic
3 3 3 5 3 3 3 5 3 3 3 5 3 3 5, Hanson
4 3 3 3 3 3 3 3 4 3 3 3 3 3 3 3 3, Tricot
2 1 1 2 1 2 1 2 1, Lambda; MOS from 9\13 intended for 13EDT (the Bohlen-Pierce Scale)
2 1 1 2 1 2 1 1 2, Dur; A scale for 13EDT (the Bohlen-Pierce Scale)


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

    PluginState.cpp
    Created: 7 Apr 2019 12:27:01pm
    Author:  Vincenzo

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

#include "PluginState.h"

SvkPluginState::SvkPluginState(AudioProcessorValueTreeState& svkTreeIn)
    : svkTree(svkTreeIn)
{
    pluginStateNode = svkTree.state.getOrCreateChildWithName(IDs::pluginStateNode, nullptr);
    pluginStateNode.setProperty(IDs::pluginPresetVersion, SVK_PRESET_VERSION, nullptr);

    // TODO: Factory default settings, use a function call to load user settings
    pluginSettings.reset(new SvkPluginSettings());

    presetManager.reset(new SvkPresetManager(pluginSettings->getSettingsNode()));
    presetManager->addChangeListener(this);

    // TODO: Factory default MIDI settings
    midiProcessor.reset(new SvkMidiProcessor());

    modeMapper.reset(new ModeMapper());

    buildFactoryDefaultState();
    buildUserDefaultState();

    revertToSavedState(true, false);

    notifyHostDummy = static_cast<AudioParameterBool*>(svkTree.getParameter("NotifyHostDummy"));
}

void SvkPluginState::recallState(ValueTree nodeIn, bool fallbackToDefaultSettings)
{
    ValueTree stateIn = nodeIn;
    int status = isValidStateNode(stateIn);
    DBG("Validity status returned: " + String(status));

    if (status & PluginStateNodeStatus::IsAPVTSNode)
    {
        if (status & 1)
            stateIn = stateIn.getChildWithName(IDs::pluginStateNode);

        // TODO
        else
        {
            //stateIn = stateIn.getChildWithName(IDs::alphaPluginStateNode);
            stateIn = factoryDefaultPluginStateNode.createCopy();
        }
    }
    else if (status & PluginStateNodeStatus::IsPresetNode)
    {
        // TODO: change to default preset
        stateIn = factoryDefaultPluginStateNode.createCopy();
        stateIn.getOrCreateChildWithName(IDs::presetNode, nullptr).copyPropertiesAndChildrenFrom(nodeIn, nullptr);
        stateIn.appendChild(pluginStateNode.getOrCreateChildWithName(IDs::pluginEditorNode, nullptr).createCopy(), nullptr);
    }

    if (stateIn.hasType(IDs::pluginStateNode))
    {
        // Ensure new state doesn't have a parent
        stateIn = stateIn.createCopy();

        bool loaded = presetManager->loadPreset(stateIn.getChildWithName(IDs::presetNode), false);
        if (!loaded)
        {
            // Might not be good - will actually delete existing properties that are set properly
            stateIn = factoryDefaultPluginStateNode;
            presetManager->loadPreset(stateIn.getChildWithName(IDs::presetNode), false);
        }

        pluginStateNode = stateIn;
        revertToSavedState(fallbackToDefaultSettings);
    }
    else
    {
        DBG("State not loaded successfully - no changes were made.");
    }

    DBG("Plugin State Node after recall:\n" + pluginStateNode.toXmlString());
}

ValueTree SvkPluginState::getPluginEditorNode() const
{
    return pluginStateNode.getChildWithName(IDs::pluginEditorNode);
}

ValueTree SvkPluginState::getMappingNode() const
{
    return midiProcessor->midiMapNode;
}

void SvkPluginState::revertToSavedState(bool fallbackToDefaultSettings, bool sendChange)
{
    presetManager->resetToSavedPreset();

    syncNodes(false);

    modeSelectorViewedNum = svkPreset->getModeSelectorViewed();

    onModeUpdate(!sendChange, !sendChange);

    if (sendChange)
        listeners.call(&Listener::presetLoaded, presetNode);

    presetEdited = false;
}

void SvkPluginState::commitStateNode()
{
    // TODO: make it so it's not necessary to call this before saving (?)

    midiProcessor->updateNodes();
    presetManager->commitPreset();

    syncNodes();

    onModeUpdate(true, true);

    DBG("COMMITTED NODE:\n" + pluginStateNode.toXmlString());

    presetEdited = false;
}

void SvkPluginState::syncNodes(bool sendChange)
{
    svkPreset = &presetManager->getPreset();
    presetNode = svkPreset->getPresetNode();

    pluginStateNode.removeChild(pluginStateNode.getChildWithName(IDs::presetNode), nullptr);
    pluginStateNode.appendChild(presetNode, nullptr);

    // TODO: is this necessary?
    for (auto child : svkTree.state)
    {
        if (child.hasType(IDs::pluginStateNode))
        {
            svkTree.state.removeChild(child, nullptr);
            break;
        }
    }
    svkTree.state.appendChild(pluginStateNode, nullptr);

    modeMapper.reset(new ModeMapper(svkPreset->getMappingsNode()));

    midiProcessor->restoreSettingsNode(presetNode.getChildWithName(IDs::midiSettingsNode));
    midiProcessor->restoreMappingNode(presetNode.getChildWithName(IDs::midiMapNode));

    if (JUCEApplication::isStandaloneApp())
        midiProcessor->restoreDevicesNode(pluginStateNode.getOrCreateChildWithName(IDs::midiDeviceSettingsNode, nullptr));

    pluginStateNode.addListener(this);
    presetNode.getChildWithName(IDs::pianoNode).addListener(this);

    if (sendChange)
        listeners.call(&SvkPluginState::Listener::resyncPresetNode, presetNode);

    DBG("PluginState: Nodes synced");
}

int SvkPluginState::isValidStateNode(ValueTree pluginStateNodeIn)
{
    int status = 0; // TODO: determine status codes

    // Determine if it's a SVK state node or a APVTS node
    ValueTree stateNode;

    if (pluginStateNodeIn.hasType(IDs::svkParentNode))
    {
        status = PluginStateNodeStatus::IsAPVTSNode;

        stateNode = pluginStateNodeIn.getChildWithName(IDs::pluginStateNode);

        if (!stateNode.isValid())
        {
            // Check if it's an alpha preset
            stateNode = pluginStateNodeIn.getChildWithName(IDs::alphaPluginStateNode);
        }
    }

    else if (pluginStateNodeIn.hasType(IDs::presetNode))
    {
        status = PluginStateNodeStatus::IsPresetNode;
    }

    else if (pluginStateNodeIn.hasType(IDs::pluginStateNode))
    {
        stateNode = pluginStateNodeIn;
    }

    if (stateNode.isValid())
    {
        // Determine if it's the current preset version or not
        if ((float)stateNode[IDs::pluginPresetVersion] == SVK_PRESET_VERSION)
        {
            status += PluginStateNodeStatus::CurrentVersion;
        }
        else // Can add more conditions for certain versions if necessary
        {
            status += PluginStateNodeStatus::AlphaVersion;
        }

        if (status == 1)
        {
            // TODO: Various validity checks
        }
    }

    return status;
}

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

SvkPresetManager* SvkPluginState::getPresetManager()
{
    return presetManager.get();
}

SvkMidiProcessor* SvkPluginState::getMidiProcessor()
{
    return midiProcessor.get();
}

SvkPluginSettings* SvkPluginState::getPluginSettings()
{
    return pluginSettings.get();
}

ModeMapper* SvkPluginState::getModeMapper()
{
    return modeMapper.get();
}

MappingHelper* SvkPluginState::getManualMappingHelper()
{
    return manualMappingHelper.get();
}

NoteMap* SvkPluginState::getMidiInputFilterMap()
{
    return midiProcessor->getInputRemapMidiFilter()->getNoteMap();
}

NoteMap* SvkPluginState::getMidiOutputFilterMap()
{
    return midiProcessor->getOutputMidiFilter()->getNoteMap();
}

ValueTree SvkPluginState::getPresetNode()
{
    return presetNode;
}

Mode* SvkPluginState::getModeInSlot(int slotNumIn) const
{
    return presetManager->getModeInSlot(slotNumIn);
}

Mode* SvkPluginState::getModeViewed()
{
    return modeViewed;
}

Mode* SvkPluginState::getMode1()
{
    return presetManager->getModeBySelector(0);
}

Mode* SvkPluginState::getMode2()
{
    return presetManager->getModeBySelector(1);
}

Mode* SvkPluginState::getModeCustom()
{
    return presetManager->getModeCustom();
}

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

//float SvkPluginState::getParameterValue(Identifier paramId)
//{
//    RangedAudioParameter* param = svkTree.getParameter(paramId);
//
//    if (param)
//    {
//        return param->convertFrom0to1(param->getValue());
//    }
//
//    return 0.0f;
//}
//
//float SvkPluginState::getParameterMin(Identifier paramId)
//{
//    RangedAudioParameter* param = svkTree.getParameter(paramId);
//
//    if (param)
//        return param->convertFrom0to1(0.0f);
//
//    return 0.0f;
//}
//
//float SvkPluginState::getParameterMax(Identifier paramId)
//{
//    RangedAudioParameter* param = svkTree.getParameter(paramId);
//
//    if (param)
//        return param->convertFrom0to1(1.0f);
//
//    return 0.0f;
//}
//
//float SvkPluginState::getParameterDefaultValue(Identifier paramId)
//{
//    RangedAudioParameter* param = svkTree.getParameter(paramId);
//
//    if (param)
//        return param->convertFrom0to1(param->getDefaultValue());
//
//    return 0.0f;
//}

int SvkPluginState::getNumModesLoaded() const
{
    return presetManager->getNumModeSlots();
}

int SvkPluginState::getModeSelectorViewed() const
{
    return modeSelectorViewedNum;
}

int SvkPluginState::getModeViewedSlotNumber() const
{
    return presetManager->getModeSlotOfSelector(modeSelectorViewedNum);
}

int SvkPluginState::getMappingMode() const
{
    return midiProcessor->midiMapNode[IDs::mappingMode];
}

int SvkPluginState::getAutoMappingStyle() const
{
    return midiProcessor->midiMapNode[IDs::autoMappingStyle];
}

bool SvkPluginState::isAutoMapping() const
{
    return getMappingMode() == 2;
}

int SvkPluginState::getModeSlotRoot(int slotNum) const
{
    return getModeInSlot(slotNum)->getRootNote();
}

int SvkPluginState::getMode1Root() const
{
    return getModeSlotRoot(0);
}

int SvkPluginState::getMode2Root() const
{
    return getModeSlotRoot(1);
}

bool SvkPluginState::isPresetEdited()
{
    return presetEdited;
}

void SvkPluginState::valueTreePropertyChanged(ValueTree& node, const Identifier& property)
{
	sendChangeNotificationToHost();
}

void SvkPluginState::valueTreeChildAdded(ValueTree& parentTree, ValueTree& child)
{
    if (child == modeViewed->modeNode)
    {
		sendChangeNotificationToHost();
    }
}

void SvkPluginState::valueTreeChildRemoved(ValueTree& parentTree, ValueTree& child, int index)
{
    if (child == modeViewed->modeNode)
    {
		sendChangeNotificationToHost();
    }
}

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

//void SvkPluginState::setParameterValue(Identifier paramIdIn, float valueIn)
//{
//    RangedAudioParameter* param = svkTree.getParameter(paramIdIn);
//
//    if (param)
//    {
//        param->setValueNotifyingHost(param->convertTo0to1(valueIn));
//    }
//}

void SvkPluginState::setModeSelectorViewed(int modeSelectorViewedIn)
{
    modeSelectorViewedNum = modeSelectorViewedIn;
    presetNode.getChildWithName(IDs::presetProperties).setProperty(IDs::modeSelectorViewed, modeSelectorViewedNum, nullptr);
    updateModeViewed();
}

void SvkPluginState::handleModeSelection(int modeBoxNum, int idIn)
{
    presetManager->handleModeSelection(modeBoxNum, idIn);
    onModeUpdate();
    presetEdited = true;
}

void SvkPluginState::setMapMode(int mapModeSelectionIn, bool sendChangeMessage)
{
   midiProcessor->midiMapNode.setProperty(IDs::mappingMode, mapModeSelectionIn, nullptr);

    DBG("Plugin State Map Mode Selection: " + String(mapModeSelectionIn));

    if (mapModeSelectionIn == 2) // Auto Mapping
    {
        midiProcessor->setInManualMappingMode(false);
        manualMappingHelper = nullptr;
        doAutoMapping(false);
    }

    else
    {
        if (mapModeSelectionIn == 3) // Manual Mapping
        {
            manualMappingHelper.reset(new MappingHelper(*getMidiInputFilterMap()));
            midiProcessor->setMappingHelper(manualMappingHelper.get());
            midiProcessor->setInManualMappingMode(true);
            setMidiInputMap(midiProcessor->getManualNoteMap(), true, false);
        }

        else // Mapping Off
        {
            midiProcessor->setInManualMappingMode(false);
            manualMappingHelper = nullptr;

            midiProcessor->setInputRemap(NoteMap(), false);
            midiProcessor->setOutputFilter(NoteMap(), false);
            setModeSelectorViewed(1);
        }
    }

	sendChangeNotificationToHost();

    if (sendChangeMessage)
        listeners.call(&Listener::mappingModeChanged, mapModeSelectionIn);

    if (mapModeSelectionIn > 1)
        listeners.call(&Listener::inputMappingChanged, *midiProcessor->getInputNoteRemap());
}

void SvkPluginState::setAutoMapStyle(int mapStyleIn)
{
    modeMapper->setMappingStyle(mapStyleIn);
    midiProcessor->midiMapNode.setProperty(IDs::autoMappingStyle, mapStyleIn, nullptr);
    DBG("mapStyle index = " + String(mapStyleIn));
    if (isAutoMapping())
    {
        doAutoMapping();
    }
}

void SvkPluginState::setModeSelectorRoot(int modeSelectorNumIn, int rootNoteIn, bool updateParameter)
{
    rootNoteIn = totalModulus(rootNoteIn, 128);
    svkPreset->setModeSelectorRootNote(modeSelectorNumIn, rootNoteIn);

    Mode* mode = presetManager->getModeBySelector(modeSelectorNumIn);
    mode->setRootNote(rootNoteIn);

    presetEdited = true;

    if (modeSelectorViewedNum == modeSelectorNumIn)
        updateModeViewed();

    if (isAutoMapping())
        doAutoMapping();
}

void SvkPluginState::onModeUpdate(bool sendModeViewedChangeMessage, bool sendMappingChangeMessage)
{
    midiProcessor->setMode1(getMode1());
    midiProcessor->setMode2(getMode2());

    updateModeViewed(sendMappingChangeMessage);

    if (isAutoMapping())
        doAutoMapping(sendMappingChangeMessage);
}

void SvkPluginState::sendChangeNotificationToHost()
{
	notifyHostValue = !notifyHostValue;
	notifyHostDummy->setValueNotifyingHost(notifyHostValue);
}

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

void SvkPluginState::setMidiInputMap(NoteMap noteMapIn, bool updateNode, bool sendChangeMessage)
{
    midiProcessor->setInputRemap(noteMapIn, updateNode);

    sendChangeNotificationToHost();

    if (sendChangeMessage)
        listeners.call(&Listener::inputMappingChanged, noteMapIn);
}

void SvkPluginState::setMidiOutputMap(NoteMap noteMapIn, bool updateNode)
{
    midiProcessor->setOutputFilter(noteMapIn, updateNode);
}

void SvkPluginState::setModeCustom(String stepsIn, bool sendChangeMessage)
{
    presetManager->setModeCustom(stepsIn);
    handleModeSelection(getModeSelectorViewed(), 999);

    if (sendChangeMessage)
        listeners.call(&Listener::customModeChanged, presetManager->getModeCustom());
}

void SvkPluginState::setMapOrder1(int orderIn)
{
    modeMapper->setMode1OrderNum(orderIn);
}

void SvkPluginState::setMapOrder2(int orderIn)
{
    modeMapper->setMode2OrderNum(orderIn);
}

void SvkPluginState::setMapOrderOffset1(int offsetIn)
{
    modeMapper->setMode1OrderOffset(offsetIn);
}

void SvkPluginState::setMapOrderOffset2(int offsetIn)
{
    modeMapper->setMode2OrderOffset(offsetIn);
}

void SvkPluginState::doAutoMapping(const Mode* mode1, const Mode* mode2, bool sendChangeMessage)
{
    NoteMap noteMap = modeMapper->map(*mode1, *mode2, *midiProcessor->getInputNoteRemap());

    setMidiInputMap(noteMap, false, sendChangeMessage);
}

void SvkPluginState::doAutoMapping(bool sendChangeMessage)
{
    if (getMappingMode() == 2)
    {
        DBG("Applying new MIDI mapping");
        doAutoMapping(getMode1(), getMode2(), sendChangeMessage);
    }
    else
    {
        midiProcessor->setInputRemap(NoteMap(), false);

        if (sendChangeMessage)
            listeners.call(&Listener::inputMappingChanged, *midiProcessor->getInputNoteRemap());
    }
}

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

void SvkPluginState::updateModeViewed(bool sendChange)
{
    modeViewed = presetManager->getModeBySelector(modeSelectorViewedNum);
    modeViewed->modeNode.addListener(this);

    midiProcessor->setModeViewed(modeViewed);

    if (sendChange)
        listeners.call(&Listener::modeViewedChanged, modeViewed, modeSelectorViewedNum, presetManager->getModeSlotOfSelector(modeSelectorViewedNum));
}

void SvkPluginState::commitModeInfo(bool sendChangeMessage)
{
    if (modeViewed == presetManager->getModeCustom())
    {
        DBG("Custom mode edited:" + presetManager->getModeCustom()->modeNode.toXmlString());
    }

    presetManager->setSlotToMode(modeSelectorViewedNum, modeViewed->modeNode);

    onModeUpdate(sendChangeMessage, sendChangeMessage);

    if (sendChangeMessage)
        listeners.call(&Listener::modeInfoChanged, modeViewed);
}

bool SvkPluginState::savePresetToFile()
{
    commitStateNode();
    return presetManager->savePresetToFile(pluginSettings->getPresetPath());
}

bool SvkPluginState::loadPresetFromFile()
{
    ValueTree presetLoaded = presetManager->presetFromFile(pluginSettings->getPresetPath());
    recallState(presetLoaded);
    return true;
}

bool SvkPluginState::saveModeViewedToFile()
{
    return presetManager->saveModeToFile(
        presetManager->getModeSlotOfSelector(modeSelectorViewedNum), pluginSettings->getModePath());
}

bool SvkPluginState::loadModeFromFile()
{
    ValueTree modeNode = presetManager->nodeFromFile("Open Mode", "*.svk", pluginSettings->getModePath());

    if (Mode::isValidMode(modeNode))
    {
        presetManager->addSlotAndSetSelection(getModeSelectorViewed(), modeNode);
        onModeUpdate();
        return true;
    }

    return false;
}

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

void SvkPluginState::buildFactoryDefaultState()
{
    factoryDefaultPluginStateNode = ValueTree(IDs::pluginStateNode);
    factoryDefaultPluginStateNode.setProperty(IDs::pluginPresetVersion, SVK_PRESET_VERSION, nullptr);
    factoryDefaultPluginStateNode.appendChild(pluginSettings->getSettingsNode().createCopy(), nullptr);
    factoryDefaultPluginStateNode.appendChild(presetManager->getPreset().getPresetNode(), nullptr);
}

void SvkPluginState::buildUserDefaultState()
{
    ValueTree defaultSettings = pluginSettings->getSettingsNode().getChildWithName(IDs::presetNode);

    // TODO: connect to actual user default settings

    if (!defaultSettings.isValid())
        defaultSettings = factoryDefaultPluginStateNode.createCopy();
}

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

//void SvkPluginState::parameterChanged(const String& paramID, float newValue)
//{
//    if (paramID == IDs::mappingMode.toString())
//    {
//        setMapMode(newValue);
//    }
//    else if (paramID == IDs::autoMappingStyle.toString())
//    {
//        setAutoMapStyle(newValue);
//    }
//}

void SvkPluginState::changeListenerCallback(ChangeBroadcaster* source)
{
    // Preset loaded
    if (source == presetManager.get())
    {
        revertToSavedState();
    }
}


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

    MidiProcessor.h
    Created: 21 May 2019 6:37:57pm
    Author:  Vincenzo Sicurella

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

#pragma once

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

class SvkMidiProcessor : public MidiMessageCollector
{
    std::unique_ptr<MidiInput> midiInput;
    std::unique_ptr<MidiOutput> midiOutput;

    String midiInputName = "";
    String midiOutputName = "";

    String inputSelected = "";
    String outputSelected = "";

    MidiBuffer midiBuffer;
    int msgCount = 0;

    Mode* modeViewed;
    Mode* mode1;
    Mode* mode2;

    float* midiChannelOut;
    float* periodShift;
    float* transposeAmt;
    bool* useModePeriod;

    std::unique_ptr<MidiFilter> midiInputFilter;
    std::unique_ptr<MidiFilter> midiOutputFilter;

    std::unique_ptr<MPEInstrument> mpeInst;

    bool mpeOn = false;
    bool mpeThru = false;
    bool mpeLegacyOn = false;
    MPEZoneLayout mpeZone;

    int pitchBendGlobalMax = 2;
    int pitchBendNoteMax = 48;
    int mpePitchTrackingMode = 0;
    int mpePressureTrackingMode = 0;
    int mpeTimbreTrackingMode = 0;

    bool midiInputPaused = false;
    bool isInputRemapped = true;
    bool isOutputRemapped = true;

    bool inputMapIsCustom = false;
    bool outputMapIsCustom = false;

    std::unique_ptr<MidiKeyboardState> originalKeyboardState; // used for sending unchanged MIDI messages
    std::unique_ptr<MidiKeyboardState> remappedKeyboardState; // used for displaying on VirtualKeyboard

public:

    SvkMidiProcessor();
    ~SvkMidiProcessor();

    ValueTree midiSettingsNode;
    ValueTree midiMapNode;

    void updateNode();
    bool restoreFromNode(ValueTree midiSettingsNodeIn);

    StringArray getAvailableInputs() const;
    Array<MidiDeviceInfo> getAvailableOutputs() const;

    MidiInput* getInputDevice();
    MidiOutput* getOutputDevice();

    String getInputName() const;
    String getOutputName() const;

    MidiKeyboardState* getOriginalKeyboardState();
    MidiKeyboardState* getRemappedKeyboardState();

    int getRootNote() const;
    int getPeriodShift() const;
    int getTransposeAmt() const;
    int getMidiChannelOut() const;

    NoteMap* getInputNoteMap();
    NoteMap* getOutputNoteMap();

    MidiFilter* getMidiInputFilter();
    MidiFilter* getMidiOutputFilter();

    int getInputNote(int midiNoteIn);
    int getOutputNote(int midiNoteIn);

    bool isMPEOn() const;
    bool isMPELegacyMode() const;
    bool isMPEThru() const;
    MPEZoneLayout getMPEZone() const;

    int getPitchBendNoteMax() const;
    int getPitchBendGlobalMax() const;
    int getPitchTrackingMode() const;
    int getPressureTrackingMode() const;
    int getTimbreTrackingMode() const;

    bool isAutoRemapping();

    String setMidiInput(String deviceID);
    String setMidiOutput(String deviceID);

    void setModeViewed(Mode* modeViewedIn);
    void setMode1(Mode* mode1In);
    void setMode2(Mode* mode2In);

    void setRootNote(int rootNoteIn);
    void setMidiChannelOut(int channelOut);
    void setPeriodShift(int shiftIn);
    void setTransposeAmt(int notesToTranspose);
    void periodUsesModeSize(bool useMode);

    void setMPEOn(bool turnOnMPE);
    void setMPEThru(bool mpeOnThru);
    void setMPELegacy(bool turnOnLegacy);
    void setMPEZone(MPEZoneLayout zoneIn);

    void setPitchBendNoteMax(int bendAmtIn);
    void setPitchBendGlobalMax(int bendAmtIn);
    void setPitchTrackingMode(int modeIn);
    void setPressureTrackingMode(int modeIn);
    void setTimbreTrackingMode(int modeIn);

    void setInputToRemap(bool doRemap=true);
    void setOutputToRemap(bool doRemap=true);

    void setMidiMaps(ValueTree midiMapIn);

    void setMidiInputMap(Array<int> mapIn, bool updateNode=true);
    void setMidiInputMap(NoteMap mapIn, bool updateNode = true);
    void setMidiOutputMap(Array<int> mapIn, bool updateNode = true);
    void setMidiOutputMap(NoteMap mapIn, bool updateNode = true);

    void mapInputNote(int noteIn, int noteOut, bool updateNode = true);
    void mapOutputNode(int noteIn, int noteOut, bool updateNode = true);

    void resetInputMap(bool updateNode=true);
    void resetOutputMap(bool updateNode=true);

    void processMidi(MidiBuffer& midiMessages);
    void sendMsgToOutputs(const MidiMessage& bufferToSend);

    void pauseMidiInput(bool setPaused=true);
    bool isMidiPaused();

    // Listen to UI input from VirtualKeyboard
    void handleNoteOn(MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity) override;
    void handleNoteOff(MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity) override;
    void handleIncomingMidiMessage(MidiInput* source, const MidiMessage& msg) override;
};


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

    This file was auto-generated!

    It contains the basic framework code for a JUCE plugin processor.

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

#include "UI/PluginEditor.h"
#include "PluginProcessor.h"

//==============================================================================
SvkAudioProcessor::SvkAudioProcessor() :
#ifndef JucePlugin_PreferredChannelConfigurations
     AudioProcessor (BusesProperties()
                     #if ! JucePlugin_IsMidiEffect
                      #if ! JucePlugin_IsSynth
                       .withInput  ("Input",  AudioChannelSet::stereo(), true)
                      #endif
                       .withOutput ("Output", AudioChannelSet::stereo(), true)
                     #endif
                       ),
#endif
    svkUndo(new UndoManager()),
    svkValueTree(*this, svkUndo.get(), IDs::svkParentNode, createParameters())
{
    // Temporary
    svkValueTree.state = ValueTree(IDs::svkParentNode);

    pluginState.reset(new SvkPluginState(svkValueTree));
}

SvkAudioProcessor::~SvkAudioProcessor()
{

}

//==============================================================================
const String SvkAudioProcessor::getName() const
{
    return JucePlugin_Name;
}

bool SvkAudioProcessor::acceptsMidi() const
{
   #if JucePlugin_WantsMidiInput
    return true;
   #else
    return false;
   #endif
}

bool SvkAudioProcessor::producesMidi() const
{
   #if JucePlugin_ProducesMidiOutput
    return true;
   #else
    return false;
   #endif
}

bool SvkAudioProcessor::isMidiEffect() const
{
   #if JucePlugin_IsMidiEffect
    return true;
   #else
    return false;
   #endif
}

double SvkAudioProcessor::getTailLengthSeconds() const
{
    return 0.0;
}

int SvkAudioProcessor::getNumPrograms()
{
    return 1;   // NB: some hosts don't cope very well if you tell them there are 0 programs,
                // so this should be at least 1, even if you're not really implementing programs.
}

int SvkAudioProcessor::getCurrentProgram()
{
    return 0;
}

void SvkAudioProcessor::setCurrentProgram (int index)
{
}

const String SvkAudioProcessor::getProgramName (int index)
{
    return {};
}

void SvkAudioProcessor::changeProgramName (int index, const String& newName)
{
}

//==============================================================================
void SvkAudioProcessor::prepareToPlay (double sampleRate, int samplesPerBlock)
{
    sendChangeMessage();
}

void SvkAudioProcessor::releaseResources()
{
    pluginState->getMidiProcessor()->allNotesOff();
}

#ifndef JucePlugin_PreferredChannelConfigurations
bool SvkAudioProcessor::isBusesLayoutSupported (const BusesLayout& layouts) const
{
    // No audio inputs or outputs needed
    ignoreUnused (layouts);
    return true;
}
#endif

void SvkAudioProcessor::processBlock (AudioBuffer<float>& buffer, MidiBuffer& midiMessages)
{
    // In case we have more outputs than inputs, this code clears any output
    // channels that didn't contain input data
    for (auto i = getTotalNumInputChannels(); i < getTotalNumOutputChannels(); ++i)
        buffer.clear (i, 0, buffer.getNumSamples());

    pluginState->getMidiProcessor()->processMidi(midiMessages);
}

//==============================================================================
bool SvkAudioProcessor::hasEditor() const
{
    return true; // (change this to false if you choose to not supply an editor)
}

AudioProcessorEditor* SvkAudioProcessor::createEditor()
{
    return new SvkPluginEditor(*this);
}

//==============================================================================
void SvkAudioProcessor::getStateInformation (MemoryBlock& destData)
{
    // You should use this method to store your parameters in the memory block.
    // You could do that either as raw data, or use the XML or ValueTree classes
    // as intermediaries to make it easy to save and load complex data.

    MemoryOutputStream memOut(destData, true);
    pluginState->commitStateNode();
    svkValueTree.state.writeToStream(memOut);
    DBG("Saving Plugin State node to internal memory:" + svkValueTree.state.toXmlString());
}

void SvkAudioProcessor::setStateInformation (const void* data, int sizeInBytes)
{
    // You should use this method to restore your parameters from this memory block,
    // whose contents will have been created by the getStateInformation() call.

    MemoryInputStream memIn(data, sizeInBytes, false);
    ValueTree presetRecall = ValueTree::readFromStream(memIn);
    DBG("Found this in memory:\n" + presetRecall.toXmlString());

    //presetRecall.removeChild(presetRecall.getChildWithName(IDs::pluginStateNode), nullptr); // uncomment this line to test new instantiation

    //svkValueTree.replaceState(presetRecall);
    //recordParamIDs();
    pluginState->recallState(presetRecall, true);
}

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

UndoManager* SvkAudioProcessor::getUndoManager()
{
    return svkUndo.get();
}

SvkPluginState* SvkAudioProcessor::getPluginState()
{
    return pluginState.get();
}

//const Array<String>& SvkAudioProcessor::getParamIDs() const
//{
//    return paramIDs;
//}

//==============================================================================
// This creates new instances of the plugin..
AudioProcessor* JUCE_CALLTYPE createPluginFilter()
{
    return new SvkAudioProcessor();
}

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

//void SvkAudioProcessor::recordParamIDs()
//{
//    for (auto param : getParameters())
//    {
//        paramIDs.add(dynamic_cast<AudioProcessorParameterWithID*>(param)->paramID);
//    }
//    DBG("Parameters are initialized");
//    DBGArray(paramIDs);
//}
//
AudioProcessorValueTreeState::ParameterLayout SvkAudioProcessor::createParameters()
{

    return AudioProcessorValueTreeState::ParameterLayout({ std::make_unique<AudioParameterBool>("NotifyHostDummy", "SameAsInitialValue", true) });
//    std::vector<std::unique_ptr<RangedAudioParameter>> paramsInit;
//
//    //paramsInit.push_back(std::make_unique<AudioParameterInt>(IDs::presetSlotViewed.toString(), "Preset Slot Viewed", 0, 1, 0));
// //
// //   paramsInit.push_back(std::make_unique<AudioParameterInt>(IDs::mode1SlotNum.toString(), "Mode 1 Slot Number", 0, 128, 0));
// //   paramsInit.push_back(std::make_unique<AudioParameterInt>(IDs::mode2SlotNum.toString(), "Mode 2 Slot Number", 0, 128, 1));
// //   paramsInit.push_back(std::make_unique<AudioParameterInt>(IDs::mode1RootNote.toString(), "Mode 1 Root Note", 0, 127, 60));
// //   paramsInit.push_back(std::make_unique<AudioParameterInt>(IDs::mode2RootNote.toString(), "Mode 2 Root Note", 0, 127, 60));
// //   paramsInit.push_back(std::make_unique<AudioParameterInt>(IDs::mode1RootChannel.toString(), "Mode 1 Root Channel", 1, 16, 1));
// //   paramsInit.push_back(std::make_unique<AudioParameterInt>(IDs::mode2RootChannel.toString(), "Mode 2 Root Channel", 1, 16, 1));
//
//    paramsInit.push_back(std::make_unique<AudioParameterInt>(IDs::mappingMode.toString(), "Mapping Mode", 1, 3, 1));
//    paramsInit.push_back(std::make_unique<AudioParameterInt>(IDs::autoMappingStyle.toString(), "Mapping Style", 1, 3, 1));
//
//    paramsInit.push_back(std::make_unique<AudioParameterBool>(IDs::mpeOn.toString(), "MPE On", false));
//    paramsInit.push_back(std::make_unique<AudioParameterBool>(IDs::mpeLegacyOn.toString(), "MPE Legacy Mode", false));
//    paramsInit.push_back(std::make_unique<AudioParameterBool>(IDs::mpeTuningPreserveMidiNote.toString(), "Preserve Midi Notes", true));
//    paramsInit.push_back(std::make_unique<AudioParameterInt>(IDs::pitchBendGlobalMax.toString(), "Global Pitch Bend", 0, 8192, 2));
//    paramsInit.push_back(std::make_unique<AudioParameterInt>(IDs::pitchBendNoteMax.toString(), "Note Pitch Bend", 0, 8192, 48));
//    paramsInit.push_back(std::make_unique<AudioParameterInt>(IDs::maxVoices.toString(), "Max Polyphony", 1, 16, 15));
//
//    paramsInit.push_back(std::make_unique<AudioParameterBool>(IDs::retuneOn.toString(), "Retune On", false));
//    paramsInit.push_back(std::make_unique<AudioParameterBool>(IDs::retuneAuto.toString(), "Retune Auto", false));
//    paramsInit.push_back(std::make_unique<AudioParameterInt>(IDs::tuningRootNote.toString(), "Tuning Reference Note", 0, 127, 69));
//    paramsInit.push_back(std::make_unique<AudioParameterFloat>(IDs::tuningRootFreq.toString(), "Tuning Reference Frequency", 0.01f, 24000.0f, 440.0f));
//
//    paramsInit.push_back(std::make_unique<AudioParameterInt>(IDs::periodShift.toString(), "Period Shift", -10, 10, 0));
//    paramsInit.push_back(std::make_unique<AudioParameterBool>(IDs::periodShiftModeSize.toString(), "Shift By Mode Size", 0));
//    paramsInit.push_back(std::make_unique<AudioParameterInt>(IDs::transposeAmt.toString(), "Transpose", -127, 127, 0));
//    paramsInit.push_back(std::make_unique<AudioParameterInt>(IDs::keyboardMidiChannel.toString(), "Midi Channel Out", 1, 16, 1));
//    paramsInit.push_back(std::make_unique<AudioParameterBool>(IDs::pianoKeysShowNoteNumbers.toString(), "Show Note Numbers", false));
//    paramsInit.push_back(std::make_unique<AudioParameterBool>(IDs::pianoKeysShowFilteredNotes.toString(), "Show Filtered Numbers", false));
//    paramsInit.push_back(std::make_unique<AudioParameterBool>(IDs::pianoKeyShowNoteLabel.toString(), "Show Pitch Names", false));
//    paramsInit.push_back(std::make_unique<AudioParameterInt>(IDs::keyboardScrollingMode.toString(), "Scrolling Mode", 0, 3, 1));
//    paramsInit.push_back(std::make_unique<AudioParameterInt>(IDs::keyboardScrollingStyle.toString(), "Scrolling Style", 0, 3, 1));
//    paramsInit.push_back(std::make_unique<AudioParameterInt>(IDs::numKeysInWidth.toString(), "Num Keys in Width", 1, 128, 16));
//    paramsInit.push_back(std::make_unique<AudioParameterInt>(IDs::keyboardNumRows.toString(), "Keyboard Rows", 1, 16, 1));
//    paramsInit.push_back(std::make_unique<AudioParameterInt>(IDs::keyboardOrientation.toString(), "Keyboard Orientation", 0, 3, 0));
//    paramsInit.push_back(std::make_unique<AudioParameterInt>(IDs::keyboardKeysStyle.toString(), "Key Style", 1, 4, 1));
//    paramsInit.push_back(std::make_unique<AudioParameterInt>(IDs::keyboardHighlightStyle.toString(), "Highlight Style", 1, 4, 1));
//
//    paramsInit.push_back(std::make_unique<AudioParameterInt>(IDs::pianoVelocityBehavior.toString(), "Keyboard Velocity Mode", 0, 2, 0));
//    paramsInit.push_back(std::make_unique<AudioParameterInt>(IDs::pianoVelocityValue.toString(), "Default Velocity", 0, 127, 100));
//    paramsInit.push_back(std::make_unique<AudioParameterFloat>(IDs::pianoWHRatio.toString(), "Key Size Ratio", 0.01f, 1.62f, 0.25f));
//
//    paramsInit.push_back(std::make_unique<AudioParameterInt>(IDs::modeSlotToEdit.toString(), "Mode Slot Debug", 0, 1, 0));
//    paramsInit.push_back(std::make_unique<AudioParameterInt>(IDs::modeLibraryIndex.toString(), "Mode Debug Index", 0, 1, 0));
//    paramsInit.push_back(std::make_unique<AudioParameterInt>(IDs::modeRootNote.toString(), "Mode Debug Root", 0, 127, 60));
//
//    paramsInit.push_back(std::make_unique<AudioParameterInt>(IDs::keyNumberToEdit.toString(), "Key To Debug", 0, 127, 60));
//    paramsInit.push_back(std::make_unique<AudioParameterFloat>(IDs::pianoKeyWidthMod.toString(), "Key Debug Width Mod", 0.001f, 10.0f, 1.0f));
//    paramsInit.push_back(std::make_unique<AudioParameterFloat>(IDs::pianoKeyHeightMod.toString(), "Key Debug Height Mod", 0.001f, 10.0f, 1.0f));
//    paramsInit.push_back(std::make_unique<AudioParameterInt>(IDs::pianoKeyXOffset.toString(), "Key Debug X Offset", -1000, 1000, 0));
//    paramsInit.push_back(std::make_unique<AudioParameterInt>(IDs::pianoKeyYOffset.toString(), "Key Debug Y Offset", -1000, 1000, 0));
//
//
//    return {paramsInit.begin(), paramsInit.end()};
}


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

    PluginIDs.h
    Created: 15 Apr 2019 8:27:23pm
    Author:  Vincenzo

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

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

// IDENTIFIERS

namespace IDs
{
// Plugin State & Presets
static Identifier svkParentNode("SVKValueTreeParent");
static Identifier pluginStateNode("SvkPluginState");
static Identifier modeLibraryNode("ModeLibrary");
static Identifier presetNode("SvkPreset");
static Identifier modePresetNode("SvkModeLayout");
static Identifier modeCustomNode("SvkCustomMode");
static Identifier pluginPresetVersion("SvkPresetVersion");

// Global Settings
static Identifier globalSettingsNode("SvkPreferences");
static Identifier settingsDirectory("SettingsDirectory");
static Identifier presetDirectory("PresetDirectory");
static Identifier modeDirectory("ModeDirectory");
static Identifier createPresetFolder("CreatePresetFolder");
static Identifier saveFactoryModes("SaveFactoryPresets");

// Preset Properties
static Identifier presetProperties("PresetProperties");
static Identifier modeSelectorsNode("ModeSelectors");
static Identifier modeSlotsNode("ModeSlots");
static Identifier modeSlotNumber("SlotNumber");
static Identifier modeSelectorViewed("ModeSelectorViewed");
static Identifier modeSelectorRootNote("ModeSelectorRootNote");

// Midi Settings
static Identifier midiDeviceSettingsNode("MidiDeviceSettings");
static Identifier midiSettingsNode("MidiSettings");
static Identifier rootMidiNote("RootNote");
static Identifier periodShift("PeriodShift");
static Identifier periodShiftModeSize("PeriodShiftModeSize");
static Identifier transposeAmt("TransposeAmt");
static Identifier maxVoices("MaxVoices");
static Identifier midiInputName("InputDevice");
static Identifier midiOutputName("OutputDevice");

// MPE Settings
static Identifier mpeOn("MPEOn");
static Identifier mpeThru("MPEThru");
static Identifier mpeZone("MPEZone");
static Identifier mpeLegacyOn("MPELegacyOn");
static Identifier pitchBendGlobalMax("PitchBendGlobalMax");
static Identifier pitchBendNoteMax("PitchBendNoteMax");
static Identifier mpePitchTrackingMode("MPEPitchTrackingMode");
static Identifier mpePressureTrackingMode("MPEPitchTrackingMode");
static Identifier mpeTimbreTrackingMode("MPEPitchTrackingMode");
static Identifier mpeTuningPreserveMidiNote("MPETunePreserveMidiNote");

// Tuning
static Identifier tuningName("TuningName");
static Identifier retuneOn("RetuneOn");
static Identifier retuneAuto("RetuneAuto");
static Identifier tuningRootNote("TuningRootNote");
static Identifier tuningRootFreq("TuningRootFreq");

// Mode
static Identifier scaleSize("ScaleSize");
static Identifier modeSize("ModeSize");
static Identifier stepString("StepsString");
static Identifier MOSClass("MosClass");
static Identifier family("Family");
static Identifier modeInfo("Description");
static Identifier modeName("ModeName");
static Identifier factoryPreset("FactoryPreset");
static Identifier libraryIndexOfMode("IndexOfMode");

// Note Mapping
static Identifier midiMapNode("MidiMappings");
static Identifier midiInputFilter("InputFilter");
static Identifier midiInputRemap("InputMapping");
static Identifier midiOutputFilter("OutputFilter");
static Identifier noteMapNode("NoteMapping");
static Identifier mappingSize("MappingSize");
static Identifier mappingMidiNoteIn("MidiNoteIn");
static Identifier mappingMidiChannelIn("MidiChannelIn");
static Identifier mappingMidiNoteOut("MidiNoteOut");
static Identifier mappingMidiChannelOut("MidiChannelOut");
static Identifier midiMapInputCustom("CustomMidiInputMap");
static Identifier midiMapOutputCustom("CustomMidiOutputMap");
static Identifier modeMapFromRootNote("ModeMapFromRootNote");
static Identifier modeMapFromPreset("ModeMapFromPreset");
static Identifier mappingMode("MappingMode");
static Identifier autoMappingStyle("ModeMappingType");
static Identifier mode1OrderMapping("Mode1OrderMapping");
static Identifier mode2OrderMapping("Mode2OrderMapping");
static Identifier mode1OrderOffsetMapping("Mode1OrderOffsetMapping");
static Identifier mode2OrderOffsetMapping("Mode2OrderOffsetMapping");
static Identifier kbmFileLocation("KbmFileLocation");

// Keyboard Window
static Identifier pluginEditorNode("PluginWindow");
static Identifier windowBoundsW("WindowW");
static Identifier windowBoundsH("WindowH");
static Identifier viewportPosition("ViewportPosition");
static Identifier settingsOpen("SettingsOpen");
static Identifier settingsTabName("SettingsTabName");

// TODO: Refactor piano -> keyboard
// Keyboard Component
static Identifier pianoNode("SvkPianoNode");
static Identifier pianoUIMode("PianoUIMode");
static Identifier keyboardOrientation("KeyboardOrientation");
static Identifier pianoLastKeyClicked("PianoLastKeyClicked");
static Identifier keyboardMidiChannel("SelectedMidiChannel");
static Identifier pianoWHRatio("WidthToHeightRatio");
static Identifier keyboardNumRows("KeyboardNumRows");
static Identifier pianoHasCustomColor("PresetHasCustomColor");
static Identifier keyboardKeysStyle("KeyPlacementType");
static Identifier pianoKeysShowNoteNumbers("PianoShowNoteNumbers");
static Identifier pianoKeysShowFilteredNotes("PianoShowFilteredNotes");
static Identifier keyboardShowsNoteLabels("KeyboardShowsNoteLabels");
static Identifier keyboardHighlightStyle("PianoHighlightStyle");
static Identifier keyboardScrollingStyle("KeyboardScrollingStyle");
static Identifier keyboardScrollingMode("KeyboardScrollingMode");
static Identifier numKeysInWidth("NumKeysInWidth");
static Identifier pianoVelocityBehavior("PianoVelocityBehavior");
static Identifier pianoVelocityScaleInput("PianoVelocityScaleInput");
static Identifier pianoVelocityValue("PianoVelocityValue");
static Identifier expressionCCVal("CCForExpression");
static Identifier pianoKeyColorsNode("KeyColors");
static Identifier pianoKeyColorsLayer("LayerColors");
static Identifier pianoKeyColorsDegree("DegreeColors");
static Identifier pianoKeyColorsIndividual("IndividualColors");
static Identifier pianoKeyColorsNoteOn("NoteOnColors");
static Identifier pianoKeyPlaceOrder("KeyOrderPlaces");
static Identifier pianoKeyPlaceDegree("KeyDegreePlaces");
static Identifier pianoKeyPlaceSingle("KeySinglePlaces");
static Identifier pianoKeyRatioOrder("KeyOrderRatios");
static Identifier pianoKeyRatioDegree("KeyDegreeRatios");
static Identifier pianoKeyRatioSingle("KeySingleRatios");

// Piano Key Component
static Identifier pianoKeyTreeNode("PianoKeyTree");
static Identifier pianoKeyNode("PianoKeyNode");
static Identifier pianoKeyNumber("KeyNumber");
static Identifier pianoKeyNoteLabel("NoteLabel");
static Identifier pianoKeyWidthMod("WidthMod");
static Identifier pianoKeyHeightMod("HeightMod");
static Identifier pianoKeyXOffset("XOffset");
static Identifier pianoKeyYOffset("YOffset");
static Identifier pianoKeyShowNumber("ShowNumber");
static Identifier pianoKeyShowNoteLabel("ShowKeyNoteLabel");
static Identifier pianoKeyColor("KeyColor");

// Control Related IDs
static Identifier colorSelected("ColorSelected");
static Identifier pianoKeyColorReset("ResetColor");
static Identifier pianoKeyPaintType("PaintType");

// Backwards compatibility
static Identifier alphaPluginStateNode("PluginState");
static Identifier alphaVirtualKeyboardNode("PianoNode");
static Identifier alphaCustomMode("CustomMode");

// Debug
static Identifier modeSlotToEdit("ModeSlotToDebug");
static Identifier modeLibraryIndex("ModeLibraryIndex");
static Identifier modeRootNote("ModeRootNote");
static Identifier keyNumberToEdit("KeyToDebug");

static Array<Identifier> pianoSettings =
{
    pianoUIMode,
    pianoWHRatio,
    keyboardKeysStyle,
    keyboardHighlightStyle,
    pianoKeyShowNumber
};

static Array<Identifier> midiSettings =
{
    periodShift,
    periodShiftModeSize,
    transposeAmt,
    keyboardMidiChannel,
    rootMidiNote // default root note
};

enum CommandIDs
{
    savePresetToFile = 1,
    saveMode,
    showSaveMenu,
    loadPreset,
    loadMode,
    showLoadMenu,
    exportPreset,
    exportReaperMap,
    exportAbletonMap,
    showExportMenu,
    showSettingsDialog,
    commitCustomScale,
    setMode1,
    setMode2,
    setMode1RootNote,
    setMode2RootNote,
    setModeViewed,
    setMode1SlotNumber,
    setMode2SlotNumber,
    showModeInfo,
    setMappingMode,
    setMappingStyle,
    setMappingModeToMode,
    setMappingModeToScale,
    setMappingOrders,
    showMapOrderEdit,
    applyMapping,
    beginMapEditing,
    setPeriodShift,
    setMidiChannelOut,
    beginColorEditing,
    showMidiNoteNumbers,
    setKeyboardOrientation,
    setPianoHorizontal,
    setPianoVerticalL,
    setPianoVerticalR,
    setKeyboardRows,
    setKeyStyle,
    setKeysNestedRight,
    setKeysFlat,
    setKeysAdjacent,
    setHighlightStyle,
    setHighlightFullKey,
    setHighlightDot,
};
}

enum SortType
{
    scaleSize = 0,
    modeSize,
    familyName,
    user
};


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

    PluginSettings.cpp
    Created: 27 May 2019 1:46:06pm
    Author:  Vincenzo

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

#include "PluginSettings.h"

SvkPluginSettings::SvkPluginSettings()
{
    pluginSettingsNode = ValueTree(IDs::globalSettingsNode);
    pluginSettingsNode.setProperty(IDs::pluginPresetVersion, SVK_PRESET_VERSION, nullptr);

    File settingsDirectory = factoryDefaultSettingsLocation;
    ValueTree settingsLoad;

    if (settingsDirectory.isDirectory())
    {
        std::unique_ptr<XmlElement> xml = parseXML(settingsDirectory.getChildFile(settingsFileName));

        if (xml.get())
        {
            settingsLoad = ValueTree::fromXml(*(xml.get()));
            restoreNode(settingsLoad);
            DBG("Loaded these settings\n " + settingsLoad.toXmlString());
        }

        if (!pluginSettingsNode.hasProperty(IDs::modeDirectory))
            resetDirectories = true;
    }

    if (currentSettingsLocation == File() || !currentSettingsLocation.exists())
    {
        currentSettingsLocation = factoryDefaultSettingsLocation;
        currentSettingsLocation.createDirectory();
    }

    if (currentPresetLocation == File() || !currentPresetLocation.exists() || resetDirectories)
    {
        currentPresetLocation = factoryDefaultPresetLocation;
        currentModeLocation = factoryDefaultModeLocation;

        DBG("CurrentPresetLocations: " + currentPresetLocation.getFullPathName());
        DBG("CurrentModeLocations: " + currentModeLocation.getFullPathName());

        if (createPresetFolder)
        {
            currentPresetLocation.createDirectory();
            currentModeLocation.createDirectory();
        }
    }

    updateNode();
}

SvkPluginSettings::~SvkPluginSettings()
{
    updateNode(true);
}

bool SvkPluginSettings::updateNode(bool writeSettings)
{
    pluginSettingsNode.setProperty(IDs::settingsDirectory, currentSettingsLocation.getFullPathName(), nullptr);
    pluginSettingsNode.setProperty(IDs::presetDirectory, currentPresetLocation.getFullPathName(), nullptr);
    pluginSettingsNode.setProperty(IDs::modeDirectory, currentModeLocation.getFullPathName(), nullptr);
    pluginSettingsNode.setProperty(IDs::createPresetFolder, createPresetFolder, nullptr);
    pluginSettingsNode.setProperty(IDs::saveFactoryModes, saveFactoryModes, nullptr);

    if (writeSettings)
    {
        DBG("Writing settings to: " + currentSettingsLocation.getFullPathName());
        std::unique_ptr<XmlElement> xml(pluginSettingsNode.createXml());
        return xml->writeTo(currentSettingsLocation.getChildFile(settingsFileName));
    }

    return true;
}

bool SvkPluginSettings::restoreNode(ValueTree pluginSettingsNodeIn)
{
    if (pluginSettingsNodeIn.hasType(IDs::globalSettingsNode))
    {
        pluginSettingsNode.copyPropertiesAndChildrenFrom(pluginSettingsNodeIn, nullptr);

        pluginSettingsNode.setProperty(IDs::pluginPresetVersion, SVK_PRESET_VERSION, nullptr);

        currentSettingsLocation = File(pluginSettingsNode[IDs::settingsDirectory].toString());
        currentPresetLocation = File(pluginSettingsNode[IDs::presetDirectory].toString());
        currentModeLocation = File(pluginSettingsNode[IDs::modeDirectory].toString());

        createPresetFolder = (bool)pluginSettingsNode[IDs::createPresetFolder];
        saveFactoryModes = (bool)pluginSettingsNode[IDs::saveFactoryModes];

        return true;
    }
    return false;
}

ValueTree SvkPluginSettings::getSettingsNode()
{
    return pluginSettingsNode;
}

String SvkPluginSettings::getSettingsPath()
{
    return currentSettingsLocation.getFullPathName();
}

String SvkPluginSettings::getPresetPath()
{
    return currentPresetLocation.getFullPathName();
}

String SvkPluginSettings::getModePath()
{
    return currentModeLocation.getFullPathName();
}

bool SvkPluginSettings::getCreatePresetFolder()
{
    return createPresetFolder;
}

bool SvkPluginSettings::getSaveFactoryModes()
{
    return saveFactoryModes;
}

void SvkPluginSettings::setPresetDirectory(File presetDirectoryIn)
{
    currentPresetLocation = presetDirectoryIn;
    pluginSettingsNode.setProperty(IDs::presetDirectory, currentPresetLocation.getFullPathName(), nullptr);
}

void SvkPluginSettings::setModeDirectory(File modeDirectoryIn)
{
    currentModeLocation = modeDirectoryIn;
    pluginSettingsNode.setProperty(IDs::modeDirectory, currentModeLocation.getFullPathName(), nullptr);
}

void SvkPluginSettings::setSettingsDirectory(File settingsDirectoryIn)
{
    currentSettingsLocation = settingsDirectoryIn;
    pluginSettingsNode.setProperty(IDs::settingsDirectory, currentSettingsLocation.getFullPathName(), nullptr);
}

void SvkPluginSettings::setCreatePresetFolder(bool shouldCreateFolder)
{
    createPresetFolder = shouldCreateFolder;
    pluginSettingsNode.setProperty(IDs::createPresetFolder, createPresetFolder, nullptr);
}

void SvkPluginSettings::setSaveFactoryPresets(bool shouldSavePresets)
{
    saveFactoryModes = shouldSavePresets;
    pluginSettingsNode.setProperty(IDs::saveFactoryModes, saveFactoryModes, nullptr);
}