SoundPlayer: Accept drop events

Files can now be dragged into the window and loading errors will be
handled more gracefully.
This commit is contained in:
Julian Offenhäuser 2020-12-02 23:58:00 +01:00 committed by Andreas Kling
parent 017490aa7f
commit 228fa1c51d
Notes: sideshowbarker 2024-07-19 01:04:09 +09:00
3 changed files with 20 additions and 3 deletions

View file

@ -26,6 +26,7 @@
#include "SoundPlayerWidget.h"
#include <AK/StringBuilder.h>
#include <LibCore/MimeData.h>
#include <LibGUI/BoxLayout.h>
#include <LibGUI/Button.h>
#include <LibGUI/Label.h>
@ -120,9 +121,10 @@ void SoundPlayerWidget::hide_scope(bool hide)
void SoundPlayerWidget::open_file(String path)
{
NonnullRefPtr<Audio::Loader> loader = Audio::Loader::create(path);
if (loader->has_error()) {
if (loader->has_error() || !loader->sample_rate()) {
const String error_string = loader->error_string();
GUI::MessageBox::show(window(),
String::formatted("Failed to load audio file: {} ({})", path, loader->error_string()),
String::formatted("Failed to load audio file: {} ({})", path, error_string.is_null() ? "Unknown error" : error_string),
"Filetype error", GUI::MessageBox::Type::Error);
return;
}
@ -145,6 +147,19 @@ void SoundPlayerWidget::open_file(String path)
update_position(0);
}
void SoundPlayerWidget::drop_event(GUI::DropEvent& event)
{
event.accept();
window()->move_to_front();
if (event.mime_data().has_urls()) {
auto urls = event.mime_data().urls();
if (urls.is_empty())
return;
open_file(urls.first().path());
}
}
int SoundPlayerWidget::normalize_rate(int rate) const
{
return static_cast<int>(rate * m_sample_ratio);

View file

@ -45,6 +45,8 @@ public:
private:
explicit SoundPlayerWidget(GUI::Window&, NonnullRefPtr<Audio::ClientConnection>);
virtual void drop_event(GUI::DropEvent&) override;
void update_position(const int position);
void update_ui();
int normalize_rate(int) const;

View file

@ -81,7 +81,7 @@ int main(int argc, char** argv)
});
app_menu.add_action(GUI::CommonActions::make_open_action([&](auto&) {
Optional<String> path = GUI::FilePicker::get_open_filepath(window, "Open wav file...");
Optional<String> path = GUI::FilePicker::get_open_filepath(window, "Open sound file...");
if (path.has_value()) {
player.open_file(path.value());
}