text
stringlengths 2
104M
| meta
dict |
---|---|
https://aica.pages.dev/creators/andite/anything/4_0_0/1.png
https://aica.pages.dev/creators/andite/anything/4_0_0/2.png
https://aica.pages.dev/creators/andite/anything/4_0_0/3.png
https://aica.pages.dev/creators/andite/anything/4_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/ogkalu/illustration_diffusion/1_0_0/1.png
https://aica.pages.dev/creators/ogkalu/illustration_diffusion/1_0_0/2.png
https://aica.pages.dev/creators/ogkalu/illustration_diffusion/1_0_0/3.png
https://aica.pages.dev/creators/ogkalu/illustration_diffusion/1_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/ogkalu/comic_diffusion/2_0_0/1.png
https://aica.pages.dev/creators/ogkalu/comic_diffusion/2_0_0/2.png
https://aica.pages.dev/creators/ogkalu/comic_diffusion/2_0_0/3.png
https://aica.pages.dev/creators/ogkalu/comic_diffusion/2_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
charliebo artstyle
holliemengert artstyle
marioalberti artstyle
pepelarraz artstyle
andreasrocha artstyle
jamesdaly artstyle | {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/alexds9/babes/1_0_0/1.png
https://aica.pages.dev/creators/alexds9/babes/1_0_0/2.png
https://aica.pages.dev/creators/alexds9/babes/1_0_0/3.png
https://aica.pages.dev/creators/alexds9/babes/1_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/astralite_heart/pony_diffusion/2_0_0/1.png
https://aica.pages.dev/creators/astralite_heart/pony_diffusion/2_0_0/2.png
https://aica.pages.dev/creators/astralite_heart/pony_diffusion/2_0_0/3.png
https://aica.pages.dev/creators/astralite_heart/pony_diffusion/2_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/lucetepolis/mare_coloris/1_0_0/1.png
https://aica.pages.dev/creators/lucetepolis/mare_coloris/1_0_0/2.png
https://aica.pages.dev/creators/lucetepolis/mare_coloris/1_0_0/3.png
https://aica.pages.dev/creators/lucetepolis/mare_coloris/1_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/junjuice0/voxo/1_0_0/1.png
https://aica.pages.dev/creators/junjuice0/voxo/1_0_0/2.png
https://aica.pages.dev/creators/junjuice0/voxo/1_0_0/3.png
https://aica.pages.dev/creators/junjuice0/voxo/1_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/evgk_132410/realistic_vision/1_3_0/1.png
https://aica.pages.dev/creators/evgk_132410/realistic_vision/1_3_0/2.png
https://aica.pages.dev/creators/evgk_132410/realistic_vision/1_3_0/3.png
https://aica.pages.dev/creators/evgk_132410/realistic_vision/1_3_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/syaimu/7th_layer/1_0_0/1.png
https://aica.pages.dev/creators/syaimu/7th_layer/1_0_0/2.png
https://aica.pages.dev/creators/syaimu/7th_layer/1_0_0/3.png
https://aica.pages.dev/creators/syaimu/7th_layer/1_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/gsdf/counterfeit/2_0_0/1.png
https://aica.pages.dev/creators/gsdf/counterfeit/2_0_0/2.png
https://aica.pages.dev/creators/gsdf/counterfeit/2_0_0/3.png
https://aica.pages.dev/creators/gsdf/counterfeit/2_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/envvi/inkpunk_diffusion/1_0_0/1.png
https://aica.pages.dev/creators/envvi/inkpunk_diffusion/1_0_0/2.png
https://aica.pages.dev/creators/envvi/inkpunk_diffusion/1_0_0/3.png
https://aica.pages.dev/creators/envvi/inkpunk_diffusion/1_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/its_jay_qz/synthwave_punk/2_0_0/1.png
https://aica.pages.dev/creators/its_jay_qz/synthwave_punk/2_0_0/2.png
https://aica.pages.dev/creators/its_jay_qz/synthwave_punk/2_0_0/3.png
https://aica.pages.dev/creators/its_jay_qz/synthwave_punk/2_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
snthwve style
nvinkpunk | {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/sentet1c/rando_mix3/1_0_0/1.png
https://aica.pages.dev/creators/sentet1c/rando_mix3/1_0_0/2.png
https://aica.pages.dev/creators/sentet1c/rando_mix3/1_0_0/3.png
https://aica.pages.dev/creators/sentet1c/rando_mix3/1_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/chilon249/yiffy_mix/1_0_0/1.png
https://aica.pages.dev/creators/chilon249/yiffy_mix/1_0_0/2.png
https://aica.pages.dev/creators/chilon249/yiffy_mix/1_0_0/3.png
https://aica.pages.dev/creators/chilon249/yiffy_mix/1_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/josephus_cheung/a_certainty/1_0_0/1.png
https://aica.pages.dev/creators/josephus_cheung/a_certainty/1_0_0/2.png
https://aica.pages.dev/creators/josephus_cheung/a_certainty/1_0_0/3.png
https://aica.pages.dev/creators/josephus_cheung/a_certainty/1_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/josephus_cheung/a_certain_model/1_0_0/1.png
https://aica.pages.dev/creators/josephus_cheung/a_certain_model/1_0_0/2.png
https://aica.pages.dev/creators/josephus_cheung/a_certain_model/1_0_0/3.png
https://aica.pages.dev/creators/josephus_cheung/a_certain_model/1_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/josephus_cheung/a_certain_thing/1_0_0/1.png
https://aica.pages.dev/creators/josephus_cheung/a_certain_thing/1_0_0/2.png
https://aica.pages.dev/creators/josephus_cheung/a_certain_thing/1_0_0/3.png
https://aica.pages.dev/creators/josephus_cheung/a_certain_thing/1_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/comp_vis/stable_diffusion_original/1_4_0/1.png
https://aica.pages.dev/creators/comp_vis/stable_diffusion_original/1_4_0/2.png
https://aica.pages.dev/creators/comp_vis/stable_diffusion_original/1_4_0/3.png
https://aica.pages.dev/creators/comp_vis/stable_diffusion_original/1_4_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://huggingface.co/ckpt/SimpMaker-3K1/resolve/main/SimpMaker%203k.ckpt
https://huggingface.co/ckpt/SimpMaker-3K1/resolve/main/SimpMaker%203k1.ckpt
https://huggingface.co/ckpt/SimpMaker-3K1/resolve/main/SimpMaker%203k2.ckpt
https://huggingface.co/ckpt/SimpMaker-3K1/resolve/main/SimpMaker%203k3.ckpt | {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/amethyst_vera/simp_maker_3k1/1_0_0/1.png
https://aica.pages.dev/creators/amethyst_vera/simp_maker_3k1/1_0_0/2.png
https://aica.pages.dev/creators/amethyst_vera/simp_maker_3k1/1_0_0/3.png
https://aica.pages.dev/creators/amethyst_vera/simp_maker_3k1/1_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/cafeai/cafe_instagram_sd_1_5/6_0_0/1.png
https://aica.pages.dev/creators/cafeai/cafe_instagram_sd_1_5/6_0_0/2.png
https://aica.pages.dev/creators/cafeai/cafe_instagram_sd_1_5/6_0_0/3.png
https://aica.pages.dev/creators/cafeai/cafe_instagram_sd_1_5/6_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/ray_hell/popup_book_diffusion/1_0_0/1.png
https://aica.pages.dev/creators/ray_hell/popup_book_diffusion/1_0_0/2.png
https://aica.pages.dev/creators/ray_hell/popup_book_diffusion/1_0_0/3.png
https://aica.pages.dev/creators/ray_hell/popup_book_diffusion/1_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/doubleyobro/yiffy_e18/1_0_0/1.png
https://aica.pages.dev/creators/doubleyobro/yiffy_e18/1_0_0/2.png
https://aica.pages.dev/creators/doubleyobro/yiffy_e18/1_0_0/3.png
https://aica.pages.dev/creators/doubleyobro/yiffy_e18/1_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/aipicasso/cool_japan_diffusion/2_1_0/1.png
https://aica.pages.dev/creators/aipicasso/cool_japan_diffusion/2_1_0/2.png
https://aica.pages.dev/creators/aipicasso/cool_japan_diffusion/2_1_0/3.png
https://aica.pages.dev/creators/aipicasso/cool_japan_diffusion/2_1_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/mehjourney_closed_ai/open_anime_journey/1_0_0/1.png
https://aica.pages.dev/creators/mehjourney_closed_ai/open_anime_journey/1_0_0/2.png
https://aica.pages.dev/creators/mehjourney_closed_ai/open_anime_journey/1_0_0/3.png
https://aica.pages.dev/creators/mehjourney_closed_ai/open_anime_journey/1_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/mocker/color_bomb_mix/1_0_0/1.png
https://aica.pages.dev/creators/mocker/color_bomb_mix/1_0_0/2.png
https://aica.pages.dev/creators/mocker/color_bomb_mix/1_0_0/3.png
https://aica.pages.dev/creators/mocker/color_bomb_mix/1_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/prompthero/openjourney/2_0_0/1.png
https://aica.pages.dev/creators/prompthero/openjourney/2_0_0/2.png
https://aica.pages.dev/creators/prompthero/openjourney/2_0_0/3.png
https://aica.pages.dev/creators/prompthero/openjourney/2_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/prompthero/midjourney_diffusion/4_0_0/1.png
https://aica.pages.dev/creators/prompthero/midjourney_diffusion/4_0_0/2.png
https://aica.pages.dev/creators/prompthero/midjourney_diffusion/4_0_0/3.png
https://aica.pages.dev/creators/prompthero/midjourney_diffusion/4_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/stabilityai/stable_diffusion_base/2_1_0/1.png
https://aica.pages.dev/creators/stabilityai/stable_diffusion_base/2_1_0/2.png
https://aica.pages.dev/creators/stabilityai/stable_diffusion_base/2_1_0/3.png
https://aica.pages.dev/creators/stabilityai/stable_diffusion_base/2_1_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/stabilityai/stable_diffusion_base/2_0_0/1.png
https://aica.pages.dev/creators/stabilityai/stable_diffusion_base/2_0_0/2.png
https://aica.pages.dev/creators/stabilityai/stable_diffusion_base/2_0_0/3.png
https://aica.pages.dev/creators/stabilityai/stable_diffusion_base/2_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/stabilityai/stable_diffusion/2_1_0/1.png
https://aica.pages.dev/creators/stabilityai/stable_diffusion/2_1_0/2.png
https://aica.pages.dev/creators/stabilityai/stable_diffusion/2_1_0/3.png
https://aica.pages.dev/creators/stabilityai/stable_diffusion/2_1_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/stabilityai/stable_diffusion/2_0_0/1.png
https://aica.pages.dev/creators/stabilityai/stable_diffusion/2_0_0/2.png
https://aica.pages.dev/creators/stabilityai/stable_diffusion/2_0_0/3.png
https://aica.pages.dev/creators/stabilityai/stable_diffusion/2_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/stabilityai/stable_diffusion_inpainting/2_0_0/1.png
https://aica.pages.dev/creators/stabilityai/stable_diffusion_inpainting/2_0_0/2.png
https://aica.pages.dev/creators/stabilityai/stable_diffusion_inpainting/2_0_0/3.png
https://aica.pages.dev/creators/stabilityai/stable_diffusion_inpainting/2_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/stabilityai/stable_diffusion_depth/2_0_0/1.png
https://aica.pages.dev/creators/stabilityai/stable_diffusion_depth/2_0_0/2.png
https://aica.pages.dev/creators/stabilityai/stable_diffusion_depth/2_0_0/3.png
https://aica.pages.dev/creators/stabilityai/stable_diffusion_depth/2_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/unknown/elldreths_lucid_mix/1_0_0/1.png
https://aica.pages.dev/creators/unknown/elldreths_lucid_mix/1_0_0/2.png
https://aica.pages.dev/creators/unknown/elldreths_lucid_mix/1_0_0/3.png
https://aica.pages.dev/creators/unknown/elldreths_lucid_mix/1_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/unknown/f222/1_0_0/1.png
https://aica.pages.dev/creators/unknown/f222/1_0_0/2.png
https://aica.pages.dev/creators/unknown/f222/1_0_0/3.png
https://aica.pages.dev/creators/unknown/f222/1_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/unknown/protogen/2_2_0/1.png
https://aica.pages.dev/creators/unknown/protogen/2_2_0/2.png
https://aica.pages.dev/creators/unknown/protogen/2_2_0/3.png
https://aica.pages.dev/creators/unknown/protogen/2_2_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/unknown/urp/1_0_0/1.png
https://aica.pages.dev/creators/unknown/urp/1_0_0/2.png
https://aica.pages.dev/creators/unknown/urp/1_0_0/3.png
https://aica.pages.dev/creators/unknown/urp/1_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/unknown/grapefruit/1_0_0/1.png
https://aica.pages.dev/creators/unknown/grapefruit/1_0_0/2.png
https://aica.pages.dev/creators/unknown/grapefruit/1_0_0/3.png
https://aica.pages.dev/creators/unknown/grapefruit/1_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/unknown/iz/1_0_0/1.png
https://aica.pages.dev/creators/unknown/iz/1_0_0/2.png
https://aica.pages.dev/creators/unknown/iz/1_0_0/3.png
https://aica.pages.dev/creators/unknown/iz/1_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/unknown/anything/3_0_0/1.png
https://aica.pages.dev/creators/unknown/anything/3_0_0/2.png
https://aica.pages.dev/creators/unknown/anything/3_0_0/3.png
https://aica.pages.dev/creators/unknown/anything/3_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/unknown/rbm/1_0_0/1.png
https://aica.pages.dev/creators/unknown/rbm/1_0_0/2.png
https://aica.pages.dev/creators/unknown/rbm/1_0_0/3.png
https://aica.pages.dev/creators/unknown/rbm/1_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/anashel/rpg/4_0_0/1.png
https://aica.pages.dev/creators/anashel/rpg/4_0_0/2.png
https://aica.pages.dev/creators/anashel/rpg/4_0_0/3.png
https://aica.pages.dev/creators/anashel/rpg/4_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/wavymulder/analog_diffusion/1_0_0/1.png
https://aica.pages.dev/creators/wavymulder/analog_diffusion/1_0_0/2.png
https://aica.pages.dev/creators/wavymulder/analog_diffusion/1_0_0/3.png
https://aica.pages.dev/creators/wavymulder/analog_diffusion/1_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://huggingface.co/ckpt/OrangeMixs/resolve/main/AbyssOrangeMix2_nsfw.safetensors
https://huggingface.co/ckpt/OrangeMixs/resolve/main/AbyssOrangeMix2_hard.safetensors
https://huggingface.co/ckpt/OrangeCocoaMix/resolve/main/OrangeCocoaMix2_hard.safetensors | {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/warrior_mama777/orange_mixs/1_0_0/1.png
https://aica.pages.dev/creators/warrior_mama777/orange_mixs/1_0_0/2.png
https://aica.pages.dev/creators/warrior_mama777/orange_mixs/1_0_0/3.png
https://aica.pages.dev/creators/warrior_mama777/orange_mixs/1_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/warrior_mama777/orange_mixs/3_0_0/1.png
https://aica.pages.dev/creators/warrior_mama777/orange_mixs/3_0_0/2.png
https://aica.pages.dev/creators/warrior_mama777/orange_mixs/3_0_0/3.png
https://aica.pages.dev/creators/warrior_mama777/orange_mixs/3_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/warrior_mama777/orange_mixs/2_0_0/1.png
https://aica.pages.dev/creators/warrior_mama777/orange_mixs/2_0_0/2.png
https://aica.pages.dev/creators/warrior_mama777/orange_mixs/2_0_0/3.png
https://aica.pages.dev/creators/warrior_mama777/orange_mixs/2_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/hassanblend/hassanblend/1_4_0/1.png
https://aica.pages.dev/creators/hassanblend/hassanblend/1_4_0/2.png
https://aica.pages.dev/creators/hassanblend/hassanblend/1_4_0/3.png
https://aica.pages.dev/creators/hassanblend/hassanblend/1_4_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/closertodeath/dpepmkmp/1_0_0/1.png
https://aica.pages.dev/creators/closertodeath/dpepmkmp/1_0_0/2.png
https://aica.pages.dev/creators/closertodeath/dpepmkmp/1_0_0/3.png
https://aica.pages.dev/creators/closertodeath/dpepmkmp/1_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/closertodeath/mouseymix/1_0_0/1.png
https://aica.pages.dev/creators/closertodeath/mouseymix/1_0_0/2.png
https://aica.pages.dev/creators/closertodeath/mouseymix/1_0_0/3.png
https://aica.pages.dev/creators/closertodeath/mouseymix/1_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/dreamlike_art/dreamlike_photoreal/2_0_0/1.png
https://aica.pages.dev/creators/dreamlike_art/dreamlike_photoreal/2_0_0/2.png
https://aica.pages.dev/creators/dreamlike_art/dreamlike_photoreal/2_0_0/3.png
https://aica.pages.dev/creators/dreamlike_art/dreamlike_photoreal/2_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/dreamlike_art/dreamlike_diffusion/1_0_0/1.png
https://aica.pages.dev/creators/dreamlike_art/dreamlike_diffusion/1_0_0/2.png
https://aica.pages.dev/creators/dreamlike_art/dreamlike_diffusion/1_0_0/3.png
https://aica.pages.dev/creators/dreamlike_art/dreamlike_diffusion/1_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/sandro_halpo/sam_does_art/3_0_0/1.png
https://aica.pages.dev/creators/sandro_halpo/sam_does_art/3_0_0/2.png
https://aica.pages.dev/creators/sandro_halpo/sam_does_art/3_0_0/3.png
https://aica.pages.dev/creators/sandro_halpo/sam_does_art/3_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/xxlmaes/vinte_protogen_mix/1_0_0/1.png
https://aica.pages.dev/creators/xxlmaes/vinte_protogen_mix/1_0_0/2.png
https://aica.pages.dev/creators/xxlmaes/vinte_protogen_mix/1_0_0/3.png
https://aica.pages.dev/creators/xxlmaes/vinte_protogen_mix/1_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/pmejna/graphic_art/1_0_0/1.png
https://aica.pages.dev/creators/pmejna/graphic_art/1_0_0/2.png
https://aica.pages.dev/creators/pmejna/graphic_art/1_0_0/3.png
https://aica.pages.dev/creators/pmejna/graphic_art/1_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/plasmo/woolitize/1_0_0/1.png
https://aica.pages.dev/creators/plasmo/woolitize/1_0_0/2.png
https://aica.pages.dev/creators/plasmo/woolitize/1_0_0/3.png
https://aica.pages.dev/creators/plasmo/woolitize/1_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
https://aica.pages.dev/creators/plasmo/food_crit/1_0_0/1.png
https://aica.pages.dev/creators/plasmo/food_crit/1_0_0/2.png
https://aica.pages.dev/creators/plasmo/food_crit/1_0_0/3.png
https://aica.pages.dev/creators/plasmo/food_crit/1_0_0/4.png
| {
"repo_name": "camenduru/ai-creator-archive",
"stars": "27",
"repo_language": "Jupyter Notebook",
"file_name": "images.txt",
"mime_type": "text/plain"
} |
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 17 19:59:33 2018
@author: mesut
"""
import yaml
import cv2
#assert cv2.__version__[0] == '3', 'The fisheye module requires opencv version >= 3.0.0'
import numpy as np
import glob
CHECKERBOARD = (6,9)
subpix_criteria = (cv2.TERM_CRITERIA_EPS+cv2.TERM_CRITERIA_MAX_ITER, 30, 0.1)
calibration_flags = cv2.fisheye.CALIB_RECOMPUTE_EXTRINSIC+cv2.fisheye.CALIB_CHECK_COND+cv2.fisheye.CALIB_FIX_SKEW
objp = np.zeros((1, CHECKERBOARD[0]*CHECKERBOARD[1], 3), np.float32)
objp[0,:,:2] = np.mgrid[0:CHECKERBOARD[0], 0:CHECKERBOARD[1]].T.reshape(-1, 2)
_img_shape = None
objpoints = [] # 3d point in real world space
imgpoints = [] # 2d points in image plane.
images = glob.glob('images/*.png')
for fname in images:
img = cv2.imread(fname)
if _img_shape == None:
_img_shape = img.shape[:2]
else:
assert _img_shape == img.shape[:2], "All images must share the same size."
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# Chess board corners
ret, corners = cv2.findChessboardCorners(gray, CHECKERBOARD, cv2.CALIB_CB_ADAPTIVE_THRESH+cv2.CALIB_CB_FAST_CHECK+cv2.CALIB_CB_NORMALIZE_IMAGE)
# Image points (after refinin them)
if ret == True:
objpoints.append(objp)
cv2.cornerSubPix(gray,corners,(3,3),(-1,-1),subpix_criteria)
imgpoints.append(corners)
N_OK = len(objpoints)
K = np.zeros((3, 3))
D = np.zeros((4, 1))
rvecs = [np.zeros((1, 1, 3), dtype=np.float64) for i in range(N_OK)]
tvecs = [np.zeros((1, 1, 3), dtype=np.float64) for i in range(N_OK)]
rms, _, _, _, _ = \
cv2.fisheye.calibrate(
objpoints,
imgpoints,
gray.shape[::-1],
K,
D,
rvecs,
tvecs,
calibration_flags,
(cv2.TERM_CRITERIA_EPS+cv2.TERM_CRITERIA_MAX_ITER, 30, 1e-6)
)
print("Found " + str(N_OK) + " valid images for calibration")
print("DIM=" + str(_img_shape[::-1]))
print("K=np.array(" + str(K.tolist()) + ")")
print("D=np.array(" + str(D.tolist()) + ")")
DIM=_img_shape[::-1]
balance=1
dim2=None
dim3=None
img = cv2.imread("images/test.png")
dim1 = img.shape[:2][::-1] #dim1 is the dimension of input image to un-distort
assert dim1[0]/dim1[1] == DIM[0]/DIM[1], "Image to undistort needs to have same aspect ratio as the ones used in calibration"
if not dim2:
dim2 = dim1
if not dim3:
dim3 = dim1
scaled_K = K * dim1[0] / DIM[0] # The values of K is to scale with image dimension.
scaled_K[2][2] = 1.0 # Except that K[2][2] is always 1.0
# This is how scaled_K, dim2 and balance are used to determine the final K used to un-distort image. OpenCV document failed to make this clear!
new_K = cv2.fisheye.estimateNewCameraMatrixForUndistortRectify(scaled_K, D, dim2, np.eye(3), balance=balance)
map1, map2 = cv2.fisheye.initUndistortRectifyMap(scaled_K, D, np.eye(3), new_K, dim3, cv2.CV_16SC2)
undistorted_img = cv2.remap(img, map1, map2, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT)
data = {'dim1': dim1,
'dim2':dim2,
'dim3': dim3,
'K': np.asarray(K).tolist(),
'D':np.asarray(D).tolist(),
'new_K':np.asarray(new_K).tolist(),
'scaled_K':np.asarray(scaled_K).tolist(),
'balance':balance}
import json
with open("fisheye_calibration_data.json", "w") as f:
json.dump(data, f)
cv2.imshow("undistorted", undistorted_img)
#img2 = cv2.imread("2.png")
#cv2.imshow("none undistorted", img2)
cv2.waitKey(0)
cv2.destroyAllWindows()
| {
"repo_name": "kostecky/VBT-Barbell-Tracker",
"stars": "58",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
import cv2
import numpy as np
def nothing(x):
pass
# Load image
image = cv2.imread('2.png')
# Create a window
cv2.namedWindow('image')
# Create trackbars for color change
# Hue is from 0-179 for Opencv
cv2.createTrackbar('HMin', 'image', 0, 179, nothing)
cv2.createTrackbar('SMin', 'image', 0, 255, nothing)
cv2.createTrackbar('VMin', 'image', 0, 255, nothing)
cv2.createTrackbar('HMax', 'image', 0, 179, nothing)
cv2.createTrackbar('SMax', 'image', 0, 255, nothing)
cv2.createTrackbar('VMax', 'image', 0, 255, nothing)
# Set default value for Max HSV trackbars
cv2.setTrackbarPos('HMax', 'image', 179)
cv2.setTrackbarPos('SMax', 'image', 255)
cv2.setTrackbarPos('VMax', 'image', 255)
# Initialize HSV min/max values
hMin = sMin = vMin = hMax = sMax = vMax = 0
phMin = psMin = pvMin = phMax = psMax = pvMax = 0
while(1):
# Get current positions of all trackbars
hMin = cv2.getTrackbarPos('HMin', 'image')
sMin = cv2.getTrackbarPos('SMin', 'image')
vMin = cv2.getTrackbarPos('VMin', 'image')
hMax = cv2.getTrackbarPos('HMax', 'image')
sMax = cv2.getTrackbarPos('SMax', 'image')
vMax = cv2.getTrackbarPos('VMax', 'image')
# Set minimum and maximum HSV values to display
lower = np.array([hMin, sMin, vMin])
upper = np.array([hMax, sMax, vMax])
# Convert to HSV format and color threshold
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv, lower, upper)
result = cv2.bitwise_and(image, image, mask=mask)
# Print if there is a change in HSV value
if((phMin != hMin) | (psMin != sMin) | (pvMin != vMin) | (phMax != hMax) | (psMax != sMax) | (pvMax != vMax) ):
print("(hMin = %d , sMin = %d, vMin = %d), (hMax = %d , sMax = %d, vMax = %d)" % (hMin , sMin , vMin, hMax, sMax , vMax))
phMin = hMin
psMin = sMin
pvMin = vMin
phMax = hMax
psMax = sMax
pvMax = vMax
# Display result image
cv2.imshow('image', result)
if cv2.waitKey(10) & 0xFF == ord('q'):
break
cv2.destroyAllWindows()
| {
"repo_name": "kostecky/VBT-Barbell-Tracker",
"stars": "58",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
imutils==0.5.3
numpy==1.17.0
opencv-python-headless==4.2.0.32
simpleaudio==1.0.4
| {
"repo_name": "kostecky/VBT-Barbell-Tracker",
"stars": "58",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
from collections import deque
import numpy as np
import argparse
import imutils
from imutils.video import FPS
import cv2
import math
import json
import simpleaudio as sa
import wave
def is_inflection(velocity, opposite_direction_is_true):
if opposite_direction_is_true:
if velocity < 0:
return True
else:
return False
if opposite_direction_is_true is False:
if velocity >= 0:
return True
else:
return False
def analyze_for_rep(history, reps):
pos = 0
first_phase = False
second_phase = False
concentric_first_lift = False
displacement = 0
first_phase_disp = 0
second_phase_disp = 0
velocities = []
error = 0
vector_threshold = 8
print("Analyzing movement for rep...")
# We need at least vector_threshold points to determine a direction and almost definitely many more for a complete rep
if len(history) < 2 * vector_threshold:
return(False, (0.0, 0.0, 0))
# Method
# 1. determine direction by looking at last X points
# 2. keep reading and ensure each point matches initial direction up until inflection point
# 3. Read all points after inflection up until next inflection or end of history
# 4. Use criteria to determine if it's a rep
for direction_pos in range(1, vector_threshold):
displacement += history[-direction_pos][2]
if displacement > 0:
concentric_first_lift = True
elif displacement < 0:
concentric_first_lift = False
else:
# need more data to determine if it's a rep
return(False, (0.0, 0.0, 0))
while True:
pos += 1
if pos > len(history):
break
print(history[-pos])
if not first_phase:
# Count at least 1 first phase point before inflection and at least 100mm of displacement
if is_inflection(history[-pos][2], concentric_first_lift) and first_phase_disp > 200:
print("First Phase Displacement: {}".format(first_phase_disp))
first_phase = True
else:
if is_inflection(history[-pos][2], concentric_first_lift):
if error > 3:
print("Found 3 error points that go in the opposite direction")
break
error += 1
continue
else:
first_phase_disp += abs(history[-pos][1])
if concentric_first_lift:
velocities.append(abs(history[-pos][2]))
continue
if not second_phase:
# Count at least 1 second phase point before first inflection and 200mm of displacement
# or we're on the last point in history
if (is_inflection(history[-pos][2], not concentric_first_lift) and second_phase_disp > 200) or (pos == len(history) and second_phase_disp > 200):
second_phase = True
print("Second Phase Displacement: {}".format(second_phase_disp))
else:
second_phase_disp += abs(history[-pos][1])
if not concentric_first_lift:
velocities.append(abs(history[-pos][2]))
continue
# All this criteria should give us a high probability of counting a rep
# Move more than 100mm, difference between eccentric and concentric displacement < 200mm
if first_phase and second_phase and abs(second_phase_disp - first_phase_disp) < 100:
print("Found rep {}! first: {} mm, second: {} mm".format(reps + 1, first_phase_disp, second_phase_disp))
if concentric_first_lift:
concentric_disp = first_phase_disp
else:
concentric_disp = second_phase_disp
avg_vel = sum(velocities) / len(velocities)
peak_vel = max(velocities)
return(True, (avg_vel, peak_vel, concentric_disp))
return(False, (0.0, 0.0, 0))
def analyze_for_x_movement(history):
# When there is a pause or inflection, let's check our previous points to see
# if there is more movement in the x direction than the y.
# This would indicate deracking/racking/setting up and we want to clear the history
# of any small movements that would confuse the algorithm from detecting the start
# of a rep, whether it be a concentric or eccentric first exercise.
pos = 0
x_displacement = 0
y_displacement = 0
print("Analyzing movement for large x displacement over y")
while pos < len(history):
x_displacement += abs(history[pos][0])
y_displacement += abs(history[pos][1])
pos += 1
if (x_displacement - y_displacement) >= 0:
return True
return False
ap = argparse.ArgumentParser()
ap.add_argument("-v", "--video", help="path to the (optional) video file")
args = vars(ap.parse_args())
# Calibrate our camera
with open("fisheye_calibration_data.json", "r") as f:
calibration_data = json.load(f)
print(calibration_data)
# Need to scale K, D, and dim
# Dim should be 800x600
# Original calibration used an image of 5120 × 3840 so same aspect ratio, which is good
dim = (800, 600)
scaled_K = np.asarray(calibration_data['K']) * dim[0] / 5120 # The values of K is to scale with image dimension.
scaled_K[2][2] = 1.0 # Except that K[2][2] is always 1.0
# This is how scaled_K, dim2 and balance are used to determine the final K used to un-distort image. OpenCV document failed to make this clear!
new_K = cv2.fisheye.estimateNewCameraMatrixForUndistortRectify(scaled_K, np.asarray(calibration_data['D']), dim, np.eye(3), balance=calibration_data['balance'])
calibration_map1, calibration_map2 = cv2.fisheye.initUndistortRectifyMap(scaled_K, np.asarray(calibration_data['D']), np.eye(3), new_K, dim, cv2.CV_16SC2)
# Different lighting conditions
# 1.png
# (hMin = 40 , sMin = 46, vMin = 0), (hMax = 86 , sMax = 88, vMax = 181)
# 2.png
# (hMin = 33 , sMin = 48, vMin = 103), (hMax = 64 , sMax = 156, vMax = 255)
greenLower = (33, 46, 80)
greenUpper = (86, 156, 255)
if not args.get("video", False):
camera = cv2.VideoCapture(0)
else:
camera = cv2.VideoCapture(args["video"])
# Read first image
(grabbed, frame) = camera.read()
frameCount = int(camera.get(cv2.CAP_PROP_FRAME_COUNT))
vid_fps = int(camera.get(cv2.CAP_PROP_FPS))
print(vid_fps)
# override with 25 fps
vid_fps = 25
fps = FPS().start()
points = deque(maxlen=10000)
last_x = None
last_y = None
ref_radius = None
velocity = 0.0
x_velocity = 0.0
y_velocity = 0.0
y_vector_up = False
moving = False
analyzed_rep = False
barbell_radius = 25
reps = 0
history = []
# How many milliseconds at rest until we consider it a rep?
rep_rest_threshold = 80.0
rep_rest_reset_threshold = 120000
rep_rest_time = 0.0
avg_vel = 0.0
peak_vel = 0.0
displacement = 0
avg_velocities = []
peak_velocities = []
velocity_loss_threshold = 20
in_range = True
end_set = False
colour = (0, 255, 0)
avg_velocity = 0
first_velocity = 0
avg_velocity_loss = 0
cv2.namedWindow("output", cv2.WINDOW_OPENGL)
while True:
(grabbed, frame) = camera.read()
if args.get("video") and not grabbed:
break
# video image is 2560 × 1920 = 1.3333333...
# should be 800/600 to maintain aspect ratio
frame = imutils.resize(frame, width=800)
# Remove barrel/fisheye distortion
frame = cv2.remap(frame, calibration_map1, calibration_map2, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT)
# Crop the frame to get rid of the deadspace from undistorting it
frame = frame[100:500, 100:700]
frame = imutils.resize(frame, width=800)
im_height, im_width, _ = frame.shape
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv, greenLower, greenUpper)
mask = cv2.erode(mask, None, iterations=2)
mask = cv2.dilate(mask, None, iterations=2)
cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
center = None
# Our barbell end is 5cm in diameter
# fps = camera.get(cv2.CAP_PROP_FPS)
# Each frame is 1/fps seconds in length
# 1. Calculate the pixel distance between last position and current position. That provides pixels travelled in 1/FPS seconds.
# That gives pixel distance between frames
# 2. How many pixels does the circle diameter occupy? Divide by 50mm and we get pixels/mm. Invert and we get mm/pixel
# Multiply 1 by 2 and we get instantaneous mm/s every 1/FPS
if len(cnts) > 0:
c = max(cnts, key=cv2.contourArea)
((x, y), radius) = cv2.minEnclosingCircle(c)
if last_x is None:
last_x = x
last_y = y
velocity = 0
y_velocity = 0
rep = False
if reps == 0:
in_range = True
avg_velocity = 0
peak_velocity = 0
avg_velocity_loss = 0
peak_velocity_loss = 0
end_set = False
colour = (0, 255, 0)
if radius / im_height > 0.0125:
# Take the first radius as the reference radius as it's stationary and most accurately represents dimensions
if ref_radius is None:
ref_radius = radius
mmpp = barbell_radius / ref_radius
print("ref_radius: {:.2f}, mmpp: {:.2f}".format(ref_radius, mmpp))
x_disp = last_x - x
y_disp = last_y - y
y_distance = y_disp * mmpp
x_distance = x_disp * mmpp
distance = math.sqrt(x_disp ** 2 + y_disp ** 2) * mmpp
if abs(y_distance) > barbell_radius / 4:
moving = True
analyzed_rep = False
velocity = distance * vid_fps / 1000
y_velocity = y_distance * vid_fps / 1000
rep_rest_time = 0.0
if y_velocity < 0.01 and y_velocity > -0.01:
moving = False
y_velocity = 0
rep_rest_time += 1 / vid_fps * 1000
print("distance: {} mm, velocity: {:.2f} m/s, x_dist: {} mm, y_dist: {} mm, y_vel: {:.2f} m/s".format(int(distance), float(velocity), int(x_distance), int(y_distance), float(y_velocity)))
history.append((int(x_distance), int(y_distance), y_velocity))
if (y_velocity > 0 and y_vector_up is False) or (y_velocity < 0 and y_vector_up is True):
y_vector_up = not y_vector_up
(rep, ret) = analyze_for_rep(history, reps)
else:
# Only log 0 once
if moving is True:
history.append((0, 0, 0))
moving = False
# Count how many milliseconds we're at 0 velocity
rep_rest_time += 1 / vid_fps * 1000
# analyze for last rep when we appear to rest for a threshold time
if (rep_rest_time > rep_rest_threshold) and not analyzed_rep:
analyzed_rep = True
if analyze_for_x_movement(history):
print("Detected significant x movement over y, resetting history...")
history = []
(rep, ret) = analyze_for_rep(history, reps)
if rep:
history = []
reps += 1
avg_velocities.append(ret[0])
peak_velocities.append(ret[1])
displacement = ret[2]
if reps == 1:
avg_velocity = avg_velocities[0]
peak_velocity = peak_velocities[0]
first_velocity = avg_velocity
if avg_velocity > 0.5:
in_range = True
wave_read = wave.open('good.wav', 'rb')
else:
in_range = False
wave_read = wave.open('bad.wav', 'rb')
else:
avg_velocity = avg_velocities[-1]
peak_velocity = peak_velocities[-1]
avg_velocity_loss = (avg_velocities[0] - avg_velocities[-1]) / avg_velocities[0] * 100
peak_velocity_loss = (peak_velocities[0] - peak_velocities[-1]) / peak_velocities[0] * 100
if avg_velocity_loss > velocity_loss_threshold:
end_set = True
wave_read = wave.open('bad.wav', 'rb')
colour = (0, 0, 255)
else:
end_set = False
wave_read = wave.open('good.wav', 'rb')
colour = (0, 255, 0)
audio_data = wave_read.readframes(wave_read.getnframes())
num_channels = wave_read.getnchannels()
bytes_per_sample = wave_read.getsampwidth()
sample_rate = wave_read.getframerate()
wave_obj = sa.WaveObject(audio_data, num_channels, bytes_per_sample, sample_rate)
play_obj = wave_obj.play()
last_x = x
last_y = y
cv2.circle(frame, (int(x), int(y)), int(ref_radius), (0, 255, 255), 2)
path_color = (0, 255, 255)
center = (int(x), int(y))
points.appendleft(center)
for i in range(1, len(points)):
if points[i - 1] is None or points[i] is None:
continue
cv2.line(frame, points[i - 1], points[i], path_color, 2)
cur_frame = camera.get(cv2.CAP_PROP_POS_FRAMES)
fps.update()
fps.stop()
info = [
("First set above 0.5 m/s", "{}".format(in_range), (0, 255, 0)),
("First set velocity", "{:.2f} m/s".format(first_velocity), (0, 255, 0)),
("Last AVG Con Velocity", "{:.2f} m/s".format(avg_velocity), (0, 255, 0)),
# ("Last PEAK Con Velocity", "{:.2f} m/s".format(peak_velocity), (0, 255, 0)),
("Last Displacement", "{:.2f} mm".format(displacement), (0, 255, 0)),
("AVG Velocity Loss", "{:.2f} %".format(avg_velocity_loss), (0, 255, 0)),
# ("PEAK Velocity Loss", "{:.2f} %".format(peak_velocity_loss), (0, 255, 0)),
("Reps", "{}".format(reps), (0, 255, 0)),
# ("FPS", "{:.2f}".format(fps.fps()), (0, 255, 0)),
# ("Y Velocity", "{:.2f} m/s".format(y_velocity), (0, 255, 0)),
("END SET", "{}".format(end_set), colour),
]
# loop over the info tuples and draw them on our frame
for (i, (k, v, c)) in enumerate(info):
text = "{}: {}".format(k, v)
cv2.putText(frame, text, (10, im_height - ((i * 40) + 20)),
cv2.FONT_HERSHEY_SIMPLEX, 1.5, c, 2)
cv2.imshow("output", frame)
cv2.resizeWindow("output", (1500, 1000))
# cv2.imshow("Mask", mask)
key = cv2.waitKey(1) & 0xFF
if key == ord("q"):
break
elif key == ord("r") or (rep_rest_time > rep_rest_reset_threshold):
reps = 0
avg_velocities = []
first_velocity = 0
peak_velocities = []
points.clear()
rep_rest_time = 0.0
camera.release()
cv2.destroyAllWindows()
| {
"repo_name": "kostecky/VBT-Barbell-Tracker",
"stars": "58",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# VBT-Barbell-Tracker
A proof of concept app to optically track a barbell through its range of motion using OpenCV to give the lifter realtime feedback on concentric avg velocity, cutoff velocity, and displacement for a Velocity Based Training program.
![Demo](/images/demo.gif?raw=true "Squat Demo")
## How it works
The app will detect a solid green area painted on to the end of your barbell. Given the measured diameter of this circle it will determine the pixel per mm scale to calculate distances and velocities of the barbell.
Movement of the barbell is continuously scanned to see if a lift is happening. When it detects a rep, it displays the most commonly referenced VBT metrics and informs you if your lifts are within 0.5-0.75 m/s as well as if they fall below a 20% velocity cutoff. There is an audible signal that is played of your lifts comply or fall outside of the range so you know when to terminate your set without having to keep your eyes on the computer.
The display tells you what rep you're on, the displacement of the bar, the velocity of the concentric part of the lift and whether the art should be terminated.
Once the barbell is at rest for 2 minutes, the counters and path tracking reset. You can also reset it by hand by pressing 'r'
## Motivation
- Optimize workouts by taking meaningful measurements, getting live feedback, and putting in minimum effective effort
- Autoregulation of load-volume
- Injury reduction
- Initial exposure to OpenCV and optical processing
- Initial exposure to training CNNs
- Avoid the purchase of a hardware unit like openbarbell, push, etc.
## Journey
- Started off wanting the app to auto-detect a wide variety of barbells in generalized surroundings
- Spent a week playing with Google Colab and training CNNs to do so. Moderate success, lots of GPU power needed and way too slow for running on CPU only devices
- Spent time playing with many different tracking models in OpenCV. None were reliable in a variety of scenarios.
- Realized that tracking a differentiated colour and shape was very fast, didn't require a GPU and was orders of magnitude more reliable than any tracking algorithm. Simple wins with a bit more initial setup, but it was worth it.
## VBT
https://www.scienceforsport.com/velocity-based-training
## Requirements
- Python 3.7
- A webcam or IP camera that supports RTSP
- Lime Green paper/paint/etc.
## Installation
1. Create a new python 3.7 virtualenv
```
mkvirtualenv VBT-barbell-tracker
```
2. Install python requirements
```
pip install -r requirements.txt
```
3. Generate intrinsic camera values to undistort fisheye/barrel effect
Generate intrinsic camera distortion values to remove any barrel/fisheye distortion that your camera may have. You can easily spot this by looking at the outer perimeter of your camera to see if straight lines appear curved.
a. Using your webcam, take 10 or more snapshots of the chessboard printout. Save the images as `.png` files. Adhere the printout to a board, so it's very flat. The images should be taken to ensure you cover all areas of your image plane, paying attention to the outer perimeter where most of the distortion will take place. You can find the opencv chessboard image here: https://github.com/opencv/opencv/blob/master/doc/pattern.png
b. Place these images in the `./images/` directory
c. Take another image of the area you want to undistort as a test. Save it as `test.png` and place it in the `./images/` directory.
d. Run the `python undistort_fisheye.py` script to discover the intrinsict values. They will be dumped out in a json file called `fisheye_calibration_data.json`
4. Place lime green paper/paint/etc. on the end of the barbell that faces the camera, ensuring that it covers the entire face of it. Then, take a measurement of the diameter of the face of the barbell end you covered. Mine comes out to 50mm, so the radius would be 25mm. This is **essential** to calibrating the distance scale within the app. You can use any colour you want, but you will have to adjust parameters accordingly. The idea here is to use a colour that is highly differentiated from anything being captured in your surroundings or your clothing.
## Usage
```
workon VBT-barbell-tracker
```
### Running it on a video
```
python vbt_barbell_tracker.py --video press.mp4
```
### Running it with your webcam
```
python VBT-barbell-tracker.py
```
### Running it on a RTSP stream
```
python VBT-barbell-tracker.py --video 'rtsp://USER:[email protected]?tcp'
```
## Hotkeys
`r` Clear set and reset all counters and bar tracker. This also happens automatically after 2 minutes of no movement.
## Roadmap
- [ ] Refactor POC
- [ ] Use QT or simpleGUI to reformulate into a proper app with input/output to adjust parameters on the fly
| {
"repo_name": "kostecky/VBT-Barbell-Tracker",
"stars": "58",
"repo_language": "Python",
"file_name": "README.md",
"mime_type": "text/plain"
} |
[package]
name = "winapi-util"
version = "0.1.5" #:version
authors = ["Andrew Gallant <[email protected]>"]
description = "A dumping ground for high level safe wrappers over winapi."
documentation = "https://docs.rs/winapi-util"
homepage = "https://github.com/BurntSushi/winapi-util"
repository = "https://github.com/BurntSushi/winapi-util"
readme = "README.md"
keywords = ["windows", "winapi", "util", "win"]
license = "Unlicense/MIT"
categories = ["os::windows-apis", "external-ffi-bindings"]
edition = "2018"
[target.'cfg(windows)'.dependencies.winapi]
version = "0.3"
features = [
"std",
"consoleapi",
"errhandlingapi",
"fileapi",
"minwindef",
"processenv",
"winbase",
"wincon",
"winerror",
"winnt",
]
[package.metadata.docs.rs]
targets = ["x86_64-pc-windows-msvc"]
| {
"repo_name": "BurntSushi/winapi-util",
"stars": "54",
"repo_language": "Rust",
"file_name": "file.rs",
"mime_type": "text/plain"
} |
max_width = 79
use_small_heuristics = "max"
| {
"repo_name": "BurntSushi/winapi-util",
"stars": "54",
"repo_language": "Rust",
"file_name": "file.rs",
"mime_type": "text/plain"
} |
This project is dual-licensed under the Unlicense and MIT licenses.
You may use this code under the terms of either license.
| {
"repo_name": "BurntSushi/winapi-util",
"stars": "54",
"repo_language": "Rust",
"file_name": "file.rs",
"mime_type": "text/plain"
} |
winapi-util
===========
This crate provides a smattering of safe wrappers around various parts of the
[winapi](https://crates.io/crates/winapi) crate.
[![Build status](https://github.com/BurntSushi/winapi-util/workflows/ci/badge.svg)](https://github.com/BurntSushi/winapi-util/actions)
[![](http://meritbadge.herokuapp.com/winapi-util)](https://crates.io/crates/winapi-util)
Dual-licensed under MIT or the [UNLICENSE](http://unlicense.org).
### Documentation
https://docs.rs/winapi-util
### Usage
Add this to your `Cargo.toml`:
```toml
[dependencies]
winapi-util = "0.1"
```
### Notes
This crate was born out of frustration with having to write lots of little
ffi utility bindings in a variety of crates in order to get Windows support.
Eventually, I started needing to copy & paste a lot of those utility routines.
Since they are utility routines, they often don't make sense to expose directly
in the crate in which they are defined. Instead of continuing this process,
I decided to make a crate instead.
Normally, I'm not a huge fan of "utility" crates like this that don't have a
well defined scope, but this is primarily a practical endeavor to make it
easier to isolate Windows specific ffi code.
While I don't have a long term vision for this crate, I will welcome additional
PRs that add more high level routines/types on an as-needed basis.
**WARNING:** I am not a Windows developer, so extra review to make sure I've
got things right is most appreciated.
### Minimum Rust version policy
This crate's minimum supported `rustc` version is `1.34.0`.
The current policy is that the minimum Rust version required to use this crate
can be increased in non-breaking version updates. For example, if `crate 1.0`
requires Rust 1.20.0, then `crate 1.0.z` for all values of `z` will also
require Rust 1.20.0 or newer. However, `crate 1.y` for `y > 0` may require a
newer minimum version of Rust.
In general, this crate will be conservative with respect to the minimum
supported version of Rust.
| {
"repo_name": "BurntSushi/winapi-util",
"stars": "54",
"repo_language": "Rust",
"file_name": "file.rs",
"mime_type": "text/plain"
} |
name: ci
on:
pull_request:
push:
branches:
- master
schedule:
- cron: '00 01 * * *'
jobs:
test:
name: test
runs-on: ${{ matrix.os }}
strategy:
matrix:
build:
- pinned
- stable
- beta
- nightly
- win-gnu
- linux
- macos
include:
- build: pinned
os: windows-2019
rust: 1.34.0
- build: stable
os: windows-2019
rust: stable
- build: beta
os: windows-2019
rust: beta
- build: nightly
os: ubuntu-18.04
rust: nightly
- build: win-gnu
os: windows-2019
rust: stable-x86_64-gnu
- build: linux
os: ubuntu-18.04
rust: stable
- build: macos
os: macos-latest
rust: stable
steps:
- name: Checkout repository
uses: actions/checkout@v2
with:
fetch-depth: 1
- name: Install Rust
uses: hecrj/setup-rust-action@v1
with:
rust-version: ${{ matrix.rust }}
- run: cargo build --verbose
- run: cargo doc --verbose
- run: cargo test --verbose
rustfmt:
name: rustfmt
runs-on: ubuntu-18.04
steps:
- name: Checkout repository
uses: actions/checkout@v2
with:
fetch-depth: 1
- name: Install Rust
uses: hecrj/setup-rust-action@v1
with:
rust-version: stable
- name: Install rustfmt
run: rustup component add rustfmt
- name: Check formatting
run: |
cargo fmt --all -- --check
| {
"repo_name": "BurntSushi/winapi-util",
"stars": "54",
"repo_language": "Rust",
"file_name": "file.rs",
"mime_type": "text/plain"
} |
use std::fs::File;
use std::io;
use std::os::windows::io::{
AsRawHandle, FromRawHandle, IntoRawHandle, RawHandle,
};
use std::path::Path;
use std::process;
/// A handle represents an owned and valid Windows handle to a file-like
/// object.
///
/// When an owned handle is dropped, then the underlying raw handle is closed.
/// To get a borrowed handle, use `HandleRef`.
#[derive(Debug)]
pub struct Handle(File);
impl AsRawHandle for Handle {
fn as_raw_handle(&self) -> RawHandle {
self.0.as_raw_handle()
}
}
impl FromRawHandle for Handle {
unsafe fn from_raw_handle(handle: RawHandle) -> Handle {
Handle(File::from_raw_handle(handle))
}
}
impl IntoRawHandle for Handle {
fn into_raw_handle(self) -> RawHandle {
self.0.into_raw_handle()
}
}
impl Handle {
/// Create an owned handle to the given file.
///
/// When the returned handle is dropped, the file is closed.
///
/// Note that if the given file represents a handle to a directory, then
/// it is generally required that it have been opened with the
/// [`FILE_FLAG_BACKUP_SEMANTICS`] flag in order to use it in various
/// calls such as `information` or `typ`. To have this done automatically
/// for you, use the `from_path_any` constructor.
///
/// [`FILE_FLAG_BACKUP_SEMANTICS`]: https://docs.microsoft.com/en-us/windows/desktop/api/FileAPI/nf-fileapi-createfilea
pub fn from_file(file: File) -> Handle {
Handle(file)
}
/// Open a file to the given file path, and return an owned handle to that
/// file.
///
/// When the returned handle is dropped, the file is closed.
///
/// If there was a problem opening the file, then the corresponding error
/// is returned.
pub fn from_path<P: AsRef<Path>>(path: P) -> io::Result<Handle> {
Ok(Handle::from_file(File::open(path)?))
}
/// Like `from_path`, but supports opening directory handles as well.
///
/// If you use `from_path` on a directory, then subsequent queries using
/// that handle will fail.
pub fn from_path_any<P: AsRef<Path>>(path: P) -> io::Result<Handle> {
use std::fs::OpenOptions;
use std::os::windows::fs::OpenOptionsExt;
use winapi::um::winbase::FILE_FLAG_BACKUP_SEMANTICS;
let file = OpenOptions::new()
.read(true)
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
.open(path)?;
Ok(Handle::from_file(file))
}
/// Return this handle as a standard `File` reference.
pub fn as_file(&self) -> &File {
&self.0
}
/// Return this handle as a standard `File` mutable reference.
pub fn as_file_mut(&mut self) -> &mut File {
&mut self.0
}
}
/// Represents a borrowed and valid Windows handle to a file-like object, such
/// as stdin/stdout/stderr or an actual file.
///
/// When a borrowed handle is dropped, then the underlying raw handle is
/// **not** closed. To get an owned handle, use `Handle`.
#[derive(Debug)]
pub struct HandleRef(HandleRefInner);
/// The representation of a HandleRef, on which we define a custom Drop impl
/// that avoids closing the underlying raw handle.
#[derive(Debug)]
struct HandleRefInner(Option<File>);
impl Drop for HandleRefInner {
fn drop(&mut self) {
self.0.take().unwrap().into_raw_handle();
}
}
impl AsRawHandle for HandleRef {
fn as_raw_handle(&self) -> RawHandle {
self.as_file().as_raw_handle()
}
}
impl Clone for HandleRef {
fn clone(&self) -> HandleRef {
unsafe { HandleRef::from_raw_handle(self.as_raw_handle()) }
}
}
impl HandleRef {
/// Create a borrowed handle to stdin.
///
/// When the returned handle is dropped, stdin is not closed.
pub fn stdin() -> HandleRef {
unsafe { HandleRef::from_raw_handle(io::stdin().as_raw_handle()) }
}
/// Create a handle to stdout.
///
/// When the returned handle is dropped, stdout is not closed.
pub fn stdout() -> HandleRef {
unsafe { HandleRef::from_raw_handle(io::stdout().as_raw_handle()) }
}
/// Create a handle to stderr.
///
/// When the returned handle is dropped, stderr is not closed.
pub fn stderr() -> HandleRef {
unsafe { HandleRef::from_raw_handle(io::stderr().as_raw_handle()) }
}
/// Create a borrowed handle to the given file.
///
/// When the returned handle is dropped, the file is not closed.
pub fn from_file(file: &File) -> HandleRef {
unsafe { HandleRef::from_raw_handle(file.as_raw_handle()) }
}
/// Create a borrowed handle from the given raw handle.
///
/// Note that unlike the `FromRawHandle` trait, this constructor does
/// **not** consume ownership of the given handle. That is, when the
/// borrowed handle created by this constructor is dropped, the underlying
/// handle will not be closed.
///
/// # Safety
///
/// This is unsafe because there is no guarantee that the given raw handle
/// is a valid handle. The caller must ensure this is true before invoking
/// this constructor.
pub unsafe fn from_raw_handle(handle: RawHandle) -> HandleRef {
HandleRef(HandleRefInner(Some(File::from_raw_handle(handle))))
}
/// Return this handle as a standard `File` reference.
pub fn as_file(&self) -> &File {
(self.0).0.as_ref().unwrap()
}
/// Return this handle as a standard `File` mutable reference.
pub fn as_file_mut(&mut self) -> &mut File {
(self.0).0.as_mut().unwrap()
}
}
/// Construct borrowed and valid Windows handles from file-like objects.
pub trait AsHandleRef {
/// A borrowed handle that wraps the raw handle of the `Self` object.
fn as_handle_ref(&self) -> HandleRef;
/// A convenience routine for extracting a `HandleRef` from `Self`, and
/// then extracting a raw handle from the `HandleRef`.
fn as_raw(&self) -> RawHandle {
self.as_handle_ref().as_raw_handle()
}
}
impl<'a, T: AsHandleRef> AsHandleRef for &'a T {
fn as_handle_ref(&self) -> HandleRef {
(**self).as_handle_ref()
}
}
impl AsHandleRef for Handle {
fn as_handle_ref(&self) -> HandleRef {
unsafe { HandleRef::from_raw_handle(self.as_raw_handle()) }
}
}
impl AsHandleRef for HandleRef {
fn as_handle_ref(&self) -> HandleRef {
self.clone()
}
}
impl AsHandleRef for File {
fn as_handle_ref(&self) -> HandleRef {
HandleRef::from_file(self)
}
}
impl AsHandleRef for io::Stdin {
fn as_handle_ref(&self) -> HandleRef {
unsafe { HandleRef::from_raw_handle(self.as_raw_handle()) }
}
}
impl AsHandleRef for io::Stdout {
fn as_handle_ref(&self) -> HandleRef {
unsafe { HandleRef::from_raw_handle(self.as_raw_handle()) }
}
}
impl AsHandleRef for io::Stderr {
fn as_handle_ref(&self) -> HandleRef {
unsafe { HandleRef::from_raw_handle(self.as_raw_handle()) }
}
}
impl AsHandleRef for process::ChildStdin {
fn as_handle_ref(&self) -> HandleRef {
unsafe { HandleRef::from_raw_handle(self.as_raw_handle()) }
}
}
impl AsHandleRef for process::ChildStdout {
fn as_handle_ref(&self) -> HandleRef {
unsafe { HandleRef::from_raw_handle(self.as_raw_handle()) }
}
}
impl AsHandleRef for process::ChildStderr {
fn as_handle_ref(&self) -> HandleRef {
unsafe { HandleRef::from_raw_handle(self.as_raw_handle()) }
}
}
| {
"repo_name": "BurntSushi/winapi-util",
"stars": "54",
"repo_language": "Rust",
"file_name": "file.rs",
"mime_type": "text/plain"
} |
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,
}
}
}
| {
"repo_name": "BurntSushi/winapi-util",
"stars": "54",
"repo_language": "Rust",
"file_name": "file.rs",
"mime_type": "text/plain"
} |
/*!
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",
"stars": "54",
"repo_language": "Rust",
"file_name": "file.rs",
"mime_type": "text/plain"
} |
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)
}
}
| {
"repo_name": "BurntSushi/winapi-util",
"stars": "54",
"repo_language": "Rust",
"file_name": "file.rs",
"mime_type": "text/plain"
} |
<?xml version="1.0" encoding="UTF-8"?>
<JUCERPROJECT id="yB68Dv" name="SuperVirtualKeyboard" projectType="audioplug"
companyName="Everytone" companyEmail="[email protected]"
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",
"stars": "38",
"repo_language": "C++",
"file_name": "MapByOrderDialog.cpp",
"mime_type": "text/x-c"
} |
# 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...
| {
"repo_name": "vsicurella/SuperVirtualKeyboard",
"stars": "38",
"repo_language": "C++",
"file_name": "MapByOrderDialog.cpp",
"mime_type": "text/x-c"
} |
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) | {
"repo_name": "vsicurella/SuperVirtualKeyboard",
"stars": "38",
"repo_language": "C++",
"file_name": "MapByOrderDialog.cpp",
"mime_type": "text/x-c"
} |
/*
==============================================================================
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();
}
} | {
"repo_name": "vsicurella/SuperVirtualKeyboard",
"stars": "38",
"repo_language": "C++",
"file_name": "MapByOrderDialog.cpp",
"mime_type": "text/x-c"
} |
/*
==============================================================================
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;
};
| {
"repo_name": "vsicurella/SuperVirtualKeyboard",
"stars": "38",
"repo_language": "C++",
"file_name": "MapByOrderDialog.cpp",
"mime_type": "text/x-c"
} |
/*
==============================================================================
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()};
}
| {
"repo_name": "vsicurella/SuperVirtualKeyboard",
"stars": "38",
"repo_language": "C++",
"file_name": "MapByOrderDialog.cpp",
"mime_type": "text/x-c"
} |
/*
==============================================================================
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
};
| {
"repo_name": "vsicurella/SuperVirtualKeyboard",
"stars": "38",
"repo_language": "C++",
"file_name": "MapByOrderDialog.cpp",
"mime_type": "text/x-c"
} |
/*
==============================================================================
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);
}
| {
"repo_name": "vsicurella/SuperVirtualKeyboard",
"stars": "38",
"repo_language": "C++",
"file_name": "MapByOrderDialog.cpp",
"mime_type": "text/x-c"
} |
/*
==============================================================================
PresetManager.cpp
Created: 27 May 2019 10:57:01pm
Author: Vincenzo
==============================================================================
*/
#include "PresetManager.h"
SvkPresetManager::SvkPresetManager(ValueTree pluginSettingsNodeIn)
{
pluginSettingsNode = pluginSettingsNodeIn;
initializeModePresets();
loadPreset(SvkPreset::getDefaultPreset().getPresetNode(), false);
}
SvkPresetManager::~SvkPresetManager()
{
removeAllChangeListeners();
}
SvkPreset& SvkPresetManager::getPreset()
{
return svkPresetWorking;
}
int SvkPresetManager::getNumMenuItems(bool withFactoryMenu , bool withUserMenu, bool withFavMenu, bool withSlots)
{
int totalMenuItems = 0;
if (withFactoryMenu)
{
int factoryMenuSize = 0;
for (auto sortedArray : modesSorted)
factoryMenuSize += sortedArray.size();
totalMenuItems += factoryMenuSize;
//modesSorted[0].size() + modesSorted[1].size() + modesSorted[2].size();
}
if (withUserMenu)
totalMenuItems += loadedUserModes.size();
if (withFavMenu)
totalMenuItems += favoriteModes.size();
if (withSlots)
totalMenuItems += modeSlots.size();
return totalMenuItems;
}
int SvkPresetManager::getNumModeSlots() const
{
return modeSlots.size();
}
Array<int> SvkPresetManager::getModeSlotsInUse() const
{
return svkPresetWorking.getSlotNumbersInUse();
}
int SvkPresetManager::getModeSlotOfSelector(int modeSelectorNumIn) const
{
return svkPresetWorking.getSlotNumberBySelector(modeSelectorNumIn);
}
ValueTree SvkPresetManager::getModeInLibrary(int indexIn)
{
if (indexIn < 0)
indexIn = 0;
int numModes = loadedFactoryModes.size() + loadedUserModes.size();
int subMenu = indexIn / numModes;
int index = indexIn % numModes;
if (subMenu < modesSorted.size())
if (index < modesSorted.getUnchecked(subMenu).size())
return modesSorted.getUnchecked(subMenu).getUnchecked(index);
return ValueTree();
}
Mode* SvkPresetManager::getModeInSlot(int modeSlotNumIn)
{
int slotIndex = svkPresetWorking.getSlotNumberIndex(modeSlotNumIn);
if (slotIndex >= 0)
{
jassert(slotIndex < modeSlots.size());
Mode* mode = modeSlots[slotIndex];
DBG("GRABBING MODE " + String(modeSlotNumIn) + " which is: " + mode->getDescription());
return mode;
}
else if (modeSlotNumIn > 0)
{
return modeCustom.get();
}
return nullptr;
}
Mode* SvkPresetManager::getModeBySelector(int selectorNumber)
{
int slotNumber = svkPresetWorking.getSlotNumberBySelector(selectorNumber);
if (svkPresetWorking.isSlotNumberInUse(slotNumber))
{
return modeSlots[svkPresetWorking.getSlotNumberIndex(slotNumber)];
}
else if (slotNumber > MAX_MODE_SLOTS_INDEX)
{
return modeCustom.get();
}
return nullptr;
}
Mode* SvkPresetManager::getModeCustom()
{
return modeCustom.get();
}
Mode* SvkPresetManager::setModeCustom(ValueTree modeNodeIn)
{
svkPresetWorking.setCustomMode(modeNodeIn);
modeCustom.reset(new Mode(svkPresetWorking.getCustomMode(), false));
return modeCustom.get();
}
Mode* SvkPresetManager::setModeCustom(String stepsIn, String familyIn, String nameIn, String infoIn, int rootNoteIn)
{
return setModeCustom(Mode::createNode(stepsIn, familyIn, nameIn, infoIn, rootNoteIn));
}
int SvkPresetManager::setSlotToMode(int modeSlotNum, ValueTree modeNode)
{
int slotIndex = svkPresetWorking.setModeSlot(modeNode, modeSlotNum);
modeNode = svkPresetWorking.getModeInSlot(modeSlotNum);
if (slotIndex >= 0)
{
if (slotIndex >= modeSlots.size())
modeSlots.add(new Mode(modeNode, false));
else
modeSlots.set(slotIndex, new Mode(modeNode, false));
}
return slotIndex;
}
int SvkPresetManager::addSlot(ValueTree modeNode)
{
int slotNumber = svkPresetWorking.addModeSlot(modeNode);
modeSlots.add(new Mode(modeNode));
return slotNumber;
}
int SvkPresetManager::setSlotAndSelection(int modeSlotNum, int modeSelectorNum, ValueTree modeNode)
{
int slotIndex = setSlotToMode(modeSlotNum, modeNode);
svkPresetWorking.setModeSelectorSlotNum(modeSelectorNum, modeSlotNum);
return slotIndex;
}
int SvkPresetManager::addSlotAndSetSelection(int modeSelectorNumber, ValueTree modeNode)
{
int modeSlotNum = addSlot(modeNode);
svkPresetWorking.setModeSelectorSlotNum(modeSelectorNumber, modeSlotNum);
return modeSlotNum;
}
void SvkPresetManager::removeMode(int modeSlotNum)
{
int slotIndex = svkPresetWorking.removeModeSlot(modeSlotNum);
modeSlots.remove(slotIndex);
}
void SvkPresetManager::resetModeSlots()
{
svkPresetWorking.resetModeSlots();
modeSlots.clear();
modeSlots.add(new Mode(svkPresetWorking.getMode1()));
modeSlots.add(new Mode(svkPresetWorking.getMode2()));
}
/*
This operation should be completely revised, as it's piecing together two systems without full implementation.
Currently, modes can be inserted in one of 128 slots, and mode selectors can point to a certain slot.
But inserting modes into different slots is not fully implemented yet, so the mode slot containing a mode that
the mode selector is pointed to will be replaced by the mode chosen in calling this function.
*/
void SvkPresetManager::handleModeSelection(int selectorNumber, int idIn)
{
int numSortedModes = getNumMenuItems(true, false, false, false);
int modeLibraryIndex = idIn - 1;
int userModesIndex = modeLibraryIndex - numSortedModes + loadedUserModes.size(); // issue here, subtracting loaded user modes is a workaround
int favIdx = userModesIndex - loadedUserModes.size();
int slotIdx = favIdx - favoriteModes.size();
int modeSlotNumber = svkPresetWorking.getSlotNumberBySelector(selectorNumber);
// if selector was set to a custom mode, change the slot to the selector's number
if (modeSlotNumber > MAX_MODE_SLOTS_INDEX)
modeSlotNumber = selectorNumber;
ValueTree modeSelected;
if (modeLibraryIndex < numSortedModes)
{
modeSelected = getModeInLibrary(modeLibraryIndex).createCopy();
}
else if (userModesIndex < loadedUserModes.size())
{
modeSelected = loadedUserModes[userModesIndex].createCopy();
}
else if (favIdx < favoriteModes.size())
{
modeSelected = favoriteModes[favIdx].createCopy();
}
else if (slotIdx < modeSlots.size())
{
// Currently the only way to switch a selector's mode slot pointer
modeSelected = ValueTree();
modeSlotNumber = slotIdx;
}
else
{
DBG("Custom mode selected");
modeSelected = modeCustom->modeNode;
modeSlotNumber = MAX_MODE_SLOTS_INDEX + 1;
}
// Replaces the mode selector's mode slot with new mode
if (modeSelected.isValid() && selectorNumber < 2 && modeSlotNumber <= MAX_MODE_SLOTS_INDEX)
{
setSlotToMode(modeSlotNumber, modeSelected);
}
svkPresetWorking.setModeSelectorSlotNum(selectorNumber, modeSlotNumber);
getModeInSlot(modeSlotNumber)->setRootNote(svkPresetWorking.getModeSelectorRootNote(selectorNumber));
}
bool SvkPresetManager::loadPreset(ValueTree presetNodeIn, bool sendChangeSignal)
{
if (presetNodeIn.hasType(IDs::presetNode))
{
DBG("Loading Preset:" + presetNodeIn.toXmlString());
svkPresetSaved.restoreFromNode(presetNodeIn, true);
svkPresetWorking = SvkPreset(svkPresetSaved);
modeSlots.clear();
for (auto mode : svkPresetWorking.getModeSlots())
{
modeSlots.add(new Mode(mode.getChild(0), false));
}
ValueTree customModeNode = svkPresetWorking.getCustomMode();
modeCustom.reset(new Mode(customModeNode, false));
if (sendChangeSignal)
sendChangeMessage();
return true;
}
DBG("Problem loading preset.");
return false;
}
bool SvkPresetManager::saveNodeToFile(ValueTree nodeToSave, String saveMsg, String fileEnding, String absolutePath)
{
File fileOut = File(absolutePath);
if (fileOut.isDirectory())
{
FileChooser chooser(saveMsg,
fileOut, fileEnding);
chooser.browseForFileToSave(true);
fileOut = chooser.getResult();
}
else if (!fileOut.exists())
{
FileChooser chooser(saveMsg,
File::getSpecialLocation(File::SpecialLocationType::userDocumentsDirectory),
fileEnding);
chooser.browseForFileToSave(true);
fileOut = chooser.getResult();
}
if (fileOut.getParentDirectory().exists())
{
std::unique_ptr<XmlElement> xml(nodeToSave.createXml());
return xml->writeTo(fileOut);
}
return false;
}
bool SvkPresetManager::savePresetToFile(String absolutePath)
{
commitPreset();
DBG("Saving the following node to " + absolutePath + ": " + svkPresetWorking.toString());
return saveNodeToFile(svkPresetWorking.getPresetNode(), "Save preset", "*.svk", absolutePath);
}
bool SvkPresetManager::saveModeToFile(int modeSlotNumber, String absolutePath)
{
Mode* mode;
if (modeSlotNumber < modeSlots.size())
mode = getModeInSlot(modeSlotNumber);
else
mode = modeCustom.get();
bool saved = saveNodeToFile(mode->modeNode, "Save mode", "*.svk", absolutePath);
if (saved)
{
ValueTree newCopy = mode->modeNode.createCopy();
addAndSortMode(newCopy);
loadedUserModes.add(newCopy);
// Reset custom mode, since saved mode is a user mode now
// Not sure if this should be done like that...
if (mode == modeCustom.get())
modeCustom.reset(new Mode("1"));
}
return saved;
}
ValueTree SvkPresetManager::nodeFromFile(String openMsg, String fileEnding, String absoluteFilePath)
{
ValueTree nodeIn;
File fileIn = File(absoluteFilePath);
if (!fileIn.existsAsFile())
{
std::unique_ptr<FileChooser> chooser;
if (fileIn.isDirectory())
chooser.reset(new FileChooser(openMsg, fileIn, fileEnding));
else
chooser.reset(new FileChooser(openMsg, File::getSpecialLocation(File::userDocumentsDirectory), fileEnding));
chooser->browseForFileToOpen();
fileIn = chooser->getResult();
}
if (fileIn.existsAsFile())
{
std::unique_ptr<XmlElement> xml = parseXML(fileIn);
nodeIn = ValueTree::fromXml(*(xml.get()));
if (nodeIn.isValid())
return nodeIn;
}
return ValueTree();
}
ValueTree SvkPresetManager::modeFromFile(String absoluteFilePath)
{
ValueTree nodeIn = nodeFromFile("Open mode", "*.svk", absoluteFilePath);
if (nodeIn.hasType(IDs::modePresetNode))
return nodeIn;
return ValueTree();
}
ValueTree SvkPresetManager::presetFromFile(String absoluteFilePath)
{
ValueTree nodeIn = nodeFromFile("Open preset", "*.svk", absoluteFilePath);
if (nodeIn.hasType(IDs::presetNode))
return nodeIn;
return ValueTree();
}
bool SvkPresetManager::commitPreset()
{
return loadPreset(svkPresetWorking.getPresetNode(), false);
}
bool SvkPresetManager::resetToSavedPreset()
{
DBG("PRESET MANAGER: Resetting to last saved preset.");
return loadPreset(svkPresetSaved.getPresetNode(), false);
}
void SvkPresetManager::initializeModePresets()
{
modeLibraryNode = ValueTree(IDs::modeLibraryNode);
loadedFactoryModes.clear();
loadedUserModes.clear();
modesSorted.clear();
for (int m = 0; m < numSortTypes; m++)
modesSorted.add(Array<ValueTree>());
createFactoryModes();
loadModeDirectory();
}
void SvkPresetManager::createFactoryModes()
{
if (!(bool) pluginSettingsNode[IDs::saveFactoryModes] || !(bool)pluginSettingsNode[IDs::createPresetFolder])
{
const char* factoryModes = BinaryData::FactoryModes_txt;
int size = BinaryData::FactoryModes_txtSize;
loadedFactoryModes.clear();
if (factoryModes && size > 0)
{
MemoryInputStream instream(factoryModes, size, false);
String line, steps, family, info, name;
ValueTree factoryMode;
while (instream.getNumBytesRemaining() > 0)
{
line = instream.readNextLine();
steps = line.upToFirstOccurrenceOf(", ", false, true);
family = line.upToFirstOccurrenceOf("; ", false, true);
family = family.substring(steps.length() + 2, family.length());
info = line.fromFirstOccurrenceOf("; ", false, true);
factoryMode = Mode::createNode(steps, family, "", info, 60, true);
addAndSortMode(factoryMode);
loadedFactoryModes.add(factoryMode);
}
factoryMode = ValueTree();
}
}
DBG("Amt of factory modes:" + String(loadedFactoryModes.size()));
}
void SvkPresetManager::loadModeDirectory()
{
// TODO: Add checking for duplicate modes
if ((bool)pluginSettingsNode[IDs::createPresetFolder])
{
File modeDirectory = File(pluginSettingsNode[IDs::modeDirectory]);
Array<File> filesToLoad = modeDirectory.findChildFiles(File::TypesOfFileToFind::findFiles, true, "*.svk");
std::unique_ptr<XmlElement> xml;
ValueTree modeNodeIn;
while (filesToLoad.size() > 0)
{
xml = parseXML(filesToLoad.removeAndReturn(0));
modeNodeIn = ValueTree::fromXml(*(xml.get()));
if (modeNodeIn.hasType(IDs::modePresetNode))
{
addAndSortMode(modeNodeIn);
if ((bool)modeNodeIn[IDs::factoryPreset])
{
loadedFactoryModes.add(modeNodeIn);
}
else
{
loadedUserModes.add(modeNodeIn);
}
}
}
}
DBG("New amt of Factory Modes: " + String(loadedFactoryModes.size()));
DBG("Amt User Modes loaded: " + String(loadedUserModes.size()));
}
void SvkPresetManager::resortModeLibrary()
{
modesSorted.clear();
for (int m = 0; m < numSortTypes; m++)
modesSorted.add(Array<ValueTree>());
ValueTree modeToSort;
for (int i = 0; i < modeLibraryNode.getNumChildren(); i++)
{
modeToSort = modeLibraryNode.getChild(i);
addModeToSort(modeToSort);
}
}
int SvkPresetManager::addModeToLibrary(ValueTree modeNodeIn)
{
if (modeNodeIn.hasType(IDs::modePresetNode))
{
int libraryIndex = modeLibraryNode.getNumChildren();
modeNodeIn.setProperty(IDs::libraryIndexOfMode, libraryIndex, nullptr);
modeLibraryNode.appendChild(modeNodeIn, nullptr);
return libraryIndex;
}
return -1;
}
void SvkPresetManager::addModeToSort(ValueTree modeNodeIn)
{
if (modeNodeIn.hasType(IDs::modePresetNode))
{
modesSorted.getReference(SortType::scaleSize).addSorted(scaleSizeSort, modeNodeIn);
modesSorted.getReference(SortType::modeSize).addSorted(modeSizeSort, modeNodeIn);
modesSorted.getReference(SortType::familyName).addSorted(familyNameSort, modeNodeIn);
if (!(bool)modeNodeIn[IDs::factoryPreset])
{
modesSorted.getReference(SortType::user).addSorted(scaleSizeSort, modeNodeIn);
}
}
}
int SvkPresetManager::addAndSortMode(ValueTree modeNodeIn)
{
int ind = addModeToLibrary(modeNodeIn);
addModeToSort(modeNodeIn);
return ind;
}
void SvkPresetManager::requestModeMenu(PopupMenu* menuToUse)
{
menuToUse->clear();
PopupMenu scaleSizeMenu;
PopupMenu modeSizeMenu;
PopupMenu familyMenu;
PopupMenu userMenu;
PopupMenu favMenu;
PopupMenu slotsMenu;
ValueTree presetIn;
String displayName;
var separatorProperty;
int numModes = 0;
int subMenuIndex = 0;
for (int subMenu = 0; subMenu <= SortType::user; subMenu++)
{
if (subMenu < SortType::user)
numModes = modeLibraryNode.getNumChildren();
else
numModes = loadedUserModes.size();
for (int presetNum = 0; presetNum < numModes; presetNum++)
{
presetIn = modesSorted.getUnchecked(subMenu).getUnchecked(presetNum);
switch (subMenu)
{
case (SortType::scaleSize):
if (separatorProperty != presetIn[IDs::scaleSize])
scaleSizeMenu.addSeparator();
separatorProperty = presetIn[IDs::scaleSize];
displayName = presetIn[IDs::modeName];
scaleSizeMenu.addItem(++subMenuIndex, displayName);
break;
case (SortType::modeSize):
if (separatorProperty != presetIn[IDs::modeSize])
modeSizeMenu.addSeparator();
separatorProperty = presetIn[IDs::modeSize];
displayName = presetIn[IDs::modeName];
modeSizeMenu.addItem(++subMenuIndex, displayName);
break;
case (SortType::familyName):
if (separatorProperty != presetIn[IDs::family])
familyMenu.addSeparator();
separatorProperty = presetIn[IDs::family];
displayName = presetIn[IDs::modeName];
familyMenu.addItem(++subMenuIndex, displayName);
break;
case (SortType::user):
if (presetIn[IDs::factoryPreset])
continue;
if (separatorProperty != presetIn[IDs::scaleSize])
userMenu.addSeparator();
separatorProperty = presetIn[IDs::scaleSize];
displayName = presetIn[IDs::modeName];
userMenu.addItem(++subMenuIndex, displayName);
break;
}
}
}
// USERS
// for (int i = 0; i < loadedUserModes.size(); i++)
// {
// userMenu.addItem(++subMenuIndex, loadedUserModes[i][IDs::modeName].toString());
// }
// FAVORITES
for (int i = 0; i < favoriteModes.size(); i++)
{
favMenu.addItem(++subMenuIndex, favoriteModes[i][IDs::modeName].toString());
}
// SLOTS
Mode* mode;
for (int i = 0; i < modeSlots.size(); i++)
{
mode = modeSlots[i];
slotsMenu.addItem(++subMenuIndex, mode->getName());
}
menuToUse->addSubMenu("by Scale Size", scaleSizeMenu);
menuToUse->addSubMenu("by Mode Size", modeSizeMenu);
menuToUse->addSubMenu("by Family", familyMenu);
menuToUse->addSubMenu("User", userMenu);
menuToUse->addSubMenu("Favorites", favMenu);
menuToUse->addSeparator();
menuToUse->addSubMenu("Slots", slotsMenu);
menuToUse->addSeparator();
String customModeName = modeCustom->getName();
if (customModeName == "undefined[1] 1")
customModeName = "Custom Mode";
menuToUse->addItem(++subMenuIndex, customModeName);
}
| {
"repo_name": "vsicurella/SuperVirtualKeyboard",
"stars": "38",
"repo_language": "C++",
"file_name": "MapByOrderDialog.cpp",
"mime_type": "text/x-c"
} |
/*
==============================================================================
This file was auto-generated!
It contains the basic framework code for a JUCE plugin processor.
==============================================================================
*/
#pragma once
#include "../JuceLibraryCode/JuceHeader.h"
#include "UI/PluginEditor.h"
#include "PluginState.h"
typedef AudioProcessorValueTreeState::Parameter Parameter;
//==============================================================================
/**
*/
class SvkAudioProcessor : public AudioProcessor,
public ChangeBroadcaster
{
public:
//==============================================================================
SvkAudioProcessor();
~SvkAudioProcessor();
std::unique_ptr<UndoManager> svkUndo;
AudioProcessorValueTreeState svkValueTree;
//==============================================================================
void prepareToPlay (double sampleRate, int samplesPerBlock) override;
void releaseResources() override;
#ifndef JucePlugin_PreferredChannelConfigurations
bool isBusesLayoutSupported (const BusesLayout& layouts) const override;
#endif
void processBlock (AudioBuffer<float>&, MidiBuffer&) override;
//==============================================================================
AudioProcessorEditor* createEditor() override;
bool hasEditor() const override;
//==============================================================================
const String getName() const override;
bool acceptsMidi() const override;
bool producesMidi() const override;
bool isMidiEffect() const override;
double getTailLengthSeconds() const override;
//==============================================================================
int getNumPrograms() override;
int getCurrentProgram() override;
void setCurrentProgram (int index) override;
const String getProgramName (int index) override;
void changeProgramName (int index, const String& newName) override;
//==============================================================================
void getStateInformation (MemoryBlock& destData) override;
void setStateInformation (const void* data, int sizeInBytes) override;
//==============================================================================
UndoManager* getUndoManager();
//ApplicationCommandManager* getAppCmdMgr();
SvkPluginState* getPluginState();
//const Array<String>& getParamIDs() const;
//==============================================================================
private:
//void recordParamIDs();
//
AudioProcessorValueTreeState::ParameterLayout createParameters();
//Array<String> paramIDs;
std::unique_ptr<SvkPluginState> pluginState;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SvkAudioProcessor)
};
| {
"repo_name": "vsicurella/SuperVirtualKeyboard",
"stars": "38",
"repo_language": "C++",
"file_name": "MapByOrderDialog.cpp",
"mime_type": "text/x-c"
} |
/*
==============================================================================
Constants.h
Created: 16 Aug 2020 12:41:04pm
Author: Vincenzo
==============================================================================
*/
#pragma once
#include <JuceHeader.h>
#include "Structures/Mode.h"
#define STD_TUNING_MODE_NODE Mode::createNode("2 2 1 2 2 2 1", "Meantone")
const int MAX_MODE_SLOTS_INDEX = 127;
const float SVK_PRESET_VERSION = 1.0; | {
"repo_name": "vsicurella/SuperVirtualKeyboard",
"stars": "38",
"repo_language": "C++",
"file_name": "MapByOrderDialog.cpp",
"mime_type": "text/x-c"
} |
/*
==============================================================================
CommonFunctions.h
Created: 6 May 2019 7:31:20pm
Author: Vincenzo
==============================================================================
*/
#pragma once
#include <JuceHeader.h>
#include "PluginIDs.h"
#include "Structures/OwnedHashMap.h"
struct ScaleSizeSorter
{
// Scale first, then mode, then family
static int compareElements(const ValueTree t1, const ValueTree t2)
{
if ((t1.hasType(IDs::modePresetNode) || t1.hasType(IDs::presetNode)) &&
(t2.hasType(IDs::modePresetNode) || t2.hasType(IDs::presetNode)))
{
int sz1 = (int) t1[IDs::scaleSize];
int sz2 = (int) t2[IDs::scaleSize];
int m1 = (int) t1[IDs::modeSize];
int m2 = (int) t2[IDs::modeSize];
String f1 = t1[IDs::family];
String f2 = t2[IDs::family];
if (sz1 < sz2) return -1;
else if (sz1 > sz2) return 1;
else
{
if (m1 < m2) return -1;
else if (m1 > m2) return 1;
else
{
if (f1 < f2) return -1;
else if (f1 > f2) return 1;
else return 0;
}
}
}
else
return 0;
}
};
struct ModeSizeSorter
{
// Mode first, then scale, then family
static int compareElements(const ValueTree t1, const ValueTree t2)
{
if ((t1.hasType(IDs::modePresetNode) || t1.hasType(IDs::presetNode)) &&
(t2.hasType(IDs::modePresetNode) || t2.hasType(IDs::presetNode)))
{
int sz1 = (int) t1[IDs::scaleSize];
int sz2 = (int) t2[IDs::scaleSize];
int m1 = (int) t1[IDs::modeSize];
int m2 = (int) t2[IDs::modeSize];
String f1 = t1[IDs::family];
String f2 = t2[IDs::family];
if (m1 < m2) return -1;
else if (m1 > m2) return 1;
else
{
if (sz1 < sz2) return -1;
else if (sz1 > sz2) return 1;
else
{
if (f1 < f2) return -1;
else if (f1 > f2) return 1;
else return 0;
}
}
}
return 0;
}
};
struct FamilyNameSorter
{
// Family first, then scale, then mode
static int compareElements(const ValueTree t1, const ValueTree t2)
{
if ((t1.hasType(IDs::modePresetNode) || t1.hasType(IDs::presetNode)) &&
(t2.hasType(IDs::modePresetNode) || t2.hasType(IDs::presetNode)))
{
int sz1 = (int) t1[IDs::scaleSize];
int sz2 = (int) t2[IDs::scaleSize];
int m1 = (int) t1[IDs::modeSize];
int m2 = (int) t2[IDs::modeSize];
String f1 = t1[IDs::family];
String f2 = t2[IDs::family];
if (f1 < f2) return -1;
else if (f1 > f2) return 1;
else
{
if (sz1 < sz2) return -1;
else if (sz1 > sz2) return 1;
else
{
if (m1 < m2) return -1;
else if (m1 > m2) return 1;
else return 0;
}
}
}
return 0;
}
};
struct IDasStringHash
{
static int generateHash (const Identifier& key, int upperLimit) noexcept
{
return DefaultHashFunctions::generateHash(key.toString(), upperLimit);
}
};
//typedef OwnedHashMap<Identifier, RangedAudioParameter, IDasStringHash> SvkParameters;
template <class T, class U>
struct Pair
{
T key;
U value;
Pair<T, U>(T keyIn, U valueIn)
{
key = keyIn;
value = valueIn;
}
};
static bool toggleMenuItemEnablement(PopupMenu& menuIn, int itemIdIn, bool shouldBeEnabled)
{
PopupMenu::MenuItemIterator menuItems(menuIn);
while (menuItems.next())
{
PopupMenu::Item& item = menuItems.getItem();
if (item.itemID == itemIdIn)
{
item.isEnabled = shouldBeEnabled;
return true;
}
}
return false;
}
//struct MidiPitch : Pair<int, int>
//{
// MidiPitch(int midiNoteIn=-1, int pitchbendIn=0)
// : Pair<int, int>(midiNoteIn, pitchbendIn) {}
//};
//static Point<int> pointFromString(Point<int>& p, String pointToStringIn)
//{
// String val1 = pointToStringIn.upToFirstOccurrenceOf(",", false, true);
// String val2 = pointToStringIn.fromFirstOccurrenceOf(",", false, true);
// p = Point<int>(val1.getIntValue(), val2.getIntValue());
// return p;
//}
//
//static Point<float> pointFromString(Point<float>& p, String pointToStringIn)
//{
// String val1 = pointToStringIn.upToFirstOccurrenceOf(",", false, true);
// String val2 = pointToStringIn.fromFirstOccurrenceOf(",", false, true);
// p = Point<float>(val1.getFloatValue(), val2.getFloatValue());
// return p;
//}
//
//static Point<double> pointFromString(Point<double>& p, String pointToStringIn)
//{
// String val1 = pointToStringIn.upToFirstOccurrenceOf(",", false, true);
// String val2 = pointToStringIn.fromFirstOccurrenceOf(",", false, true);
// p = Point<double>(val1.getDoubleValue(), val2.getDoubleValue());
// return p;
//}
template <class T>
static void add_array_to_node(ValueTree nodeIn, const Array<T>& arrayIn, Identifier arrayID, Identifier itemId)
{
ValueTree arrayTree = ValueTree(arrayID);
ValueTree item;
for (int i = 0; i < arrayIn.size(); i++)
{
item = ValueTree(itemId);
item.setProperty("Value", arrayIn[i], nullptr);
arrayTree.addChild(item, i, nullptr);
}
nodeIn.addChild(arrayTree, -1, nullptr);
}
template <class T>
static void get_array_from_node(const ValueTree nodeIn, Array<T>& arrayIn, Identifier arrayID)
{
ValueTree childArray = nodeIn.getChildWithName(arrayID);
if (childArray.isValid())
{
for (int i = 0; i < childArray.getNumChildren(); i++)
{
arrayIn.add(childArray.getChild(i).getProperty("Value"));
}
}
}
///* Adds a Colour array reduced to nontrivial items to a node represented in a ValueTree structure */
//static void add_array_to_node(ValueTree nodeIn, const Array<Colour>& arrayIn, Identifier arrayID, Identifier itemId)
//{
// ValueTree arrayTree = ValueTree(arrayID);
// ValueTree item;
//
// for (int i = 0; i < arrayIn.size(); i++)
// {
// if (arrayIn[i].isOpaque())
// {
// item = ValueTree(itemId);
// item.setProperty("Key", i, nullptr);
// item.setProperty("Value", arrayIn[i].toString(), nullptr);
// arrayTree.addChild(item, i, nullptr);
// }
// }
//
// nodeIn.addChild(arrayTree, -1, nullptr);
//}
//
//static void add_array_as_property(ValueTree& nodeIn, const Array<Colour>& arrayIn, Identifier itemId)
//{
// String array = "";
//
// for (int i = 0; i < arrayIn.size(); i++)
// {
// array += arrayIn[i].toString();
// array += '\n';
// }
//
// nodeIn.setProperty(itemId, array, nullptr);
//}
//static void get_array_from_node(const ValueTree& nodeIn, Array<Colour>& arrayIn, Identifier arrayID)
//{
// String array = nodeIn[arrayID];
// String value = "";
// int charsRead = 0;
//
// Colour c = Colours::transparentWhite;
//
// while (charsRead < array.length())
// {
// value += array[charsRead];
//
// if (charsRead + 1 < array.length())
// {
// if (array[charsRead + 1] == '\n')
// c = Colour::fromString(value);
// }
//
// if (c != Colours::transparentWhite)
// {
// arrayIn.add(c);
// c = Colours::transparentWhite;
// }
// }
//}
///* Creates a Colour array from a node, and populates trivial and nontrivial keys */
//static void get_array_from_node(const ValueTree nodeIn, Array<Colour>& arrayIn, Identifier arrayID, int arraySizeOut)
//{
// ValueTree arrayNode;
// ValueTree item;
//
// arrayIn.resize(arraySizeOut);
//
// arrayNode = nodeIn.getChildWithName(arrayID);
//
// for (int i = 0; i < arrayNode.getNumChildren(); i++)
// {
// item = arrayNode.getChild(i);
// arrayIn.set(item["Key"], Colour::fromString(item["Value"].toString()));
// }
//}
//template <class T>
//static void add_array_to_node(ValueTree nodeIn, const Array<Point<T>>& arrayIn, Identifier arrayID, Identifier itemId)
//{
// ValueTree arrayTree = ValueTree(arrayID);
// ValueTree item;
// for (int i = 0; i < arrayIn.size(); i++)
// {
// item = ValueTree(itemId);
// item.setProperty("Value", arrayIn[i].toString(), nullptr);
// arrayTree.addChild(item, i, nullptr);
// }
//
// nodeIn.addChild(arrayTree, -1, nullptr);
//}
//static void get_array_from_node(const ValueTree nodeIn, Array<Point<int>>& arrayIn, Identifier arrayID)
//{
// ValueTree childArray = nodeIn.getChildWithName(arrayID);
//
// if (childArray.isValid())
// for (int i = 0; i < childArray.getNumChildren(); i++)
// arrayIn.add(pointFromString(arrayIn.getReference(0), childArray.getChild(i).getProperty("Value").toString()));
//}
//
//static void get_array_from_node(const ValueTree nodeIn, Array<Point<float>>& arrayIn, Identifier arrayID)
//{
// ValueTree childArray = nodeIn.getChildWithName(arrayID);
//
// if (childArray.isValid())
// for (int i = 0; i < childArray.getNumChildren(); i++)
// arrayIn.add(pointFromString(arrayIn.getReference(0), childArray.getChild(i).getProperty("Value")));
//}
//
//static void get_array_from_node(const ValueTree nodeIn, Array<Point<double>>& arrayIn, Identifier arrayID)
//{
// ValueTree childArray = nodeIn.getChildWithName(arrayID);
//
// if (childArray.isValid())
// for (int i = 0; i < childArray.getNumChildren(); i++)
// arrayIn.add(pointFromString(arrayIn.getReference(0), childArray.getChild(i).getProperty("Value")));
//}
template <class T>
static void set_value_in_array(ValueTree nodeIn, Identifier arrayID, int indexToChange, T valueToSet)
{
ValueTree arrayNode = nodeIn.getChildWithName(arrayID);
if (arrayNode.isValid() && indexToChange >= 0 && indexToChange < arrayNode.getNumChildren())
{
arrayNode.getChild(indexToChange).setProperty("Value", valueToSet, nullptr);
}
}
static int totalModulus(int numIn, int mod)
{
int val = 0;
if (mod != 0)
val = ((numIn % mod) + mod) % mod;
return val;
}
template <class T>
static T sumUpToIndex(Array<T> arrayIn, int indexIn)
{
indexIn = totalModulus(indexIn, arrayIn.size());
T sum = 0;
for (int i = 0; i < indexIn; i++)
{
sum += arrayIn[i];
}
return sum;
}
template <class T>
static T sumUpToRingIndex(Array<T> arrayIn, int indexIn)
{
T sum = 0;
for (int i = 0; i < indexIn; i++)
{
sum += arrayIn[i % arrayIn.size()];
}
return sum;
}
template <class T>
Array<T> reverseArray(const Array<T>& arrayIn)
{
Array<T> outArray;
outArray.resize(arrayIn.size());
for (int i = 0; i < arrayIn.size(); i++)
{
outArray.set(i, arrayIn.getUnchecked(arrayIn.size() - i - 1));
}
return outArray;
}
template <class T>
String arrayToString(const Array<T>& arrayIn)
{
String arrayString = "";
for (int i = 0; i < arrayIn.size(); i++)
{
arrayString+= String(arrayIn[i]);
if (i + 1 < arrayIn.size())
arrayString += ", ";
}
return arrayString;
}
template <class T>
static void DBGArray(Array<T>& arrayIn, String arrayName="Array")
{
DBG(arrayName + ":");
for (int i = 0; i < arrayIn.size(); i++)
{
DBG(String(i) + ": " + String(arrayIn[i]));
}
}
static double getStdFrequency(int midiNoteIn)
{
return 440.0 * pow(2, (midiNoteIn - 69) / 12.0);
} | {
"repo_name": "vsicurella/SuperVirtualKeyboard",
"stars": "38",
"repo_language": "C++",
"file_name": "MapByOrderDialog.cpp",
"mime_type": "text/x-c"
} |
/*
==============================================================================
PluginModes.h
Created: 25 Jul 2020 5:39:15pm
Author: Vincenzo
==============================================================================
*/
#pragma once
#include <JuceHeader.h>
namespace VirtualKeyboard
{
enum UIMode
{
playMode = 0,
editMode,
mapMode
};
enum Orientation
{
horizontal = 0,
verticalLeft,
verticalRight
};
enum HighlightStyle
{
full = 1,
inside,
outline,
circles,
squares
};
enum VelocityStyle
{
linear = 1,
curved,
fixed
};
enum ScrollingStyle
{
smooth = 1,
stepped
};
enum KeyPlacementType
{
nestedRight = 1,
nestedCenter,
flat,
adjacent
};
enum KeyShapeFlags
{
Basic = 0x0001,
NotchPrevious = 0x0010,
NotchNext = 0x0100,
NotchCenter = 0x1000
};
}
enum MappingStyle
{
ModeToMode = 1,
ModeToScale,
ModeByOrder
};
enum PluginStateNodeStatus
{
InvalidNode = 0,
CurrentVersion,
AlphaVersion,
IsPresetNode = 0x0100,
IsAPVTSNode = 0x1000
}; | {
"repo_name": "vsicurella/SuperVirtualKeyboard",
"stars": "38",
"repo_language": "C++",
"file_name": "MapByOrderDialog.cpp",
"mime_type": "text/x-c"
} |
/*
==============================================================================
PluginState.h
Created: 7 Apr 2019 12:27:01pm
Author: Vincenzo
==============================================================================
*/
#pragma once
#include "JuceHeader.h"
#include "CommonFunctions.h"
#include "Constants.h"
#include "PluginIDs.h"
#include "PluginModes.h"
#include "PluginSettings.h"
#include "Midi/MidiProcessor.h"
#include "PresetManager.h"
#include "Structures/Preset.h"
#include "Structures/ModeMapper.h"
class SvkPluginState : public ChangeListener, public ValueTree::Listener
//private AudioProcessorValueTreeState::Listener
{
public:
AudioProcessorValueTreeState& svkTree;
ValueTree pluginStateNode;
//ValueTree pluginSettingsNode;
//ValueTree midiSettingsNode;
//ValueTree modeLibraryNode;
//ValueTree pianoNode;
SvkPluginState(AudioProcessorValueTreeState&);
~SvkPluginState() {}
//==============================================================================
// Data
void recallState(ValueTree nodeIn, bool fallbackToDefaultSettings = false);
// TODO: make it so it's not necessary to call this before saving (?)
void commitStateNode();
static int isValidStateNode(ValueTree pluginStateNodeIn);
//==============================================================================
// Object getters
ValueTree getPluginEditorNode() const;
ValueTree getMappingNode() const;
SvkPresetManager* getPresetManager();
SvkMidiProcessor* getMidiProcessor();
SvkPluginSettings* getPluginSettings();
ModeMapper* getModeMapper();
MappingHelper* getManualMappingHelper();
NoteMap* getMidiInputFilterMap();
NoteMap* getMidiOutputFilterMap();
ValueTree getPresetNode();
Mode* getModeInSlot(int slotNumIn) const;
Mode* getModeViewed();
Mode* getMode1();
Mode* getMode2();
Mode* getModeCustom();
//==============================================================================
// Parameter Getters
//float getParameterValue(Identifier paramId);
//float getParameterMin(Identifier paramId);
//float getParameterMax(Identifier paramId);
//float getParameterDefaultValue(Identifier paramId);
int getNumModesLoaded() const;
int getModeSelectorViewed() const;
int getModeViewedSlotNumber() const;
int getMappingMode() const;
int getAutoMappingStyle() const;
bool isAutoMapping() const;
//bool isAutoRetuning();
int getModeSlotRoot(int slotNum) const;
int getMode1Root() const;
int getMode2Root() const;
bool isPresetEdited();
// ValueTree::Listener Implementation
void valueTreePropertyChanged(ValueTree&, const Identifier&) override;
void valueTreeChildAdded(ValueTree& parentTree, ValueTree& child) override;
void valueTreeChildRemoved(ValueTree& parentTree, ValueTree& child, int index) override;
//==============================================================================
//void setParameterValue(Identifier paramIdIn, float valueIn);
void setMapMode(int mapModeSelectionIn, bool sendChangeMessage = true);
void setAutoMapStyle(int mapStyleIn);
void setModeSelectorRoot(int modeSlotIn, int rootNoteIn, bool updateParameter=false);
/*
Should be called whenever a mode is initialized in the PresetManager
*/
void onModeUpdate(bool sendModeViewedChangeMessage = true, bool sendMappingChangeMessage = true);
void sendChangeNotificationToHost();
//==============================================================================
// User Functionality
void setModeSelectorViewed(int modeViewedIn);
void handleModeSelection(int modeBoxNum, int idIn);
void setMidiInputMap(NoteMap noteMapIn, bool updateNode, bool sendChangeMessage = true);
void setMidiOutputMap(NoteMap noteMapIn, bool updateNode);
void setModeCustom(String stepsIn, bool sendChangeMessage = true);
void setMapOrder1(int orderIn);
void setMapOrder2(int orderIn);
void setMapOrderOffset1(int offsetIn);
void setMapOrderOffset2(int offsetIn);
void doAutoMapping(const Mode* mode1, const Mode* mode2, bool sendChangeMessage = true);
void doAutoMapping(bool sendChangeMessage = true);
void revertToSavedState(bool fallbackToDefaultSettings = false, bool sendChange = true);
bool savePresetToFile();
bool loadPresetFromFile();
bool saveModeViewedToFile();
bool loadModeFromFile();
void commitModeInfo(bool sendChangeMessage = true);
//==============================================================================
//void parameterChanged(const String& paramID, float newValue) override;
void changeListenerCallback(ChangeBroadcaster* source) override;
//==============================================================================
class Listener
{
public:
virtual ~Listener() {};
virtual void presetLoaded(ValueTree presetNodeIn) {};
virtual void resyncPresetNode(ValueTree presetNodeIn) {}; // TODO: make unnecessary
virtual void modeViewedChanged(Mode* modeIn, int selectorNumber, int slotNumber) {};
virtual void mappingModeChanged(int mappingModeId) {};
virtual void inputMappingChanged(NoteMap& inputNoteMap) {};
virtual void outputMappingChanged(NoteMap& outputNoteMap) {};
virtual void customModeChanged(Mode* newCustomMode) {};
virtual void modeInfoChanged(Mode* modeEdited) {};
};
void addListener(SvkPluginState::Listener* listenerIn) { listeners.add(listenerIn); }
void removeListener(SvkPluginState::Listener* listenerIn) { listeners.remove(listenerIn); }
protected:
ListenerList<Listener> listeners;
private:
//==============================================================================
// Internal Functionality
void buildFactoryDefaultState();
void buildUserDefaultState();
void updateModeViewed(bool sendChange=true);
void syncNodes(bool sendChange=true);
private:
std::unique_ptr<SvkPresetManager> presetManager;
std::unique_ptr<SvkMidiProcessor> midiProcessor;
std::unique_ptr<SvkPluginSettings> pluginSettings;
std::unique_ptr<ModeMapper> modeMapper;
std::unique_ptr<MappingHelper> manualMappingHelper;
AudioParameterBool* notifyHostDummy;
bool notifyHostValue = true;
ValueTree factoryDefaultPluginStateNode;
ValueTree defaultPluginStateNode;
SvkPreset* svkPreset;
ValueTree presetNode;
Mode* modeViewed; // What is currently on screen
int modeSelectorViewedNum = 1;
bool presetEdited = false;
};
| {
"repo_name": "vsicurella/SuperVirtualKeyboard",
"stars": "38",
"repo_language": "C++",
"file_name": "MapByOrderDialog.cpp",
"mime_type": "text/x-c"
} |
/*
==============================================================================
MidiProcessor.cpp
Created: 21 May 2019 6:37:57pm
Author: Vincenzo Sicurella
==============================================================================
*/
#include "MidiProcessor.h"
SvkMidiProcessor::SvkMidiProcessor()
{
midiSettingsNode = ValueTree(IDs::midiSettingsNode);
midiMapNode = ValueTree(IDs::midiMapNode);
midiSettingsNode.addChild(midiMapNode, -1, nullptr);
midiInputFilter = std::make_unique<MidiFilter>();
midiOutputFilter = std::make_unique<MidiFilter>();
midiInput = nullptr;
midiOutput = nullptr;
mpeInst.reset(new MPEInstrument());
originalKeyboardState.reset(new MidiKeyboardState());
remappedKeyboardState.reset(new MidiKeyboardState());
setRootNote(60);
}
SvkMidiProcessor::~SvkMidiProcessor()
{
}
void SvkMidiProcessor::updateNode()
{
midiSettingsNode.setProperty(IDs::rootMidiNote, rootMidiNote, nullptr);
midiSettingsNode.setProperty(IDs::pianoMidiChannel, midiChannelOut, nullptr);
midiSettingsNode.setProperty(IDs::periodShift, periodShift, nullptr);
midiSettingsNode.setProperty(IDs::periodShiftModeSize, useModePeriod, nullptr);
midiSettingsNode.setProperty(IDs::transposeAmt, transposeAmt, nullptr);
midiSettingsNode.setProperty(IDs::mpeOn, mpeOn, nullptr);
midiSettingsNode.setProperty(IDs::mpeThru, mpeThru, nullptr);
midiSettingsNode.setProperty(IDs::mpeZone, 0 /*do something here*/, nullptr);
midiSettingsNode.setProperty(IDs::mpeLegacyOn, mpeLegacyOn, nullptr);
midiSettingsNode.setProperty(IDs::pitchBendNoteMax, pitchBendNoteMax, nullptr);
midiSettingsNode.setProperty(IDs::pitchBendGlobalMax, pitchBendGlobalMax, nullptr);
midiSettingsNode.setProperty(IDs::mpePitchTrackingMode, mpePitchTrackingMode, nullptr);
midiSettingsNode.setProperty(IDs::mpePressureTrackingMode, mpePressureTrackingMode, nullptr);
midiSettingsNode.setProperty(IDs::mpeTimbreTrackingMode, mpeTimbreTrackingMode, nullptr);
Array<int> inputMap = midiInputFilter->getRemappedNotes();
midiMapNode.removeChild(midiMapNode.getChildWithName(IDs::midiInputMap), nullptr);
add_array_to_node(midiMapNode, inputMap, IDs::midiInputMap, "Note");
Array<int> outputMap = midiOutputFilter->getRemappedNotes();
midiMapNode.removeChild(midiMapNode.getChildWithName(IDs::midiOutputMap), nullptr);
add_array_to_node(midiMapNode, outputMap, IDs::midiOutputMap, "Note");
}
bool SvkMidiProcessor::restoreFromNode(ValueTree midiSettingsNodeIn)
{
if (midiSettingsNodeIn.hasType(IDs::midiSettingsNode))
{
midiSettingsNode.copyPropertiesAndChildrenFrom(midiSettingsNodeIn, nullptr);
// Root note
rootMidiNote = midiSettingsNode.getProperty(IDs::rootMidiNote);
// Set Note Maps
if (!midiSettingsNode.getChildWithName(IDs::midiMapNode).isValid())
{
midiMapNode = ValueTree(IDs::midiMapNode);
midiSettingsNode.addChild(midiMapNode, -1, nullptr);
}
setMidiMaps(midiSettingsNode.getChildWithName(IDs::midiMapNode));
return true;
}
return false;
}
//==============================================================================
StringArray SvkMidiProcessor::getAvailableInputs() const
{
return MidiInput::getDevices();
}
Array<MidiDeviceInfo> SvkMidiProcessor::getAvailableOutputs() const
{
return MidiOutput::getAvailableDevices();
}
MidiInput* SvkMidiProcessor::getInputDevice()
{
return midiInput.get();
}
MidiOutput* SvkMidiProcessor::getOutputDevice()
{
return midiOutput.get();
}
String SvkMidiProcessor::getInputName() const
{
return midiInputName;
}
String SvkMidiProcessor::getOutputName() const
{
return midiOutputName;
}
MidiKeyboardState* SvkMidiProcessor::getOriginalKeyboardState()
{
return originalKeyboardState.get();
}
MidiKeyboardState* SvkMidiProcessor::getRemappedKeyboardState()
{
return remappedKeyboardState.get();
}
int SvkMidiProcessor::getRootNote() const
{
return rootMidiNote;
}
int SvkMidiProcessor::getPeriodShift() const
{
return periodShift;
}
int SvkMidiProcessor::getMidiChannelOut() const
{
return midiChannelOut;
}
int SvkMidiProcessor::getTransposeAmt() const
{
return transposeAmt;
}
bool SvkMidiProcessor::isMPEOn() const
{
return mpeOn;
}
bool SvkMidiProcessor::isMPELegacyMode() const
{
return mpeLegacyOn;
}
bool SvkMidiProcessor::isMPEThru() const
{
return mpeThru;
}
MPEZoneLayout SvkMidiProcessor::getMPEZone() const
{
return mpeZone;
}
int SvkMidiProcessor::getPitchBendNoteMax() const
{
return pitchBendNoteMax;
}
int SvkMidiProcessor::getPitchBendGlobalMax() const
{
return pitchBendGlobalMax;
}
int SvkMidiProcessor::getPitchTrackingMode() const
{
return mpePitchTrackingMode;
}
int SvkMidiProcessor::getPressureTrackingMode() const
{
return mpePressureTrackingMode;
}
int SvkMidiProcessor::getTimbreTrackingMode() const
{
return mpeTimbreTrackingMode;
}
NoteMap* SvkMidiProcessor::getInputNoteMap()
{
return midiInputFilter->getNoteMap();
}
NoteMap* SvkMidiProcessor::getOutputNoteMap()
{
return midiOutputFilter->getNoteMap();
}
MidiFilter* SvkMidiProcessor::getMidiInputFilter()
{
return midiInputFilter.get();
}
MidiFilter* SvkMidiProcessor::getMidiOutputFilter()
{
return midiOutputFilter.get();
}
int SvkMidiProcessor::getInputNote(int midiNoteIn)
{
return midiInputFilter->getNoteRemapped(midiNoteIn);
}
int SvkMidiProcessor::getOutputNote(int midiNoteIn)
{
return midiOutputFilter->getNoteRemapped(midiNoteIn);
}
//==============================================================================
String SvkMidiProcessor::setMidiInput(String deviceID)
{
midiInput = MidiInput::openDevice(deviceID, this);
midiInputName = midiInput->getName();
if (midiInputName.isNotEmpty())
{
inputSelected = deviceID;
midiSettingsNode.setProperty(IDs::midiInputName, midiInput->getIdentifier(), nullptr);
}
else
{
inputSelected = "";
midiInput = nullptr;
}
return midiInputName;
}
String SvkMidiProcessor::setMidiOutput(String deviceID)
{
midiOutput = MidiOutput::openDevice(deviceID);
if (midiOutput.get())
{
midiOutputName = midiOutput->getName();
outputSelected = deviceID;
midiSettingsNode.setProperty(IDs::midiOutputName, midiOutput->getIdentifier(), nullptr);
}
else
{
midiOutputName = "";
outputSelected = "";
midiOutput = nullptr;
}
return midiOutputName;
}
void SvkMidiProcessor::setModeViewed(Mode* modeViewedIn)
{
modeViewed = modeViewedIn;
}
void SvkMidiProcessor::setMode1(Mode* mode1In)
{
mode1 = mode1In;
}
void SvkMidiProcessor::setMode2(Mode* mode2In)
{
mode2 = mode2In;
}
void SvkMidiProcessor::setRootNote(int rootNoteIn)
{
midiSettingsNode.setProperty(IDs::rootMidiNote, rootNoteIn, nullptr);
rootMidiNote = rootNoteIn;
}
void SvkMidiProcessor::setPeriodShift(int shiftIn)
{
midiSettingsNode.setProperty(IDs::periodShift, periodShift, nullptr);
periodShift = shiftIn;
}
void SvkMidiProcessor::periodUsesModeSize(bool useModeSizeIn)
{
useModePeriod = useModeSizeIn;
}
void SvkMidiProcessor::setMidiChannelOut(int channelOut)
{
if (channelOut < 1)
channelOut = 1;
channelOut = channelOut % 16;
midiSettingsNode.setProperty(IDs::pianoMidiChannel, channelOut, nullptr);
midiChannelOut = channelOut;
}
void SvkMidiProcessor::setTransposeAmt(int notesToTranspose)
{
transposeAmt = notesToTranspose;
}
void SvkMidiProcessor::setMPEOn(bool turnOnMPE)
{
mpeOn = turnOnMPE;
}
void SvkMidiProcessor::setMPEThru(bool mpeOnThru)
{
mpeThru = mpeOnThru;
}
void SvkMidiProcessor::setMPELegacy(bool turnOnLegacy)
{
mpeLegacyOn = turnOnLegacy;
}
void SvkMidiProcessor::setMPEZone(MPEZoneLayout zoneIn)
{
mpeZone = zoneIn;
}
void SvkMidiProcessor::setPitchBendNoteMax(int bendAmtIn)
{
pitchBendNoteMax = bendAmtIn;
}
void SvkMidiProcessor::setPitchBendGlobalMax(int bendAmtIn)
{
pitchBendGlobalMax = bendAmtIn;
}
void SvkMidiProcessor::setPitchTrackingMode(int modeIn)
{
mpePitchTrackingMode = modeIn;
}
void SvkMidiProcessor::setPressureTrackingMode(int modeIn)
{
mpePressureTrackingMode = modeIn;
}
void SvkMidiProcessor::setTimbreTrackingMode(int modeIn)
{
mpeTimbreTrackingMode = modeIn;
}
void SvkMidiProcessor::setInputToRemap(bool doRemap)
{
isInputRemapped = doRemap;
}
void SvkMidiProcessor::setOutputToRemap(bool doRemap)
{
isOutputRemapped = doRemap;
}
void SvkMidiProcessor::setMidiMaps(ValueTree midiMapIn)
{
if (midiMapIn.hasType(IDs::midiMapNode))
{
Array<int> map;
get_array_from_node(midiMapIn, map, IDs::midiInputMap);
if (map.size() > 0)
setMidiInputMap(map);
else
setMidiInputMap(NoteMap());
map.clear();
get_array_from_node(midiMapIn, map, IDs::midiOutputMap);
if (map.size() > 0)
setMidiOutputMap(map);
else
setMidiOutputMap(NoteMap());
midiMapNode.copyPropertiesAndChildrenFrom(midiMapIn, nullptr);
}
}
void SvkMidiProcessor::setMidiInputMap(Array<int> mapIn, bool updateNode)
{
midiInputFilter->setNoteMap(mapIn);
if (updateNode)
{
midiMapNode.removeChild(midiMapNode.getChildWithName(IDs::midiInputMap), nullptr);
add_array_to_node(midiMapNode, midiInputFilter->getNoteMap()->getValues(), IDs::midiInputMap, "Note");
}
}
void SvkMidiProcessor::setMidiInputMap(NoteMap mapIn, bool updateNode)
{
midiInputFilter->setNoteMap(mapIn);
if (updateNode)
{
midiMapNode.removeChild(midiMapNode.getChildWithName(IDs::midiInputMap), nullptr);
add_array_to_node(midiMapNode, midiInputFilter->getNoteMap()->getValues(), IDs::midiInputMap, "Note");
}
}
void SvkMidiProcessor::setMidiOutputMap(Array<int> mapIn, bool updateNode)
{
midiOutputFilter->setNoteMap(mapIn);
if (updateNode)
{
midiMapNode.removeChild(midiMapNode.getChildWithName(IDs::midiOutputMap), nullptr);
add_array_to_node(midiMapNode, midiInputFilter->getNoteMap()->getValues(), IDs::midiOutputMap, "Note");
}
}
void SvkMidiProcessor::setMidiOutputMap(NoteMap mapIn, bool updateNode)
{
midiOutputFilter->setNoteMap(mapIn.getValues());
if (updateNode)
{
midiMapNode.removeChild(midiMapNode.getChildWithName(IDs::midiOutputMap), nullptr);
add_array_to_node(midiMapNode, midiInputFilter->getNoteMap()->getValues(), IDs::midiOutputMap, "Note");
}
}
void SvkMidiProcessor::resetInputMap(bool updateNode)
{
setMidiInputMap(NoteMap(), updateNode);
}
void SvkMidiProcessor::resetOutputMap(bool updateNode)
{
setMidiOutputMap(NoteMap(), updateNode);
}
void SvkMidiProcessor::mapInputNote(int noteIn, int noteOut, bool updateNode)
{
midiInputFilter->setNote(noteIn, noteOut);
if (updateNode)
set_value_in_array(midiMapNode, IDs::midiInputMap, noteIn, noteOut);
}
void SvkMidiProcessor::mapOutputNode(int noteIn, int noteOut, bool updateNode)
{
midiOutputFilter->setNote(noteIn, noteOut);
if (updateNode)
set_value_in_array(midiMapNode, IDs::midiInputMap, noteIn, noteOut);
}
//==============================================================================
void SvkMidiProcessor::processMidi(MidiBuffer& midiMessages)
{
// Input filtering
auto midiEvent = MidiBuffer::Iterator(midiMessages);
MidiMessage msg;
int smpl;
int midiNote;
if (midiInput == nullptr)
{
while (midiEvent.getNextEvent(msg, smpl))
{
originalKeyboardState->processNextMidiEvent(msg);
midiNote = msg.getNoteNumber();
if (isInputRemapped)
midiNote = midiInputFilter->getNoteRemapped(msg.getNoteNumber());
msg.setNoteNumber(midiNote);
if (midiNote >= 0 && midiNote < 128)
{
msg.setTimeStamp(++msgCount);
remappedKeyboardState->processNextMidiEvent(msg);
addMessageToQueue(msg);
}
}
}
// Midi Output filtering
msgCount = 0;
midiMessages.clear();
removeNextBlockOfMessages(midiBuffer, 4096);
if (!midiInputPaused)
{
auto midiEventOut = MidiBuffer::Iterator(midiBuffer);
while (midiEventOut.getNextEvent(msg, smpl))
{
int midiNote = msg.getNoteNumber();
midiNote = midiOutputFilter->getNoteRemapped(msg.getNoteNumber());
midiNote += periodShift * mode2->getScaleSize();
msg.setNoteNumber(midiNote);
msg.setTimeStamp(++msgCount);
midiMessages.addEvent(msg, smpl);
sendMsgToOutputs(msg);
}
}
midiBuffer.clear();
msgCount = 0;
}
void SvkMidiProcessor::sendMsgToOutputs(const MidiMessage& msg)
{
if (midiOutput)
midiOutput->sendMessageNow(msg);
}
//==============================================================================
void SvkMidiProcessor::pauseMidiInput(bool setPaused)
{
midiInputPaused = setPaused;
}
bool SvkMidiProcessor::isMidiPaused()
{
return midiInputPaused;
}
//==============================================================================
void SvkMidiProcessor::handleNoteOn(MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity)
{
MidiMessage msg = MidiMessage::noteOn(midiChannel, midiNoteNumber, velocity);
msg.setTimeStamp(++msgCount);
addMessageToQueue(msg);
}
void SvkMidiProcessor::handleNoteOff(MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity)
{
MidiMessage msg = MidiMessage::noteOn(midiChannel, midiNoteNumber, velocity);
msg.setTimeStamp(++msgCount);
addMessageToQueue(msg);
}
void SvkMidiProcessor::handleIncomingMidiMessage(MidiInput* source, const MidiMessage& msg)
{
MidiMessage myMsg = MidiMessage(msg);
if (isInputRemapped && !midiInputPaused)
myMsg.setNoteNumber(midiInputFilter->getNoteRemapped(myMsg.getNoteNumber()));
addMessageToQueue(myMsg);
}
| {
"repo_name": "vsicurella/SuperVirtualKeyboard",
"stars": "38",
"repo_language": "C++",
"file_name": "MapByOrderDialog.cpp",
"mime_type": "text/x-c"
} |
/*
==============================================================================
PluginSettings.h
Created: 27 May 2019 1:46:06pm
Author: Vincenzo
==============================================================================
*/
#pragma once
#include "../JuceLibraryCode/JuceHeader.h"
#include "PluginIDs.h"
#include "CommonFunctions.h"
#include "Constants.h"
class SvkPluginSettings
{
const String appFolderName = "SuperVirtualKeyboard";
const String settingsFileName = "SuperVirtualKeyboard.svksettings";
const String presetSubDirectory = "Presets";
const String modeSubDirectory = "Modes";
File factoryDefaultSettingsLocation = File::getSpecialLocation(File::userApplicationDataDirectory).getChildFile(appFolderName);
File factoryDefaultPresetLocation = File::getSpecialLocation(File::userDocumentsDirectory).getChildFile(appFolderName).getChildFile(presetSubDirectory);
File factoryDefaultModeLocation = File::getSpecialLocation(File::userDocumentsDirectory).getChildFile(appFolderName).getChildFile(modeSubDirectory);
File currentSettingsLocation;
File currentPresetLocation;
File currentModeLocation;
ValueTree pluginSettingsNode;
bool createPresetFolder = true;
bool saveFactoryModes = false;
bool resetDirectories = false;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(SvkPluginSettings)
public:
SvkPluginSettings();
~SvkPluginSettings();
ValueTree getSettingsNode();
bool updateNode(bool writeSettings=false);
bool restoreNode(ValueTree pluginSettingsNodeIn);
String getSettingsPath();
String getPresetPath();
String getModePath();
bool getCreatePresetFolder();
bool getSaveFactoryModes();
void setPresetDirectory(File presetDirectoryIn);
void setModeDirectory(File modeDirectoryIn);
void setSettingsDirectory(File settingsDirectoryIn);
void setCreatePresetFolder(bool shouldCreateFolder);
void setSaveFactoryPresets(bool shouldSavePresets);
};
| {
"repo_name": "vsicurella/SuperVirtualKeyboard",
"stars": "38",
"repo_language": "C++",
"file_name": "MapByOrderDialog.cpp",
"mime_type": "text/x-c"
} |
/*
==============================================================================
PresetManager.h
Created: 27 May 2019 10:57:01pm
Author: Vincenzo
==============================================================================
*/
#pragma once
#include "../JuceLibraryCode/JuceHeader.h"
#include "CommonFunctions.h"
#include "PluginIDs.h"
#include "Structures/Preset.h"
#include "Structures/Mode.h"
class SvkPresetManager : public ChangeBroadcaster
{
Array<ValueTree> loadedFactoryModes;
Array<ValueTree> loadedUserModes;
Array<ValueTree> favoriteModes;
Array<Array<ValueTree>> modesSorted;
int numSortTypes = 4;
ScaleSizeSorter scaleSizeSort;
ModeSizeSorter modeSizeSort;
FamilyNameSorter familyNameSort;
SvkPreset svkPresetSaved;
SvkPreset svkPresetWorking;
OwnedArray<Mode> modeSlots;
std::unique_ptr<Mode> modeCustom;
// Methods
void createFactoryModes();
void resortModeLibrary();
void initializeModePresets();
void loadModeDirectory();
int addModeToLibrary(ValueTree modeNodeIn);
void addModeToSort(ValueTree modeNodeIn);
int addAndSortMode(ValueTree modeNodeIn);
public:
ValueTree presetLibraryNode;
ValueTree modeLibraryNode;
ValueTree pluginSettingsNode;
SvkPresetManager(ValueTree pluginSettingsNodeIn);
~SvkPresetManager();
SvkPreset& getPreset();
int getNumMenuItems(bool withFactoryMenu=true, bool withUserMenu=true, bool withFavMenu=true, bool withSlots=true);
int getNumModeSlots() const;
Array<int> getModeSlotsInUse() const;
int getModeSlotOfSelector(int modeSelectorNumIn) const;
ValueTree getModeInLibrary(int indexIn);
/*
Returns the mode in the given mode slot number
*/
Mode* getModeInSlot(int modeSlotNumIn);
/*
Returns the mode used by given selector
If the selector is set to an invalid slot, this will return nullptr
*/
Mode* getModeBySelector(int selectorNumber);
Mode* getModeCustom();
Mode* setModeCustom(ValueTree modeNodeIn);
Mode* setModeCustom(String stepsIn, String familyIn = "undefined", String nameIn = "", String infoIn = "", int rootNoteIn = 60);
int setSlotToMode(int modeSlotNum, ValueTree modeNode);
int addSlot(ValueTree modeNode);
int setSlotAndSelection(int modeSlotNum, int modeSelectorNum, ValueTree modeNode);
int addSlotAndSetSelection(int modeSelectorNumber, ValueTree modeNode);
void removeMode(int modeSlotNum);
void resetModeSlots();
/*
Replaces the mode slot the selector is pointed to with a new mode
- See note above definition -
*/
void handleModeSelection(int selectorNumber, int idIn);
bool loadPreset(ValueTree presetNodeIn, bool sendChangeSignal=true);
bool saveNodeToFile(ValueTree nodeToSave, String saveMsg, String fileEnding, String absolutePath = "");
bool savePresetToFile(String absolutePath="");
bool saveModeToFile(int modeSlotNumber, String absolutePath = "");
/*
Saves changes made since the last preset recall
Returns true if successful
*/
bool commitPreset();
/*
Reverts the changes made since the last recall
Returns true if successful
*/
bool resetToSavedPreset();
static ValueTree nodeFromFile(String openMsg, String fileEnding, String absoluteFilePath = "");
static ValueTree modeFromFile(String absoluteFilePath = "");
static ValueTree presetFromFile(String absoluteFilePath = "");
void requestModeMenu(PopupMenu* comboBoxToUse);
private:
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(SvkPresetManager)
};
| {
"repo_name": "vsicurella/SuperVirtualKeyboard",
"stars": "38",
"repo_language": "C++",
"file_name": "MapByOrderDialog.cpp",
"mime_type": "text/x-c"
} |
/*
==============================================================================
ReaperWriter.h
Created: 18 Apr 2019 12:22:34pm
Author: Vincenzo
==============================================================================
*/
#pragma once
#include "../../JuceLibraryCode/JuceHeader.h"
#include "../Structures/Mode.h"
class ReaperWriter
{
Mode* mode;
//Scale* scale;
Array<String> orderSymbols;
File filePath;
File fileOut;
void setup_default_symbols();
public:
ReaperWriter(Mode* modeIn);
~ReaperWriter();
void set_mode(Mode* modeIn);
void set_symbol(int orderIndex, String symbolIn);
bool set_path(String pathIn);
String ask_for_location();
Array<String> get_symbols();
String get_symbol(int orderIndexIn);
String get_path();
bool write();
};
| {
"repo_name": "vsicurella/SuperVirtualKeyboard",
"stars": "38",
"repo_language": "C++",
"file_name": "MapByOrderDialog.cpp",
"mime_type": "text/x-c"
} |
/*
==============================================================================
KbmWriter.h
Created: 23 Oct 2020 11:37:09pm
Author: Vincenzo
==============================================================================
*/
#pragma once
#include <JuceHeader.h>
#include "../Structures/ModeMapper.h"
class KbmWriter
{
public:
KbmWriter(
int sizeIn, int firstMidiNoteIn, int lastMidiNoteIn, int mappingRootNoteIn,
int referenceMidiNoteIn, double referenceFreqIn, int periodDegreeIn,
Array<int> mappingIn
) :
size(sizeIn), firstMidiNote(firstMidiNoteIn), lastMidiNote(lastMidiNoteIn), mappingRootMidiNote(mappingRootNoteIn),
referenceMidiNote(referenceMidiNoteIn), referenceFrequency(referenceFreqIn), periodDegree(periodDegreeIn),
mapping(mappingIn) {}
bool writeTo(const File& fileToWriteTo)
{
if (!fileToWriteTo.existsAsFile())
{
if (!fileToWriteTo.create())
return false;
}
StringArray valuesOut =
{
String(size), String(firstMidiNote), String(lastMidiNote),
String(mappingRootMidiNote), String(referenceMidiNote),
String(referenceFrequency), String(periodDegree), ""
};
// Ensure frequency is floating point
if (!valuesOut[5].containsChar('.'))
valuesOut.getReference(5) += ".0";
// Change OOB notes to x
for (auto deg : mapping)
{
String degOut = (deg < 0 || deg > 127) ? "x" : String(deg);
valuesOut.getReference(7) += degOut + '\n';
}
String fileTextOut;
for (int i = 0; i < sectionLabels.size(); i++)
{
if (i > 0)
fileTextOut += '\n';
fileTextOut += sectionLabels[i];
fileTextOut += valuesOut[i];
}
fileToWriteTo.replaceWithText(fileTextOut);
return true;
}
static KbmWriter fromModes(
const Mode* inputMode, const Mode* outputMode, const ModeMapper& mapperIn,
int firstMidiNoteIn = 0, int lastMidiNoteIn = 127, int mappingRootNoteIn = -1,
int referenceMidiNoteIn = 69, double referenceFreqIn = 440.0, int periodDegreeIn = -1)
{
Array<int> periodMap = mapperIn.getSelectedPeriodMap(*inputMode, *outputMode);
int middleNote = mappingRootNoteIn;
int period = periodDegreeIn;
int size = periodMap.size();
if (periodMap.size() >= 128)
{
middleNote = 0;
period = 127;
size = 0;
}
else
{
if (middleNote < 0 || middleNote > 127)
middleNote = outputMode->getRootNote();
if (period < 0)
period = outputMode->getScaleSize();
}
return KbmWriter(
size, jlimit(0, 127, firstMidiNoteIn), jlimit(0, 127, lastMidiNoteIn), middleNote,
jlimit(0, 127, referenceMidiNoteIn), jlimit(10e-3, 20e3, referenceFreqIn), period, periodMap
);
}
//static KbmWriter fromNoteMap(const NoteMap& noteMapIn)
//{
// Array<int> mapping;
//}
private:
int size;
int firstMidiNote;
int lastMidiNote;
int mappingRootMidiNote;
int referenceMidiNote;
double referenceFrequency;
int periodDegree;
Array<int> mapping;
StringArray sectionLabels =
{
"! Template for a keyboard mapping\n!\n! Size of map. The pattern repeats every so many keys:\n",
"! First MIDI note number to retune:\n",
"! Last MIDI note number to retune:\n",
"! Middle note where the first entry of the mapping is mapped to:\n",
"! Reference note for which frequency is given:\n",
"! Frequency to tune the above note to (floating point e.g. 440.0):\n",
"! Scale degree to consider as formal octave (determines difference in pitch\n! between adjacent mapping patterns):\n",
"! Mapping.\n! The numbers represent scale degrees mapped to keys. The first entry is for\n"
"! the given middle note, the next for subsequent higher keys.\n"
"! For an unmapped key, put in an \"x\". At the end, unmapped keys may be left out.\n"
};
}; | {
"repo_name": "vsicurella/SuperVirtualKeyboard",
"stars": "38",
"repo_language": "C++",
"file_name": "MapByOrderDialog.cpp",
"mime_type": "text/x-c"
} |
/*
==============================================================================
AbletonMidiSequence.h
Created: 14 Sep 2020 1:05:22am
Author: Vincenzo
==============================================================================
*/
#pragma once
#include "../Structures/Mode.h"
static File abletonUserLibrary =
#if JUCE_WINDOWS
File::getSpecialLocation(File::userDocumentsDirectory).getChildFile("Ableton").getChildFile("User Library")
#else
File::getSpecialLocation(File::userMusicDirectory).getChildFile("Ableton").getChildFile("User Library")
#endif
;
class AbletonMidiWriter
{
public:
AbletonMidiWriter(const Mode& modeIn)
: mode(modeIn)
{
refreshSequence();
};
bool writeTo(File directory = abletonUserLibrary, String filename = "")
{
if (!directory.exists())
directory = File::getSpecialLocation(File::userDocumentsDirectory);
if (filename.length() == 0)
filename = mode.getName();
if (!filename.endsWith(".mid"))
filename += ".mid";
File fileOut = File::createTempFile(".mid");
midiFile.clear();
midiFile.addTrack(sequence);
midiFile.setTicksPerQuarterNote(96);
File intendedFile = directory.getChildFile(filename);
FileOutputStream stream(intendedFile);
if (midiFile.writeTo(stream))
{
stream.flush();
DBG("File written");
return true;
}
return false;
}
bool write(String filename = "")
{
if (filename.length() == 0)
filename = mode.getName();
if (!filename.endsWith(".mid"))
filename += ".mid";
File intendedFile = abletonUserLibrary.exists()
? abletonUserLibrary.getChildFile(filename)
: File::getSpecialLocation(File::userDocumentsDirectory).getChildFile(filename);
FileChooser chooser("Save Ableton Midi Map", intendedFile, "*.mid");
if (chooser.browseForFileToSave(true))
return writeTo(chooser.getResult().getParentDirectory(), chooser.getResult().getFileName());
return false;
}
void refreshSequence()
{
Array<int> noteNums = mode.getNotesOfOrder();
sequence.clear();
for (auto noteNum : noteNums)
{
MidiMessage msg = MidiMessage::noteOn(1, noteNum, (uint8)1);
sequence.addEvent(msg);
}
for (auto noteNum : noteNums)
{
MidiMessage msg = MidiMessage::noteOff(1, noteNum);
sequence.addEvent(msg, 96);
}
sequence.updateMatchedPairs();
}
private:
const Mode& mode;
MidiFile midiFile;
MidiMessageSequence sequence;
}; | {
"repo_name": "vsicurella/SuperVirtualKeyboard",
"stars": "38",
"repo_language": "C++",
"file_name": "MapByOrderDialog.cpp",
"mime_type": "text/x-c"
} |
/*
==============================================================================
ReaperWriter.cpp
Created: 18 Apr 2019 12:22:34pm
Author: Vincenzo
==============================================================================
*/
#include "ReaperWriter.h"
ReaperWriter::ReaperWriter(Mode* modeIn)
{
mode = modeIn;
// check if reaper resource path exists
if ((SystemStats::getOperatingSystemType() & SystemStats::OperatingSystemType::MacOSX) != 0)
{
filePath = File(File::getSpecialLocation(File::userApplicationDataDirectory).getChildFile("Application Support").getChildFile("REAPER").getChildFile("MIDINoteNames"));
}
else if ((SystemStats::getOperatingSystemType() & SystemStats::OperatingSystemType::Windows) != 0)
{
filePath = File(File::getSpecialLocation(File::userHomeDirectory).getChildFile("AppData").getChildFile("Roaming").getChildFile("REAPER").getChildFile("MIDINoteNames"));
}
if (!filePath.isDirectory())
filePath = File::getSpecialLocation(File::userDocumentsDirectory);
FileChooser chooser("Save as", filePath, "*.txt");
chooser.browseForFileToSave(true);
fileOut = chooser.getResult();
setup_default_symbols();
}
ReaperWriter::~ReaperWriter()
{
}
void ReaperWriter::set_mode(Mode* modeIn)
{
mode = modeIn;
}
void ReaperWriter::set_symbol(int orderIndex, String symbolIn)
{
orderSymbols.set(orderIndex % orderSymbols.size(), symbolIn);
}
bool ReaperWriter::set_path(String pathIn)
{
fileOut = File(pathIn);
return fileOut.getParentDirectory().isDirectory();
}
String ReaperWriter::ask_for_location()
{
return "";
}
Array<String> ReaperWriter::get_symbols()
{
return orderSymbols;
}
String ReaperWriter::get_symbol(int orderIndexIn)
{
return orderSymbols[orderIndexIn];
}
String ReaperWriter::get_path()
{
return fileOut.getFullPathName();
}
void ReaperWriter::setup_default_symbols()
{
orderSymbols.clear();
CharPointer_UTF8 block = CharPointer_UTF8("\xe2\x96\x88");
String symbol;
int orderMax = mode->getMaxStep();
int repeats = 11;
for (int i = 0; i < repeats; i++)
{
symbol = "";
for (int o = 0; o < (repeats - i); o++)
{
symbol += *block;
}
orderSymbols.add(symbol);
}
}
bool ReaperWriter::write()
{
Array<int> modeOrders = mode->getOrders();
Array<float> modeDegrees = Mode::ordersToModalDegrees(modeOrders);
if (!fileOut.getParentDirectory().exists())
return false;
std::unique_ptr<FileOutputStream> outStream(fileOut.createOutputStream());
if (!outStream->openedOk())
return false;
outStream->setPosition(0);
outStream->truncate();
// Header
outStream->writeText("# MIDI note / CC name map\n", false, false, nullptr);
int scaleSize = mode->getScaleSize();
int modeSize = mode->getModeSize();
int order;
int index;
float degree;
String noteName;
for (int i = 0; i < 128; i++)
{
index = 127 - i;
order = modeOrders[index];
degree = modeDegrees[index];
noteName = String(degree - ((int) degree / modeSize) * modeSize);
outStream->writeText(String(index) + " ", false, false, nullptr);
if (order != 0)
{
outStream->writeText(orderSymbols[order-1], false, false, nullptr);
}
outStream->writeText(" " + noteName, false, false, nullptr);
outStream->write("\n", 1);
}
outStream->flush();
return true;
}
| {
"repo_name": "vsicurella/SuperVirtualKeyboard",
"stars": "38",
"repo_language": "C++",
"file_name": "MapByOrderDialog.cpp",
"mime_type": "text/x-c"
} |
/*
==============================================================================
MidiProcessor.h
Created: 21 May 2019 6:37:57pm
Author: Vincenzo Sicurella
==============================================================================
*/
#pragma once
#include "../JuceLibraryCode/JuceHeader.h"
#include "../CommonFunctions.h"
#include "../Structures/MidiFilter.h"
#include "../Structures/Mode.h"
#include "../Structures/MappingHelper.h"
class SvkMidiProcessor : public MidiInputCallback,
public MidiKeyboardStateListener
{
public:
SvkMidiProcessor();
~SvkMidiProcessor();
ValueTree midiSettingsNode;
ValueTree midiMapNode;
ValueTree midiDeviceNode;
void updateNodes();
bool restoreSettingsNode(ValueTree midiSettingsNodeIn);
bool restoreMappingNode(ValueTree midiMapIn);
bool restoreDevicesNode(ValueTree midiDevicesNodeIn);
MidiInput* getInputDevice();
MidiOutput* getOutputDevice();
String getInputName() const;
String getOutputName() const;
MidiKeyboardState* getOriginalKeyboardState();
MidiKeyboardState* getRemappedKeyboardState();
int getPeriodShift() const;
int getTransposeAmt() const;
int getMidiChannelOut() const;
NoteMap* getInputNoteFilter();
NoteMap* getInputNoteRemap();
NoteMap* getOutputNoteFilter();
NoteMap getManualNoteMap() const;
MidiFilter* getInputMidiFilter();
MidiFilter* getInputRemapMidiFilter();
MidiFilter* getOutputMidiFilter();
int getInputNote(int midiNoteIn);
int getOutputNote(int midiNoteIn);
int getVoiceLimit() const;
bool isRetuning() const;
String setMidiInput(String deviceID);
String setMidiOutput(String deviceID);
void setModeViewed(Mode* modeViewedIn);
void setMode1(Mode* mode1In);
void setMode2(Mode* mode2In);
void setInputToFilter(bool doRemap=true);
void setInputToRemap(bool doRemap=true);
void setOutputToFilter(bool doFilter=true);
void setInputFilter(Array<int> mapIn, bool updateNode=true);
void setInputFilter(NoteMap mapIn, bool updateNode=true);
void setInputRemap(Array<int> mapIn, bool updateNode=true);
void setInputRemap(NoteMap mapIn, bool updateNode = true);
void setOutputFilter(Array<int> mapIn, bool updateNode = true);
void setOutputFilter(NoteMap mapIn, bool updateNode = true);
/*
How many periods to shift notes.
Notes held will be transposed for now.
*/
void setPeriodShift(int periodsToShift);
/*
Sets the value to transpose all notes by
*/
void setTransposeAmt(int transposeAmtIn);
/*
The MIDI channel for mouse-based virtual keyboard interaction
*/
void setMidiChannelOut(int virtualKeyboardMidiChannelOut);
/*
Updates the note number transposition cache
*/
void updateNoteTransposition();
//void setVoiceLimit(int maxVoicesIn);
//void setRetuneOn(bool retuneOn);
void setMappingHelper(MappingHelper* helperIn);
void setInManualMappingMode(bool manualModeOn);
void resetInputFilter(bool updateNode=true);
void resetInputMap(bool updateNode=true);
void resetOutputFilter(bool updateNode=true);
void processMidi(MidiBuffer& midiMessages);
//MidiBuffer convertToMPE(const MidiBuffer& bufferToConvert);
void sendMsgToOutputs(const MidiMessage& msgToSend);
void sendBufferToOutputs(const MidiBuffer& bufferToSend);
void allNotesOff();
void pauseMidiInput(bool setPaused=true);
bool isMidiPaused();
//void parameterChanged(const String& paramID, float newValue) override;
// 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;
private:
std::unique_ptr<MidiInput> midiInput;
std::unique_ptr<MidiOutput> midiOutput;
String midiInputName = "";
String midiOutputName = "";
String inputSelected = "";
String outputSelected = "";
double startTime;
MidiBuffer externalInputBuffer;
int numInputMsgs = 0;
MidiBuffer svkBuffer;
int numSvkMsgs = 0;
MidiBuffer directOutBuffer;
int directMsgs = 0;
MidiBuffer allNotesOffBuffer;
Array<Array<int>> notesOnPerChannel;
Mode* modeViewed;
Mode* mode1;
Mode* mode2;
int periodShift = 0;
bool periodShiftModeSize = false;
int transposeAmt = 0;
int currentNoteShift = 0;
int midiChannelOut = 1;
int maxNumVoices = 15;
int pitchBendNoteMax = 48;
int pitchBendGlobalMax = 2;
bool mpeTuningPreserveMidiNote = true;
std::unique_ptr<MidiFilter> midiInputFilter;
std::unique_ptr<MidiFilter> midiInputRemap;
std::unique_ptr<MidiFilter> midiOutputFilter;
MappingHelper* manualMappingHelper;
NoteMap currentRemap;
NoteMap manualRemap;
bool inManualMappingMode = false;
int mpePitchbendTrackingMode = 0;
int mpePressureTrackingMode = 0;
int mpeTimbreTrackingMode = 0;
bool mpeOn = false;
bool doRetuning = false;
bool midiInputPaused = false;
bool isInputFiltered = false;
bool isInputRemapped = true;
bool isOutputFiltered = false;
bool noteMapIsCustom = false;
std::unique_ptr<MidiKeyboardState> originalKeyboardState; // post-filtered input
std::unique_ptr<MidiKeyboardState> remappedKeyboardState; // remapped input
};
| {
"repo_name": "vsicurella/SuperVirtualKeyboard",
"stars": "38",
"repo_language": "C++",
"file_name": "MapByOrderDialog.cpp",
"mime_type": "text/x-c"
} |
/*
==============================================================================
MidiProcessor.cpp
Created: 21 May 2019 6:37:57pm
Author: Vincenzo Sicurella
==============================================================================
*/
#include "MidiProcessor.h"
SvkMidiProcessor::SvkMidiProcessor()
{
midiInputFilter.reset(new MidiFilter());
midiInputRemap.reset(new MidiFilter());
midiOutputFilter.reset(new MidiFilter());
midiInput = nullptr;
midiOutput = nullptr;
originalKeyboardState.reset(new MidiKeyboardState());
remappedKeyboardState.reset(new MidiKeyboardState());
notesOnPerChannel.resize(16);
startTime = Time::getMillisecondCounterHiRes();
// Create all-notes-off buffer
for (int i = 0; i < 128; i++)
for (int ch = 1; ch <= 16; ch++)
allNotesOffBuffer.addEvent(MidiMessage::noteOff(ch, i), ch * 16 + i);
}
SvkMidiProcessor::~SvkMidiProcessor()
{
}
//==============================================================================
void SvkMidiProcessor::updateNodes()
{
//midiSettingsNode.setProperty(IDs::mpeThru, mpeThru, nullptr);
//midiSettingsNode.setProperty(IDs::mpeZone, 0 /*do something here*/, nullptr);
//midiSettingsNode.setProperty(IDs::mpeLegacyOn, mpeInst->isLegacyModeEnabled(), nullptr);
//midiSettingsNode.setProperty(IDs::pitchBendNoteMax, pitchBendNoteMax, nullptr);
//midiSettingsNode.setProperty(IDs::pitchBendGlobalMax, mpeInst->getLegacyModePitchbendRange(), nullptr);
//midiSettingsNode.setProperty(IDs::mpePitchTrackingMode, mpePitchbendTrackingMode, nullptr);
//midiSettingsNode.setProperty(IDs::mpePressureTrackingMode, mpePressureTrackingMode, nullptr);
//midiSettingsNode.setProperty(IDs::mpeTimbreTrackingMode, mpeTimbreTrackingMode, nullptr);
//midiSettingsNode.setProperty(IDs::mpeTuningPreserveMidiNote, mpeTuningPreserveMidiNote, nullptr);
// Unused so far / TODO
//NoteMap* inputFilter = midiInputFilter->getNoteMap();
//midiMapNode.removeChild(midiMapNode.getChildWithName(IDs::midiInputFilter), nullptr);
//if (*inputFilter != standardNoteMap)
// midiMapNode.appendChild(inputFilter->getAsValueTree(IDs::midiInputFilter), nullptr);
midiMapNode.removeChild(midiMapNode.getChildWithName(IDs::midiInputRemap), nullptr);
if (inManualMappingMode || (manualRemap != currentRemap))
midiMapNode.appendChild(manualRemap.getAsValueTree(IDs::midiInputRemap), nullptr);
// Unused so far / TODO
//NoteMap* outputFilter = midiOutputFilter->getNoteMap();
//midiMapNode.removeChild(midiMapNode.getChildWithName(IDs::midiOutputFilter), nullptr);
//if (*outputFilter != standardNoteMap)
// midiMapNode.appendChild(outputFilter->getAsValueTree(IDs::midiOutputFilter), nullptr);
}
bool SvkMidiProcessor::restoreSettingsNode(ValueTree midiSettingsNodeIn)
{
if (midiSettingsNodeIn.hasType(IDs::midiSettingsNode))
{
midiSettingsNode = midiSettingsNodeIn;
periodShift = midiSettingsNode[IDs::periodShift];
transposeAmt = midiSettingsNode[IDs::transposeAmt];
midiChannelOut = jlimit(1, 16, (int) midiSettingsNode[IDs::keyboardMidiChannel]);
// Note transposition is updated when new mode is applied
return true;
}
return false;
}
bool SvkMidiProcessor::restoreMappingNode(ValueTree midiMapIn)
{
bool loadedMap = false;
if (midiMapIn.hasType(IDs::midiMapNode))
{
midiMapNode = midiMapIn;
Array<int> map;
NoteMap noteMap;
//get_array_from_node(midiMapIn, map, IDs::midiInputFilter);
//
//if (map.size() > 0)
// setInputFilter(map);
//else
// resetInputFilter();
//
//map.clear();
ValueTree remapNode = midiMapNode.getChildWithName(IDs::midiInputRemap);
noteMap = NoteMap(midiMapNode.getChildWithName(IDs::midiInputRemap));
if (remapNode.isValid() && remapNode.getNumChildren() > 0)
{
loadedMap = true;
setInputRemap(noteMap);
}
//map.clear();
//get_array_from_node(midiMapIn, map, IDs::midiOutputFilter);
//
//if (map.size() > 0)
// setOutputFilter(map);
//else
// resetOutputFilter();
}
return loadedMap;
}
bool SvkMidiProcessor::restoreDevicesNode(ValueTree midiDevicesNodeIn)
{
// TODO: check if devices exist, give a name to imply if it doesn't
if (JUCEApplication::isStandaloneApp && midiDevicesNodeIn.hasType(IDs::midiDeviceSettingsNode))
{
midiDeviceNode = midiDevicesNodeIn;
setMidiInput(midiDeviceNode[IDs::midiInputName]);
setMidiOutput(midiDeviceNode[IDs::midiOutputName]);
return true;
}
return false;
}
//==============================================================================
MidiInput* SvkMidiProcessor::getInputDevice()
{
return midiInput.get();
}
MidiOutput* SvkMidiProcessor::getOutputDevice()
{
return midiOutput.get();
}
String SvkMidiProcessor::getInputName() const
{
return midiInputName;
}
String SvkMidiProcessor::getOutputName() const
{
return midiOutputName;
}
MidiKeyboardState* SvkMidiProcessor::getOriginalKeyboardState()
{
return originalKeyboardState.get();
}
MidiKeyboardState* SvkMidiProcessor::getRemappedKeyboardState()
{
return remappedKeyboardState.get();
}
int SvkMidiProcessor::getPeriodShift() const
{
return periodShift;
}
int SvkMidiProcessor::getMidiChannelOut() const
{
return midiChannelOut;
}
int SvkMidiProcessor::getTransposeAmt() const
{
return transposeAmt;
}
int SvkMidiProcessor::getVoiceLimit() const
{
return maxNumVoices;
}
bool SvkMidiProcessor::isRetuning() const
{
return doRetuning;
}
NoteMap* SvkMidiProcessor::getInputNoteRemap()
{
return midiInputRemap->getNoteMap();
}
NoteMap* SvkMidiProcessor::getOutputNoteFilter()
{
return midiOutputFilter->getNoteMap();
}
NoteMap SvkMidiProcessor::getManualNoteMap() const
{
return manualRemap;
}
MidiFilter* SvkMidiProcessor::getInputRemapMidiFilter()
{
return midiInputRemap.get();
}
MidiFilter* SvkMidiProcessor::getOutputMidiFilter()
{
return midiOutputFilter.get();
}
//
//MPEInstrument* SvkMidiProcessor::getMPEInstrument()
//{
// return mpeInst.get();
//}
int SvkMidiProcessor::getInputNote(int midiNoteIn)
{
return midiInputRemap->getNoteRemapped(midiNoteIn);
}
int SvkMidiProcessor::getOutputNote(int midiNoteIn)
{
return midiOutputFilter->getNoteRemapped(midiNoteIn);
}
//==============================================================================
String SvkMidiProcessor::setMidiInput(String deviceID)
{
std::unique_ptr<MidiInput> inputToOpen = MidiInput::openDevice(deviceID, this);
if (inputToOpen.get())
{
if (midiInput.get())
midiInput->stop();
midiInput.swap(inputToOpen);
midiInput->start();
midiInputName = midiInput->getName();
inputSelected = deviceID;
midiDeviceNode.setProperty(IDs::midiInputName, inputSelected, nullptr);
DBG("Successfully opened input " + midiInputName);
}
else
{
inputSelected = "";
midiInput = nullptr;
}
return midiInputName;
}
String SvkMidiProcessor::setMidiOutput(String deviceID)
{
std::unique_ptr<MidiOutput> outputToOpen = MidiOutput::openDevice(deviceID);
if (outputToOpen.get())
{
midiOutput.swap(outputToOpen);
midiOutputName = midiOutput->getName();
outputSelected = deviceID;
midiDeviceNode.setProperty(IDs::midiOutputName, outputSelected, nullptr);
DBG("Successfully opened output " + midiOutputName);
}
else
{
midiOutputName = "";
outputSelected = "";
midiOutput = nullptr;
}
return midiOutputName;
}
void SvkMidiProcessor::setModeViewed(Mode* modeViewedIn)
{
modeViewed = modeViewedIn;
}
void SvkMidiProcessor::setMode1(Mode* mode1In)
{
mode1 = mode1In;
}
void SvkMidiProcessor::setMode2(Mode* mode2In)
{
mode2 = mode2In;
updateNoteTransposition();
}
void SvkMidiProcessor::setPeriodShift(int periodsToShift)
{
periodShift = periodsToShift;
midiSettingsNode.setProperty(IDs::periodShift, periodShift, nullptr);
updateNoteTransposition();
}
void SvkMidiProcessor::setTransposeAmt(int transposeAmtIn)
{
transposeAmt = transposeAmtIn;
midiSettingsNode.setProperty(IDs::transposeAmt, transposeAmt, nullptr);
updateNoteTransposition();
}
void SvkMidiProcessor::setMidiChannelOut(int virtualKeyboardMidiChannelOut)
{
midiChannelOut = virtualKeyboardMidiChannelOut;
midiSettingsNode.setProperty(IDs::keyboardMidiChannel, midiChannelOut, nullptr);
// TODO: remove notes or better yet...use a note queue for the proper note off
}
void SvkMidiProcessor::updateNoteTransposition()
{
currentNoteShift = transposeAmt;
if (periodShiftModeSize)
currentNoteShift += periodShift * mode2->getModeSize();
else
currentNoteShift += periodShift * mode2->getScaleSize();
// handle sustained notes | TODO: more thorough solution
for (int i = 0; i < 16; i++)
{
Array<int>& channel = notesOnPerChannel.getReference(i);
for (auto note : channel)
{
directOutBuffer.addEvent(MidiMessage::noteOff(i + 1, note), directMsgs++);
}
}
}
//void SvkMidiProcessor::setRetuneOn(bool retuneOn)
//{
// doRetuning = retuneOn;
//}
void SvkMidiProcessor::setInputToFilter(bool doRemap)
{
isInputFiltered = doRemap;
}
void SvkMidiProcessor::setInputToRemap(bool doRemap)
{
isInputRemapped = doRemap;
}
void SvkMidiProcessor::setOutputToFilter(bool doFilter)
{
isOutputFiltered = doFilter;
}
void SvkMidiProcessor::setInputFilter(Array<int> mapIn, bool updateNode)
{
setInputFilter(NoteMap(mapIn));
}
void SvkMidiProcessor::setInputFilter(NoteMap mapIn, bool updateNode)
{
midiInputFilter->setNoteMap(mapIn);
if (updateNode)
{
midiMapNode.removeChild(midiMapNode.getChildWithName(IDs::midiInputFilter), nullptr);
add_array_to_node(midiMapNode, midiInputFilter->getNoteMap()->getValues(), IDs::midiInputFilter, "Note");
}
}
void SvkMidiProcessor::setInputRemap(Array<int> mapIn, bool updateNode)
{
setInputRemap(NoteMap(mapIn));
}
void SvkMidiProcessor::setInputRemap(NoteMap mapIn, bool updateNode)
{
// not using inManualMappingMode because the processMidi call depends on it,
// and setting that to "true" before initialization is complete causes a crash in some hosts
if ((int)midiMapNode[IDs::mappingMode] == 3 || updateNode)
manualRemap = mapIn;
currentRemap = mapIn;
midiInputRemap->setNoteMap(currentRemap);
if (updateNode)
{
midiMapNode.removeChild(midiMapNode.getChildWithName(IDs::midiInputRemap), nullptr);
midiMapNode.appendChild(currentRemap.getAsValueTree(IDs::midiInputRemap), nullptr);
//add_array_to_node(midiMapNode, midiInputRemap->getNoteMap()->getValues(), IDs::midiInputRemap, "Note");
}
}
void SvkMidiProcessor::setOutputFilter(Array<int> mapIn, bool updateNode)
{
setOutputFilter(NoteMap(mapIn));
}
void SvkMidiProcessor::setOutputFilter(NoteMap mapIn, bool updateNode)
{
midiOutputFilter->setNoteMap(mapIn.getValues());
if (updateNode)
{
midiMapNode.removeChild(midiMapNode.getChildWithName(IDs::midiOutputFilter), nullptr);
midiMapNode.appendChild(mapIn.getAsValueTree(IDs::midiOutputFilter), nullptr);
//add_array_to_node(midiMapNode, midiInputRemap->getNoteMap()->getValues(), IDs::midiOutputFilter, "Note");
}
}
void SvkMidiProcessor::resetInputFilter(bool updateNode)
{
setInputFilter(NoteMap(), updateNode);
}
void SvkMidiProcessor::resetInputMap(bool updateNode)
{
setInputRemap(NoteMap(), updateNode);
}
void SvkMidiProcessor::resetOutputFilter(bool updateNode)
{
setOutputFilter(NoteMap(), updateNode);
}
void SvkMidiProcessor::setMappingHelper(MappingHelper* helperIn)
{
manualMappingHelper = helperIn;
}
void SvkMidiProcessor::setInManualMappingMode(bool manualModeOn)
{
inManualMappingMode = manualModeOn;
}
//==============================================================================
void SvkMidiProcessor::processMidi(MidiBuffer &midiMessages)
{
// TODO: handle note offs if period/transpose is changed before note offs
// Combine external inputs
midiMessages.addEvents(externalInputBuffer, 0, numInputMsgs, 0);
externalInputBuffer.clear();
numInputMsgs = 0;
// Process input
MidiBuffer combinedMessages;
MidiMessage msg;
int midiNote;
for (auto msgData : midiMessages)
{
msg = msgData.getMessage();
if (msg.isNoteOnOrOff())
{
midiNote = msg.getNoteNumber();
if (inManualMappingMode)
{
if (manualMappingHelper->isWaitingForKeyInput())
{
MessageManagerLock lock;
manualMappingHelper->mapPreparedKeyToNote(midiNote, false);
originalKeyboardState->processNextMidiEvent(msg);
continue;
}
}
if (isInputFiltered)
{
midiNote = midiInputFilter->getNoteRemapped(midiNote);
}
originalKeyboardState->processNextMidiEvent(msg);
if (isInputRemapped)
{
midiNote = midiInputRemap->getNoteRemapped(midiNote);
}
msg.setNoteNumber(midiNote);
remappedKeyboardState->processNextMidiEvent(msg);
}
combinedMessages.addEvent(msg, msgData.samplePosition);
}
combinedMessages.addEvents(svkBuffer, 0, numSvkMsgs, 0);
MidiBuffer finalOutputBuffer;
// Output Filtering on all MIDI events
for (auto msgData : combinedMessages)
{
if (!msgData.numBytes)
continue;
msg = msgData.getMessage();
// Process transpositions
if (msg.isNoteOnOrOff())
{
midiNote = msg.getNoteNumber() + currentNoteShift;
if (isOutputFiltered)
{
midiNote = midiOutputFilter->getNoteRemapped(midiNote);
}
if (midiNote < 0 || midiNote > 127)
continue;
msg.setNoteNumber(midiNote);
// TODO: better method for handling this (when transpositions change before note off)
if (msg.isNoteOn())
notesOnPerChannel.getReference(msg.getChannel() - 1).addIfNotAlreadyThere(msg.getNoteNumber());
else if (msg.isNoteOff())
notesOnPerChannel.getReference(msg.getChannel() - 1).removeAllInstancesOf(msg.getNoteNumber());
}
finalOutputBuffer.addEvent(msg, msgData.samplePosition);
}
svkBuffer.clear();
numSvkMsgs = 0;
finalOutputBuffer.addEvents(directOutBuffer, 0, directMsgs, 0);
directOutBuffer.clear();
directMsgs = 0;
midiMessages.swapWith(finalOutputBuffer);
sendBufferToOutputs(midiMessages);
}
void SvkMidiProcessor::sendMsgToOutputs(const MidiMessage& msg)
{
if (midiOutput)
midiOutput->sendMessageNow(msg);
}
void SvkMidiProcessor::sendBufferToOutputs(const MidiBuffer& bufferToSend)
{
if (midiOutput)
{
midiOutput->sendBlockOfMessagesNow(bufferToSend);
}
}
void SvkMidiProcessor::allNotesOff()
{
auto events = MidiBuffer::Iterator(allNotesOffBuffer);
MidiMessage msg;
int smplNum;
while (events.getNextEvent(msg, smplNum))
{
externalInputBuffer.addEvent(msg, numInputMsgs++);
}
}
//==============================================================================
void SvkMidiProcessor::pauseMidiInput(bool setPaused)
{
midiInputPaused = setPaused;
}
bool SvkMidiProcessor::isMidiPaused()
{
return midiInputPaused;
}
//==============================================================================
//
//void SvkMidiProcessor::parameterChanged(const String& paramID, float newValue)
//{
// if (paramID == IDs::mappingMode.toString())
// {
// isInputRemapped = newValue > 1;
// }
// else if (paramID == IDs::periodShift.toString())
// {
// periodShift = newValue;
// updateNoteTransposition();
// }
// else if (paramID == IDs::periodShiftModeSize.toString())
// {
// periodShiftModeSize = newValue;
// }
// else if (paramID == IDs::transposeAmt.toString())
// {
// transposeAmt = newValue;
// updateNoteTransposition();
// }
// else if (paramID == IDs::keyboardMidiChannel.toString())
// {
// //allNotesOff(midiChannelOut);
// midiChannelOut = newValue;
// }
// else if (paramID == IDs::mpeOn.toString())
// {
// mpeOn = newValue;
// }
//
// DBG("Midi processor updated parameter " + paramID + " to " + String(newValue));
//}
void SvkMidiProcessor::handleNoteOn(MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity)
{
MidiMessage msg = MidiMessage::noteOn(midiChannelOut, midiNoteNumber, velocity);
msg.setTimeStamp(Time::getMillisecondCounterHiRes() - startTime);
svkBuffer.addEvent(msg, numSvkMsgs++);
}
void SvkMidiProcessor::handleNoteOff(MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity)
{
MidiMessage msg = MidiMessage::noteOn(midiChannelOut, midiNoteNumber, velocity);
msg.setTimeStamp(Time::getMillisecondCounterHiRes() - startTime);
svkBuffer.addEvent(msg, numSvkMsgs++);
}
void SvkMidiProcessor::handleIncomingMidiMessage(MidiInput* source, const MidiMessage& msg)
{
MidiMessage myMsg = MidiMessage(msg);
externalInputBuffer.addEvent(myMsg, numInputMsgs++);
} | {
"repo_name": "vsicurella/SuperVirtualKeyboard",
"stars": "38",
"repo_language": "C++",
"file_name": "MapByOrderDialog.cpp",
"mime_type": "text/x-c"
} |
/*
==============================================================================
FractionalGrid.cpp
Created: 22 Apr 2019 12:05:22pm
Author: Vincenzo
==============================================================================
*/
#include "Preset.h"
SvkPreset::SvkPreset()
{
parentNode = ValueTree(IDs::presetNode);
parentNode.setProperty(IDs::pluginPresetVersion, SVK_PRESET_VERSION, nullptr);
thePropertiesNode = parentNode.getOrCreateChildWithName(IDs::presetProperties, nullptr);
theModeSlots = parentNode.getOrCreateChildWithName(IDs::modeSlotsNode, nullptr);
theModeSelectors = parentNode.getOrCreateChildWithName(IDs::modeSelectorsNode, nullptr);
theCustomMode = parentNode.getOrCreateChildWithName(IDs::modeCustomNode, nullptr);
theKeyboardNode = parentNode.getOrCreateChildWithName(IDs::pianoNode, nullptr);
theMidiSettingsNode = parentNode.getOrCreateChildWithName(IDs::midiSettingsNode, nullptr);
theMappingsNode = parentNode.getOrCreateChildWithName(IDs::midiMapNode, nullptr);
}
SvkPreset::SvkPreset(const ValueTree presetNodeIn)
: SvkPreset()
{
restoreFromNode(presetNodeIn, true);
}
SvkPreset::SvkPreset(const SvkPreset& presetToCopy)
: SvkPreset(presetToCopy.parentNode.createCopy())
{
}
SvkPreset::~SvkPreset() {}
ValueTree SvkPreset::getPresetNode(bool sortModeSlots)
{
if (sortModeSlots)
{
// TODO: Maybe rethink the context of this...
// If sorted, PresetManager's ModeSlots will need to be resynched
HashMap<int, ValueTree> slotMap;
for (auto mode : theModeSlots)
slotMap.set(mode[IDs::modeSlotNumber], mode);
theModeSlots.removeAllChildren(nullptr);
for (auto slotNum : slotNumbersInUse)
theModeSlots.appendChild(slotMap[slotNum], nullptr);
}
return parentNode;
}
ValueTree SvkPreset::getKeyboardNode()
{
return theKeyboardNode;
}
ValueTree SvkPreset::getMidiSettingsNode()
{
return theMidiSettingsNode;
}
ValueTree SvkPreset::getMappingsNode()
{
return theMappingsNode;
}
bool SvkPreset::restoreFromNode(ValueTree presetNodeIn, bool createCopy)
{
if (isValidPresetNode(presetNodeIn))
{
if (createCopy)
presetNodeIn = presetNodeIn.createCopy();
parentNode = presetNodeIn;
parentNode.setProperty(IDs::pluginPresetVersion, SVK_PRESET_VERSION, nullptr);
thePropertiesNode = parentNode.getOrCreateChildWithName(IDs::presetProperties, nullptr);
theModeSlots = parentNode.getOrCreateChildWithName(IDs::modeSlotsNode, nullptr);
theModeSelectors = parentNode.getOrCreateChildWithName(IDs::modeSelectorsNode, nullptr);
theCustomMode = parentNode.getOrCreateChildWithName(IDs::modeCustomNode, nullptr);
theKeyboardNode = parentNode.getOrCreateChildWithName(IDs::pianoNode, nullptr);
theMidiSettingsNode = parentNode.getOrCreateChildWithName(IDs::midiSettingsNode, nullptr);
theMappingsNode = parentNode.getOrCreateChildWithName(IDs::midiMapNode, nullptr);
slotNumbersInUse.clear();
for (int i = 0; i < theModeSlots.getNumChildren(); i++)
{
ValueTree modeNode = theModeSlots.getChild(i);
int slotNum = jlimit(0, MAX_MODE_SLOTS_INDEX, (int)modeNode[IDs::modeSlotNumber]);
slotNumbersInUse.addUsingDefaultSort(slotNum);
}
// Ensure this has at least 2 mode selectors
while (theModeSelectors.getNumChildren() < 2)
{
ValueTree selectorNode(IDs::modeSelectorsNode);
selectorNode.setProperty(IDs::modeSlotNumber, theModeSelectors.getNumChildren(), nullptr);
selectorNode.setProperty(IDs::modeSelectorRootNote, 60, nullptr); // TODO: default midi root note
theModeSelectors.appendChild(selectorNode, nullptr);
}
// Make sure mode selectors have a midi root note
for (auto selector : theModeSelectors)
{
if (!selector.hasProperty(IDs::modeSelectorRootNote))
selector.setProperty(IDs::modeSelectorRootNote, 60, nullptr);
}
return true;
}
return false;
}
Array<int> SvkPreset::getSlotNumbersInUse() const
{
return slotNumbersInUse;
}
int SvkPreset::getModeSelectorViewed() const
{
return thePropertiesNode[IDs::modeSelectorViewed];
}
bool SvkPreset::isSlotNumberInUse(int modeSlotNumberIn) const
{
return slotNumbersInUse.contains(modeSlotNumberIn);
}
int SvkPreset::getModeSlotsSize() const
{
return theModeSlots.getNumChildren();
}
int SvkPreset::getSlotNumberBySelector(int selectorNumIn) const
{
return theModeSelectors.getChild(selectorNumIn)[IDs::modeSlotNumber];
}
int SvkPreset::getMode1SlotNumber() const
{
return getSlotNumberBySelector(0);
}
int SvkPreset::getMode2SlotNumber() const
{
return getSlotNumberBySelector(1);
}
int SvkPreset::getModeViewedSlotNumber() const
{
return getSlotNumberBySelector(getModeSelectorViewed());
}
int SvkPreset::getSlotNumberIndex(int slotNumIn)
{
for (int i = 0; i < theModeSlots.getNumChildren(); i++)
{
if (slotNumIn == (int)(theModeSlots.getChild(i)[IDs::modeSlotNumber]))
return i;
}
return -1;
}
int SvkPreset::getNextFreeSlotNumber()
{
for (int i = 1; i < slotNumbersInUse.size(); i++)
{
if (slotNumbersInUse[i] - slotNumbersInUse[i - 1] > 1)
return slotNumbersInUse[i - 1] + 1;
}
if (slotNumbersInUse.size() < MAX_MODE_SLOTS_INDEX + 1)
return slotNumbersInUse.size();
return -1;
}
int SvkPreset::getModeSelectorRootNote(int modeSelectorNum) const
{
return theModeSelectors.getChild(modeSelectorNum)[IDs::modeSelectorRootNote];
}
ValueTree SvkPreset::getModeSlots()
{
return theModeSlots;
}
ValueTree SvkPreset::getModeInSlot(int slotNum)
{
return theModeSlots.getChild(getSlotNumberIndex(slotNum)).getChild(0);
}
ValueTree SvkPreset::getModeBySelector(int selectorNumIn)
{
return theModeSlots.getChild(getSlotNumberIndex(getSlotNumberBySelector(selectorNumIn))).getChild(0);
}
ValueTree SvkPreset::getMode1()
{
return getModeBySelector(0);
}
ValueTree SvkPreset::getMode2()
{
return getModeBySelector(1);
}
ValueTree SvkPreset::getModeViewed()
{
return getModeBySelector(thePropertiesNode[IDs::modeSelectorViewed]);
}
ValueTree SvkPreset::getCustomMode()
{
return theCustomMode.getChild(0);
}
int SvkPreset::setModeSelectorSlotNum(int selectorNumIn, int slotNumIn)
{
if (selectorNumIn >= 0 && slotNumIn >= 0)
{
ValueTree modeSelectorNode = ValueTree(IDs::modeSelectorsNode);
if (selectorNumIn < theModeSelectors.getNumChildren())
modeSelectorNode = theModeSelectors.getChild(selectorNumIn);
else
theModeSelectors.appendChild(modeSelectorNode, nullptr);
modeSelectorNode.setProperty(IDs::modeSlotNumber, slotNumIn, nullptr);
return slotNumIn;
}
return -1;
}
void SvkPreset::setMode1SlotNumber(int slotNumIn)
{
setModeSelectorSlotNum(0, slotNumIn);
}
void SvkPreset::setMode2SlotNumber(int slotNumIn)
{
setModeSelectorSlotNum(1, slotNumIn);
}
void SvkPreset::setModeSelectorRootNote(int modeSelectorNumIn, int rootNoteIn)
{
ValueTree node = theModeSelectors.getChild(modeSelectorNumIn);
if (node.isValid() && rootNoteIn >= 0 && rootNoteIn < 128)
node.setProperty(IDs::modeSelectorRootNote, rootNoteIn, nullptr);
}
int SvkPreset::setModeSlot(ValueTree modeNodeIn, int slotNumberIn)
{
if (Mode::isValidMode(modeNodeIn) && slotNumberIn >= 0 && slotNumberIn <= MAX_MODE_SLOTS_INDEX)
{
ValueTree slotNode = ValueTree(IDs::modeSlotsNode);
int slotIndex = getSlotNumberIndex(slotNumberIn);
if (slotIndex >= 0)
{
slotNode = theModeSlots.getChild(slotIndex);
slotNode.removeAllChildren(nullptr);
}
else
{
slotIndex = theModeSlots.getNumChildren();
theModeSlots.appendChild(slotNode, nullptr);
}
slotNode.setProperty(IDs::modeSlotNumber, slotNumberIn, nullptr);
slotNode.appendChild(modeNodeIn.createCopy(), nullptr);
if (slotNumbersInUse.indexOf(slotNumberIn) < 0)
slotNumbersInUse.addUsingDefaultSort(slotNumberIn);
return slotIndex;
}
return -1;
}
int SvkPreset::addModeSlot(ValueTree modeNodeIn)
{
int slotIndex = getNextFreeSlotNumber();
return setModeSlot(modeNodeIn, slotIndex);
}
ValueTree SvkPreset::setCustomMode(ValueTree customModeNodeIn, bool createCopy)
{
if (Mode::isValidMode(customModeNodeIn))
{
ValueTree nodeToAdd = customModeNodeIn;
if (createCopy)
nodeToAdd = customModeNodeIn.createCopy();
theCustomMode.removeAllChildren(nullptr);
theCustomMode.appendChild(nodeToAdd, nullptr);
return nodeToAdd;
}
return ValueTree();
}
int SvkPreset::removeModeSlot(int slotNumberIn)
{
int slotIndex = getSlotNumberIndex(slotNumberIn);
if (slotIndex >= 0)
{
theModeSlots.removeChild(slotIndex, nullptr);
slotNumbersInUse.removeFirstMatchingValue(slotNumberIn);
}
return slotIndex;
}
void SvkPreset::resetModeSlots()
{
theModeSelectors.removeAllChildren(nullptr);
slotNumbersInUse.clear();
addModeSlot(STD_TUNING_MODE_NODE);
addModeSlot(STD_TUNING_MODE_NODE);
setMode1SlotNumber(0);
setMode2SlotNumber(1);
}
bool SvkPreset::isValidPresetNode(ValueTree presetNodeIn)
{
bool isValid = presetNodeIn.hasType(IDs::presetNode);
if (isValid)
{
isValid *= presetNodeIn.getChildWithName(IDs::modeSlotsNode).getNumChildren() > 0;
// TODO: more checks?
}
return isValid;
}
SvkPreset SvkPreset::getDefaultPreset()
{
SvkPreset defaultPreset;
ValueTree propertiesNode = defaultPreset.parentNode.getOrCreateChildWithName(IDs::presetProperties, nullptr);
propertiesNode.setProperty(IDs::modeSelectorViewed, 1, nullptr);
defaultPreset.resetModeSlots();
ValueTree pianoNode = defaultPreset.parentNode.getOrCreateChildWithName(IDs::pianoNode, nullptr);
pianoNode.setProperty(IDs::keyboardKeysStyle, 1, nullptr);
pianoNode.setProperty(IDs::pianoKeysShowNoteNumbers, 0, nullptr);
pianoNode.setProperty(IDs::keyboardHighlightStyle, 1, nullptr);
ValueTree mappingMode = defaultPreset.parentNode.getOrCreateChildWithName(IDs::midiMapNode, nullptr);
mappingMode.setProperty(IDs::mappingMode, 1, nullptr);
mappingMode.setProperty(IDs::autoMappingStyle, 1, nullptr);
ValueTree customMode = defaultPreset.parentNode.getOrCreateChildWithName(IDs::modeCustomNode, nullptr);
customMode.appendChild(Mode::createNode("1"), nullptr);
return defaultPreset;
}
String SvkPreset::toString()
{
return parentNode.toXmlString();
}
| {
"repo_name": "vsicurella/SuperVirtualKeyboard",
"stars": "38",
"repo_language": "C++",
"file_name": "MapByOrderDialog.cpp",
"mime_type": "text/x-c"
} |
/*
==============================================================================
MappingHelper.cpp
Created: 21 Aug 2019 4:38:52pm
Author: Vincenzo Sicurella
==============================================================================
*/
#include "MappingHelper.h"
MappingHelper::MappingHelper(NoteMap noteMapIn)
: noteMapping(noteMapIn)
{
virtualKeyToMap = -1;
waitingForKeyInput = false;
allPeriods = false;
}
MappingHelper::~MappingHelper()
{
}
//================================================================
NoteMap MappingHelper::getCurrentNoteMapping() const
{
return noteMapping;
}
void MappingHelper::mapMidiNoteToKey(int midiNoteIn, int keyNumberOut)
{
noteMapping.setValue(midiNoteIn, keyNumberOut);
listeners.call(&Listener::mappingEditorChanged, noteMapping);
}
void MappingHelper::resetMapping(NoteMap mappingIn, bool sendMessage)
{
noteMapping = mappingIn;
if (sendMessage)
listeners.call(&Listener::mappingEditorChanged, noteMapping);
}
//================================================================
bool MappingHelper::isWaitingForKeyInput()
{
return waitingForKeyInput;
}
int MappingHelper::getVirtualKeyToMap()
{
if (waitingForKeyInput)
return virtualKeyToMap;
else
return -1;
}
bool MappingHelper::isMappingAllPeriods()
{
return allPeriods;
}
void MappingHelper::prepareKeyToMap(int virtualKeyClicked, bool allPeriodsIn)
{
virtualKeyToMap = virtualKeyClicked;
allPeriods = allPeriodsIn;
waitingForKeyInput = true;
listeners.call(&Listener::keyMappingStatusChanged, virtualKeyToMap, true);
}
void MappingHelper::mapPreparedKeyToNote(int midiNoteTriggered, bool allPeriods, Mode* modeFrom, Mode* modeTo)
{
if (waitingForKeyInput)
{
if (allPeriods && modeFrom != nullptr && modeTo != nullptr)
{
Array<int> triggeredPeriods = getKeyInAllPeriods(midiNoteTriggered, modeFrom);
Array<int> virtualKeyPeriods = getKeyInAllPeriods(virtualKeyToMap, modeTo);
// TODO
}
else
{
mapMidiNoteToKey(midiNoteTriggered, virtualKeyToMap);
}
DBG("Midi Note " + String(midiNoteTriggered) + " is now mapped to " + String(noteMapping.getValue(midiNoteTriggered)));
waitingForKeyInput = false;
listeners.call(&Listener::keyMapConfirmed, virtualKeyToMap, midiNoteTriggered);
}
}
void MappingHelper::cancelKeyMap()
{
waitingForKeyInput = false;
listeners.call(&Listener::keyMappingStatusChanged, virtualKeyToMap, false);
virtualKeyToMap = -1;
DBG("Key map cancelled.");
}
Array<int> MappingHelper::getKeyInAllPeriods(int keyNumber, Mode* modeToReference)
{
Array<int> keyNumsOut;
int scaleSize = modeToReference->getScaleSize();
int totalNumPeriods = 128 / scaleSize;
int keyPeriod = keyNumber / scaleSize;
int keyNum;
for (int i = 0; i < totalNumPeriods; i++)
{
keyNum = (i - keyPeriod) * scaleSize + keyNumber;
if (keyNum >= 0 && keyNum < 128)
keyNumsOut.add(keyNum);
}
return keyNumsOut;
} | {
"repo_name": "vsicurella/SuperVirtualKeyboard",
"stars": "38",
"repo_language": "C++",
"file_name": "MapByOrderDialog.cpp",
"mime_type": "text/x-c"
} |
/*
==============================================================================
NoteMap.h
Created: 25 May 2019 10:34:43pm
Author: Vincenzo
==============================================================================
*/
#pragma once
#include "../JuceLibraryCode/JuceHeader.h"
#include "../Constants.h"
class NoteMap
{
public:
NoteMap();
NoteMap(int sizeIn, bool useIdentity, int nullValIn = -1);
NoteMap(Array<int> valuesIn, int nullValIn = -1);
NoteMap(ValueTree noteMappingNode);
NoteMap(const NoteMap& mapToCopy);
~NoteMap() {}
ValueTree getAsValueTree(Identifier parentNodeId, bool includeIdentities = false) const;
void setValue(int keyNum, int valIn);
void setValues(Array<int> valuesIn);
int* setNullVal(int nullValIn);
int getSize();
int getKey(int valIn);
int getValue(int keyNum);
const Array<int>& getKeys() const;
const Array<int>& getValues() const;
int getNullVal();
bool operator==(const NoteMap& mapToCompare) const { return values == mapToCompare.values; }
bool operator!=(const NoteMap& mapToCompare) const { return values != mapToCompare.values; }
String toString();
private:
int size;
Array<int> keys; // Midi Note In, Key Number Out
Array<int> values; // Key Number In, Midi Note Out
int nullVal;
};
| {
"repo_name": "vsicurella/SuperVirtualKeyboard",
"stars": "38",
"repo_language": "C++",
"file_name": "MapByOrderDialog.cpp",
"mime_type": "text/x-c"
} |