diff --git a/include/utils/math.hpp b/include/utils/math.hpp index b93ea72b..d11dec85 100644 --- a/include/utils/math.hpp +++ b/include/utils/math.hpp @@ -41,6 +41,17 @@ namespace math_util { else return cap(percentage * max_value / 100.0f, 0.0f, max_value); } + + /** + * Get value for percentage of `min_value` to `max_value` + */ + template + ReturnType percentage_to_value(ValueType percentage, ValueType min_value, ValueType max_value) { + if (std::is_integral()) + return cap(percentage * (max_value - min_value) / 100.0f + 0.5f, 0, max_value - min_value) + min_value; + else + return cap(percentage * (max_value - min_value) / 100.0f, 0.0f, max_value - min_value) + min_value; + } } POLYBAR_NS_END diff --git a/src/adapters/alsa.cpp b/src/adapters/alsa.cpp index 222017b2..3c35c888 100644 --- a/src/adapters/alsa.cpp +++ b/src/adapters/alsa.cpp @@ -1,4 +1,5 @@ #include "adapters/alsa.hpp" +#include "utils/math.hpp" POLYBAR_NS @@ -166,7 +167,7 @@ int alsa_mixer::get_volume() { } } - return 100.0f * (vol_total / chan_n) / vol_max + 0.5f; + return math_util::percentage(vol_total / chan_n, vol_min, vol_max); } int alsa_mixer::get_normalized_volume() { @@ -187,7 +188,7 @@ int alsa_mixer::get_normalized_volume() { } if (vol_max - vol_min <= MAX_LINEAR_DB_SCALE * 100) - return 100.0f * (vol_total / chan_n - vol_min) / (vol_max - vol_min) + 0.5f; + return math_util::percentage(vol_total / chan_n, vol_min, vol_max); normalized = pow10((vol_total / chan_n - vol_max) / 6000.0); if (vol_min != SND_CTL_TLV_DB_GAIN_MUTE) { @@ -205,9 +206,8 @@ void alsa_mixer::set_volume(float percentage) { std::lock_guard guard(m_lock); long vol_min, vol_max; - snd_mixer_selem_get_playback_volume_range(m_mixerelement, &vol_min, &vol_max); - snd_mixer_selem_set_playback_volume_all(m_mixerelement, vol_max * percentage / 100); + snd_mixer_selem_set_playback_volume_all(m_mixerelement, math_util::percentage_to_value(percentage, vol_min, vol_max)); } void alsa_mixer::set_normalized_volume(float percentage) { diff --git a/tests/unit_tests/utils/math.cpp b/tests/unit_tests/utils/math.cpp index b9cc575b..c7f12ba3 100644 --- a/tests/unit_tests/utils/math.cpp +++ b/tests/unit_tests/utils/math.cpp @@ -41,4 +41,9 @@ int main() { expect(math_util::percentage_to_value(200, 5) == 5); expect(math_util::percentage_to_value(-30, 5) == 0); }; + + "ranged_percentage_to_value"_test = [] { + expect(math_util::percentage_to_value(50, 200, 300) == 250); + expect(math_util::percentage_to_value(50, 1, 5) == 3); + }; }