Serenity Operating System
at master 71 lines 2.6 kB view raw
1/* 2 * Copyright (c) 2021, Cesar Torres <shortanemoia@protonmail.com> 3 * Copyright (c) 2022, the SerenityOS developers. 4 * Copyright (c) 2022, Nícolas F. R. A. Prado <n@nfraprado.net> 5 * 6 * SPDX-License-Identifier: BSD-2-Clause 7 */ 8 9#include "AlbumCoverVisualizationWidget.h" 10#include <AK/LexicalPath.h> 11#include <LibCore/DeprecatedFile.h> 12#include <LibGUI/Painter.h> 13#include <LibGfx/Rect.h> 14 15AlbumCoverVisualizationWidget::AlbumCoverVisualizationWidget(Function<RefPtr<Gfx::Bitmap>()> get_file_cover_from_player) 16 : m_get_file_cover_from_player(move(get_file_cover_from_player)) 17{ 18} 19 20void AlbumCoverVisualizationWidget::paint_event(GUI::PaintEvent& event) 21{ 22 Frame::paint_event(event); 23 GUI::Painter painter(*this); 24 25 auto const& cover = m_file_cover ? m_file_cover : m_album_cover; 26 if (cover) { 27 auto album_cover_rect = cover->rect(); 28 29 auto height_ratio = frame_inner_rect().height() / (float)album_cover_rect.height(); 30 auto width_ratio = frame_inner_rect().width() / (float)album_cover_rect.width(); 31 auto scale = min(height_ratio, width_ratio); 32 33 Gfx::IntRect fitted_rect = { 0, 0, (int)(album_cover_rect.width() * scale), (int)(album_cover_rect.height() * scale) }; 34 fitted_rect.center_within(frame_inner_rect()); 35 36 painter.draw_scaled_bitmap(fitted_rect, *cover, cover->rect(), 1.0f); 37 } else { 38 if (!m_serenity_bg) 39 m_serenity_bg = Gfx::Bitmap::load_from_file("/res/wallpapers/sunset-retro.png"sv).release_value_but_fixme_should_propagate_errors(); 40 painter.draw_scaled_bitmap(frame_inner_rect(), *m_serenity_bg, m_serenity_bg->rect(), 1.0f); 41 } 42} 43 44ErrorOr<NonnullRefPtr<Gfx::Bitmap>> AlbumCoverVisualizationWidget::get_album_cover(StringView const filename) 45{ 46 auto directory = LexicalPath::dirname(filename); 47 48 static constexpr auto possible_cover_filenames = Array { "cover.png"sv, "cover.jpg"sv }; 49 for (auto& it : possible_cover_filenames) { 50 LexicalPath cover_path = LexicalPath::join(directory, it); 51 if (Core::DeprecatedFile::exists(cover_path.string())) 52 return Gfx::Bitmap::load_from_file(cover_path.string()); 53 } 54 55 return Error::from_string_literal("No cover file found"); 56} 57 58void AlbumCoverVisualizationWidget::start_new_file(StringView filename) 59{ 60 if (m_get_file_cover_from_player) 61 m_file_cover = m_get_file_cover_from_player(); 62 63 if (m_file_cover) 64 return; 65 66 auto album_cover_or_error = get_album_cover(filename); 67 if (album_cover_or_error.is_error()) 68 m_album_cover = nullptr; 69 else 70 m_album_cover = album_cover_or_error.value(); 71}