| 1 | package App::DrivePlayer::GUI; | ||
| 2 | |||
| 3 | # GTK3-based music player GUI. | ||
| 4 | |||
| 5 | use App::DrivePlayer::Setup; | ||
| 6 | use Glib qw( TRUE FALSE ); | ||
| 7 | use Gtk3 '-init'; | ||
| 8 | use POSIX qw( WNOHANG ); | ||
| 9 | |||
| 10 | use Google::RestApi; | ||
| 11 | use Google::RestApi::DriveApi3; | ||
| 12 | use App::DrivePlayer::Config; | ||
| 13 | use App::DrivePlayer::DB; | ||
| 14 | use App::DrivePlayer::Player; | ||
| 15 | use App::DrivePlayer::Scanner; | ||
| 16 | use App::DrivePlayer::SheetDB; | ||
| 17 | |||
| 18 | Readonly my $POLL_INTERVAL_MS => 500; | ||
| 19 | |||
| 20 | my $log = do { eval { require Log::Log4perl; Log::Log4perl->get_logger(__PACKAGE__) } }; | ||
| 21 | |||
| 22 | has config => ( | ||
| 23 | is => 'lazy', | ||
| 24 | isa => InstanceOf['App::DrivePlayer::Config'], | ||
| 25 | builder => sub { App::DrivePlayer::Config->new() }, | ||
| 26 | ); | ||
| 27 | |||
| 28 | has db => ( | ||
| 29 | is => 'lazy', | ||
| 30 | isa => InstanceOf['App::DrivePlayer::DB'], | ||
| 31 | builder => '_build_db', | ||
| 32 | ); | ||
| 33 | |||
| 34 | has rest_api => ( is => 'rw', default => sub { undef } ); | ||
| 35 | has drive => ( is => 'rw', default => sub { undef } ); | ||
| 36 | has player => ( is => 'rw', default => sub { undef } ); | ||
| 37 | has scanner => ( is => 'rw', default => sub { undef } ); | ||
| 38 | |||
| 39 | has _playlist => ( is => 'rw', isa => ArrayRef, default => sub { [] } ); | ||
| 40 | has _track_by_id => ( is => 'rw', default => sub { {} } ); | ||
| 41 | has _playing_row_ref => ( is => 'rw', default => sub { undef } ); | ||
| 42 | has _playing_track_id => ( is => 'rw', default => sub { undef } ); | ||
| 43 | has _progress_dragging => ( is => 'rw', isa => Bool, default => 0 ); | ||
| 44 | has _settings_open => ( is => 'rw', isa => Bool, default => 0 ); | ||
| 45 | |||
| 46 | # Widget accessors — set during _build_ui | ||
| 47 | has win => ( is => 'rw' ); | ||
| 48 | has sidebar_store => ( is => 'rw' ); | ||
| 49 | has sidebar_view => ( is => 'rw' ); | ||
| 50 | has alpha_view => ( is => 'rw' ); | ||
| 51 | has _alpha_category => ( is => 'rw', default => sub { 'Artists' } ); | ||
| 52 | has _suppress_sidebar_activated => ( is => 'rw', isa => Bool, default => 0 ); | ||
| 53 | has track_store => ( is => 'rw' ); | ||
| 54 | has _track_iter_map => ( is => 'rw', default => sub { {} } ); | ||
| 55 | has track_view => ( is => 'rw' ); | ||
| 56 | has track_count_label => ( is => 'rw' ); | ||
| 57 | has now_playing_label => ( is => 'rw' ); | ||
| 58 | has progress => ( is => 'rw' ); | ||
| 59 | has time_label => ( is => 'rw' ); | ||
| 60 | has dur_label => ( is => 'rw' ); | ||
| 61 | has play_btn => ( is => 'rw' ); | ||
| 62 | has prev_btn => ( is => 'rw' ); | ||
| 63 | has stop_btn => ( is => 'rw' ); | ||
| 64 | has next_btn => ( is => 'rw' ); | ||
| 65 | has vol_scale => ( is => 'rw' ); | ||
| 66 | has search_entry => ( is => 'rw' ); | ||
| 67 | has statusbar => ( is => 'rw' ); | ||
| 68 | has _status_ctx => ( is => 'rw' ); | ||
| 69 | with qw( | ||
| 70 | App::DrivePlayer::GUI::MetadataFetch | ||
| 71 | App::DrivePlayer::GUI::SheetSync | ||
| 72 | App::DrivePlayer::GUI::FolderBrowse | ||
| 73 | ); | ||
| 74 | |||
| 75 | sub _bearer_token { | ||
| 76 | my ($self) = @_; | ||
| 77 | return unless $self->rest_api; | ||
| 78 | my %h = @{ $self->rest_api->auth->headers() }; | ||
| 79 | return $h{Authorization}; | ||
| 80 | } | ||
| 81 | |||
| 82 | sub _build_db { | ||
| 83 | my ($self) = @_; | ||
| 84 | return App::DrivePlayer::DB->new(path => $self->config->db_path()); | ||
| 85 | } | ||
| 86 | |||
| 87 | sub BUILD { | ||
| 88 | my ($self) = @_; | ||
| 89 | $self->_init_logging(); | ||
| 90 | } | ||
| 91 | |||
| 92 | sub run { | ||
| 93 | my ($self) = @_; | ||
| 94 | my $db_is_new = !-f $self->config->db_path(); | ||
| 95 | $self->_build_ui(); | ||
| 96 | $self->_auto_sync_from_sheet_on_new_db() if $db_is_new; | ||
| 97 | $self->_prune_removed_folders(); | ||
| 98 | $self->_load_library(); | ||
| 99 | |||
| 100 | Glib::Timeout->add($POLL_INTERVAL_MS, sub { | ||
| 101 | $self->_player_poll(); | ||
| 102 | return TRUE; | ||
| 103 | }); | ||
| 104 | |||
| 105 | Gtk3->main(); | ||
| 106 | $self->player->quit() if $self->player; | ||
| 107 | } | ||
| 108 | |||
| 109 | # ---- Initialisation ---- | ||
| 110 | |||
| 111 | sub _init_logging { | ||
| 112 | my ($self) = @_; | ||
| 113 | $self->config->ensure_dirs(); | ||
| 114 | my $level = $self->config->log_level(); | ||
| 115 | my $file = $self->config->log_file() // '/tmp/drive_player.log'; | ||
| 116 | |||
| 117 | # Google::RestApi logs ~27 DEBUG lines per cell while reading a worksheet | ||
| 118 | # (tens of thousands of lines for a large sheet), which froze the UI for a | ||
| 119 | # minute during a big sheet sync just writing them to disk. Its category | ||
| 120 | # level is controlled independently via config (restapi_log_level), so the | ||
| 121 | # app can run at DEBUG without the RestApi firehose; default WARN. | ||
| 122 | my $restapi_level = $self->config->restapi_log_level(); | ||
| 123 | |||
| 124 | my $log4perl_conf = " | ||
| 125 | log4perl.rootLogger=$level, Screen, File | ||
| 126 | log4perl.logger.Google.RestApi=$restapi_level | ||
| 127 | log4perl.appender.Screen=Log::Log4perl::Appender::Screen | ||
| 128 | log4perl.appender.Screen.layout=Log::Log4perl::Layout::PatternLayout | ||
| 129 | log4perl.appender.Screen.layout.ConversionPattern=%d [%p] %m%n | ||
| 130 | log4perl.appender.File=Log::Log4perl::Appender::File | ||
| 131 | log4perl.appender.File.filename=$file | ||
| 132 | log4perl.appender.File.utf8=1 | ||
| 133 | log4perl.appender.File.layout=Log::Log4perl::Layout::PatternLayout | ||
| 134 | log4perl.appender.File.layout.ConversionPattern=%d [%p] %m%n | ||
| 135 | "; | ||
| 136 | if (eval { require Log::Log4perl; 1 }) { | ||
| 137 | Log::Log4perl->init(\$log4perl_conf); | ||
| 138 | binmode STDERR, ':encoding(UTF-8)'; | ||
| 139 | } | ||
| 140 | } | ||
| 141 | |||
| 142 | sub _init_api { | ||
| 143 | my ($self) = @_; | ||
| 144 | return $self->rest_api if $self->rest_api; | ||
| 145 | |||
| 146 | my $auth_cfg = $self->config->auth_config(); | ||
| 147 | unless ($auth_cfg->{client_id} && $auth_cfg->{client_secret}) { | ||
| 148 | $self->_show_error( | ||
| 149 | "Google API credentials not configured.\n\n" . | ||
| 150 | "Open File > Settings and enter your OAuth Client ID and Secret.\n\n" . | ||
| 151 | "You can obtain these from the Google Cloud Console under\n" . | ||
| 152 | "APIs & Services > Credentials (OAuth 2.0 Client ID, Desktop app type)." | ||
| 153 | ); | ||
| 154 | return; | ||
| 155 | } | ||
| 156 | unless (-f ($auth_cfg->{token_file} // '')) { | ||
| 157 | $self->_show_error("OAuth token file not found: $auth_cfg->{token_file}\n\n" . | ||
| 158 | "Run the token creator from p5-google-restapi:\n" . | ||
| 159 | " bin/google_restapi_oauth_token_creator"); | ||
| 160 | return; | ||
| 161 | } | ||
| 162 | |||
| 163 | # Pass a shallow copy: Google::RestApi mutates the auth hash it is given | ||
| 164 | # (it deletes 'class' and adds 'config_dir'), which would otherwise strip | ||
| 165 | # the 'class' key from our live config and lose it on the next save(). | ||
| 166 | my $api = eval { Google::RestApi->new(auth => { %$auth_cfg }) }; | ||
| 167 | if ($@) { | ||
| 168 | $self->_show_error("Failed to initialise Google API: $@"); | ||
| 169 | return; | ||
| 170 | } | ||
| 171 | $self->rest_api($api); | ||
| 172 | $self->drive(Google::RestApi::DriveApi3->new(api => $api)); | ||
| 173 | |||
| 174 | $self->player(App::DrivePlayer::Player->new( | ||
| 175 | auth => $api->auth(), | ||
| 176 | on_track_end => sub { $self->_on_track_end() }, | ||
| 177 | on_position => sub { $self->_on_position(@_) }, | ||
| 178 | on_state_change => sub { $self->_on_state_change(@_) }, | ||
| 179 | )); | ||
| 180 | |||
| 181 | return $self->rest_api; | ||
| 182 | } | ||
| 183 | |||
| 184 | sub _reinit_api { | ||
| 185 | my ($self) = @_; | ||
| 186 | if ($self->player) { | ||
| 187 | $self->player->quit(); | ||
| 188 | $self->player(undef); | ||
| 189 | } | ||
| 190 | $self->rest_api(undef); | ||
| 191 | $self->drive(undef); | ||
| 192 | return $self->_init_api(); | ||
| 193 | } | ||
| 194 | |||
| 195 | # ---- UI Construction ---- | ||
| 196 | |||
| 197 | sub _build_ui { | ||
| 198 | my ($self) = @_; | ||
| 199 | |||
| 200 | Gtk3::Window::set_default_icon_name('multimedia-player'); | ||
| 201 | |||
| 202 | $self->win(Gtk3::Window->new('toplevel')); | ||
| 203 | $self->win->set_title('Drive Player'); | ||
| 204 | $self->win->set_default_size(900, 600); | ||
| 205 | $self->win->signal_connect(destroy => sub { $self->_quit() }); | ||
| 206 | |||
| 207 | my $vbox = Gtk3::Box->new('vertical', 0); | ||
| 208 | $self->win->add($vbox); | ||
| 209 | |||
| 210 | # Menu bar | ||
| 211 | $vbox->pack_start($self->_build_menubar(), FALSE, FALSE, 0); | ||
| 212 | |||
| 213 | # Toolbar | ||
| 214 | $vbox->pack_start($self->_build_toolbar(), FALSE, FALSE, 0); | ||
| 215 | |||
| 216 | # Main paned: sidebar | tracklist | ||
| 217 | my $paned = Gtk3::Paned->new('horizontal'); | ||
| 218 | $paned->set_position(220); | ||
| 219 | $vbox->pack_start($paned, TRUE, TRUE, 0); | ||
| 220 | |||
| 221 | $paned->pack1($self->_build_sidebar(), TRUE, TRUE); | ||
| 222 | $paned->pack2($self->_build_tracklist(), TRUE, TRUE); | ||
| 223 | |||
| 224 | # Search bar | ||
| 225 | $vbox->pack_start($self->_build_searchbar(), FALSE, FALSE, 0); | ||
| 226 | |||
| 227 | # Player controls | ||
| 228 | $vbox->pack_start($self->_build_controls(), FALSE, FALSE, 0); | ||
| 229 | |||
| 230 | # Status bar | ||
| 231 | $self->statusbar(Gtk3::Statusbar->new()); | ||
| 232 | $self->_status_ctx($self->statusbar->get_context_id('main')); | ||
| 233 | $vbox->pack_start($self->statusbar, FALSE, FALSE, 0); | ||
| 234 | |||
| 235 | $self->win->show_all(); | ||
| 236 | $self->stop_btn->hide(); # hidden until playback starts | ||
| 237 | } | ||
| 238 | |||
| 239 | sub _build_menubar { | ||
| 240 | my ($self) = @_; | ||
| 241 | my $mb = Gtk3::MenuBar->new(); | ||
| 242 | |||
| 243 | # File menu | ||
| 244 | my $file_menu = Gtk3::Menu->new(); | ||
| 245 | $self->_add_menu_item($file_menu, 'Add Music Folder…', sub { $self->_add_folder_dialog() }); | ||
| 246 | $self->_add_menu_item($file_menu, 'Manage Folders…', sub { $self->_manage_folders_dialog() }); | ||
| 247 | $file_menu->append(Gtk3::SeparatorMenuItem->new()); | ||
| 248 | $self->_add_menu_item($file_menu, 'Settings…', sub { $self->_settings_dialog() }); | ||
| 249 | $file_menu->append(Gtk3::SeparatorMenuItem->new()); | ||
| 250 | $self->_add_menu_item($file_menu, 'Quit', sub { $self->_quit() }); | ||
| 251 | my $file_item = Gtk3::MenuItem->new_with_label('File'); | ||
| 252 | $file_item->set_submenu($file_menu); | ||
| 253 | $mb->append($file_item); | ||
| 254 | |||
| 255 | # Library menu | ||
| 256 | my $lib_menu = Gtk3::Menu->new(); | ||
| 257 | $self->_add_menu_item($lib_menu, 'Sync', sub { $self->_sync_all() }); | ||
| 258 | $self->_add_menu_item($lib_menu, 'Refresh', sub { $self->_load_library() }); | ||
| 259 | $lib_menu->append(Gtk3::SeparatorMenuItem->new()); | ||
| 260 | my $fetch_item = $self->_add_menu_item($lib_menu, 'Fetch All Metadata', sub { $self->_toggle_metadata_fetch() }); | ||
| 261 | $self->_meta_fetch_item($fetch_item); | ||
| 262 | $self->_add_menu_item($lib_menu, 'Retry Incomplete Metadata', sub { $self->_retry_incomplete_metadata() }); | ||
| 263 | $self->_add_menu_item($lib_menu, 'Reset Metadata Fetch', sub { $self->_reset_metadata_fetch() }); | ||
| 264 | $lib_menu->append(Gtk3::SeparatorMenuItem->new()); | ||
| 265 | $self->_add_menu_item($lib_menu, 'Clear Library', sub { $self->_clear_library() }); | ||
| 266 | my $lib_item = Gtk3::MenuItem->new_with_label('Library'); | ||
| 267 | $lib_item->set_submenu($lib_menu); | ||
| 268 | $mb->append($lib_item); | ||
| 269 | |||
| 270 | # Playback menu | ||
| 271 | my $pb_menu = Gtk3::Menu->new(); | ||
| 272 | $self->_add_menu_item($pb_menu, 'Play / Pause', sub { $self->_toggle_play() }); | ||
| 273 | $self->_add_menu_item($pb_menu, 'Stop', sub { $self->_stop() }); | ||
| 274 | $self->_add_menu_item($pb_menu, 'Next Track', sub { $self->_next_track() }); | ||
| 275 | $self->_add_menu_item($pb_menu, 'Previous Track',sub { $self->_prev_track() }); | ||
| 276 | my $pb_item = Gtk3::MenuItem->new_with_label('Playback'); | ||
| 277 | $pb_item->set_submenu($pb_menu); | ||
| 278 | $mb->append($pb_item); | ||
| 279 | |||
| 280 | return $mb; | ||
| 281 | } | ||
| 282 | |||
| 283 | sub _add_menu_item { | ||
| 284 | my ($self, $menu, $label, $cb) = @_; | ||
| 285 | my $item = Gtk3::MenuItem->new_with_label($label); | ||
| 286 | $item->signal_connect(activate => $cb); | ||
| 287 | $menu->append($item); | ||
| 288 | return $item; | ||
| 289 | } | ||
| 290 | |||
| 291 | sub _build_toolbar { | ||
| 292 | my ($self) = @_; | ||
| 293 | my $tb = Gtk3::Toolbar->new(); | ||
| 294 | $tb->set_style('both-horiz'); | ||
| 295 | |||
| 296 | my $scan_btn = Gtk3::ToolButton->new( | ||
| 297 | Gtk3::Image->new_from_icon_name('view-refresh', 'small-toolbar'), | ||
| 298 | 'Sync' | ||
| 299 | ); | ||
| 300 | $scan_btn->signal_connect(clicked => sub { $self->_sync_all() }); | ||
| 301 | $tb->insert($scan_btn, -1); | ||
| 302 | |||
| 303 | my $add_btn = Gtk3::ToolButton->new( | ||
| 304 | Gtk3::Image->new_from_icon_name('folder-new', 'small-toolbar'), | ||
| 305 | 'Add Folder' | ||
| 306 | ); | ||
| 307 | $add_btn->signal_connect(clicked => sub { $self->_add_folder_dialog() }); | ||
| 308 | $tb->insert($add_btn, -1); | ||
| 309 | |||
| 310 | $tb->insert(Gtk3::SeparatorToolItem->new(), -1); | ||
| 311 | |||
| 312 | my $settings_btn = Gtk3::ToolButton->new( | ||
| 313 | Gtk3::Image->new_from_icon_name('preferences-system', 'small-toolbar'), | ||
| 314 | 'Settings' | ||
| 315 | ); | ||
| 316 | $settings_btn->signal_connect(clicked => sub { $self->_settings_dialog() }); | ||
| 317 | $tb->insert($settings_btn, -1); | ||
| 318 | |||
| 319 | return $tb; | ||
| 320 | } | ||
| 321 | |||
| 322 | sub _build_sidebar { | ||
| 323 | my ($self) = @_; | ||
| 324 | my $sw = Gtk3::ScrolledWindow->new(); | ||
| 325 | $sw->set_policy('automatic', 'automatic'); | ||
| 326 | $sw->set_size_request(100, 1); | ||
| 327 | $sw->set_propagate_natural_height(FALSE); | ||
| 328 | |||
| 329 | # TreeStore: label (str), type (str: 'category'|'artist'|'album'|'folder'), | ||
| 330 | # value (str: artist name, album name, folder_id) | ||
| 331 | my $store = Gtk3::TreeStore->new('Glib::String', 'Glib::String', 'Glib::String'); | ||
| 332 | $self->sidebar_store($store); | ||
| 333 | |||
| 334 | my $view = Gtk3::TreeView->new($store); | ||
| 335 | $view->set_headers_visible(FALSE); | ||
| 336 | $view->get_selection()->set_mode('single'); | ||
| 337 | $view->signal_connect('cursor-changed' => sub { $self->_sidebar_activated($view) }); | ||
| 338 | $view->signal_connect('button-press-event' => sub { $self->_sidebar_button_press($view, $_[1]) }); | ||
| 339 | $self->sidebar_view($view); | ||
| 340 | |||
| 341 | $view->set_size_request(100, 1); | ||
| 342 | |||
| 343 | my $renderer = Gtk3::CellRendererText->new(); | ||
| 344 | $renderer->set(ellipsize => 'end'); | ||
| 345 | my $col = Gtk3::TreeViewColumn->new_with_attributes('', $renderer, text => 0); | ||
| 346 | $col->set_sizing('fixed'); | ||
| 347 | $col->set_expand(TRUE); | ||
| 348 | $view->append_column($col); | ||
| 349 | $view->set_fixed_height_mode(TRUE); | ||
| 350 | |||
| 351 | $sw->add($view); | ||
| 352 | |||
| 353 | my $hbox = Gtk3::Box->new('horizontal', 0); | ||
| 354 | $hbox->pack_start($self->_build_alpha_strip(), FALSE, FALSE, 0); | ||
| 355 | $hbox->pack_start($sw, TRUE, TRUE, 0); | ||
| 356 | return $hbox; | ||
| 357 | } | ||
| 358 | |||
| 359 | sub _build_alpha_strip { | ||
| 360 | my ($self) = @_; | ||
| 361 | |||
| 362 | my $css = Gtk3::CssProvider->new(); | ||
| 363 | $css->load_from_data( | ||
| 364 | 'treeview.alpha-nav { font-size: 10px; padding: 0; }' | ||
| 365 | . ' treeview.alpha-nav row { min-height: 0; padding: 1px 0; }' | ||
| 366 | ); | ||
| 367 | |||
| 368 | my $store = Gtk3::ListStore->new('Glib::String'); | ||
| 369 | for my $letter ('#', 'A' .. 'Z') { | ||
| 370 | my $iter = $store->append(); | ||
| 371 | $store->set($iter, 0, $letter); | ||
| 372 | } | ||
| 373 | |||
| 374 | my $view = Gtk3::TreeView->new($store); | ||
| 375 | $view->set_headers_visible(FALSE); | ||
| 376 | $view->set_fixed_height_mode(TRUE); | ||
| 377 | $view->set_can_focus(FALSE); | ||
| 378 | $view->set_activate_on_single_click(TRUE); | ||
| 379 | $view->get_style_context()->add_class('alpha-nav'); | ||
| 380 | $view->get_style_context()->add_provider($css, 600); | ||
| 381 | $self->alpha_view($view); | ||
| 382 | |||
| 383 | my $renderer = Gtk3::CellRendererText->new(); | ||
| 384 | $renderer->set(xalign => 0.5); | ||
| 385 | my $col = Gtk3::TreeViewColumn->new_with_attributes('', $renderer, text => 0); | ||
| 386 | $col->set_sizing('fixed'); | ||
| 387 | $col->set_fixed_width(32); | ||
| 388 | $view->append_column($col); | ||
| 389 | |||
| 390 | $view->signal_connect('row-activated' => sub { | ||
| 391 | my ($tv, $path, $col) = @_; | ||
| 392 | my $iter = $store->get_iter($path) or return; | ||
| 393 | my $letter = $store->get($iter, 0); | ||
| 394 | $self->_sidebar_jump_to_letter($letter); | ||
| 395 | $tv->get_selection()->unselect_all(); | ||
| 396 | }); | ||
| 397 | |||
| 398 | my $sw = Gtk3::ScrolledWindow->new(); | ||
| 399 | $sw->set_policy('never', 'automatic'); | ||
| 400 | $sw->set_size_request(32, 1); | ||
| 401 | $sw->set_propagate_natural_height(FALSE); | ||
| 402 | $sw->add($view); | ||
| 403 | return $sw; | ||
| 404 | } | ||
| 405 | |||
| 406 | sub _sidebar_jump_to_letter { | ||
| 407 | my ($self, $letter) = @_; | ||
| 408 | my $cat_label = $self->_alpha_category or return; | ||
| 409 | my $store = $self->sidebar_store; | ||
| 410 | my $view = $self->sidebar_view; | ||
| 411 | |||
| 412 | my $cat_iter = $store->get_iter_first() or return; | ||
| 413 | my $target; | ||
| 414 | while (1) { | ||
| 415 | if (($store->get($cat_iter, 0) // '') eq $cat_label) { | ||
| 416 | $target = $store->get_path($cat_iter); # snapshot path before iter moves | ||
| 417 | last; | ||
| 418 | } | ||
| 419 | last unless $store->iter_next($cat_iter); | ||
| 420 | } | ||
| 421 | return unless $target; | ||
| 422 | |||
| 423 | my $target_iter = $store->get_iter($target) or return; | ||
| 424 | my $n = $store->iter_n_children($target_iter); | ||
| 425 | for my $i (0 .. $n - 1) { | ||
| 426 | my $child = $store->iter_nth_child($target_iter, $i) or next; | ||
| 427 | my $label = $store->get($child, 0) // ''; | ||
| 428 | my $first = uc(substr($label, 0, 1)); | ||
| 429 | my $matches = $letter eq '#' ? ($first lt 'A' || $first gt 'Z') | ||
| 430 | : $first eq $letter; | ||
| 431 | next unless $matches; | ||
| 432 | my $path = $store->get_path($child); | ||
| 433 | $view->expand_to_path($path); | ||
| 434 | $view->set_cursor($path, undef, FALSE); | ||
| 435 | $view->scroll_to_cell($path, undef, TRUE, 0.0, 0.0); | ||
| 436 | return; | ||
| 437 | } | ||
| 438 | } | ||
| 439 | |||
| 440 | sub _navigate_sidebar_to { | ||
| 441 | my ($self, $kind, $value) = @_; | ||
| 442 | my $cat_label = $kind eq 'artist' ? 'Artists' | ||
| 443 | : $kind eq 'album' ? 'Albums' | ||
| 444 | : $kind eq 'genre' ? 'Genres' | ||
| 445 | : return; | ||
| 446 | my $store = $self->sidebar_store; | ||
| 447 | my $view = $self->sidebar_view; | ||
| 448 | |||
| 449 | # Locate the category header (top-level row whose label matches). | ||
| 450 | my $cat_iter = $store->get_iter_first() or return; | ||
| 451 | my $cat_path; | ||
| 452 | while (1) { | ||
| 453 | if (($store->get($cat_iter, 0) // '') eq $cat_label) { | ||
| 454 | $cat_path = $store->get_path($cat_iter); | ||
| 455 | last; | ||
| 456 | } | ||
| 457 | last unless $store->iter_next($cat_iter); | ||
| 458 | } | ||
| 459 | return unless $cat_path; | ||
| 460 | |||
| 461 | # Match against the raw value stored in column 2, not the display label | ||
| 462 | # in column 0 (which may carry LRM markers from _display_text/_album). | ||
| 463 | my $cat_iter2 = $store->get_iter($cat_path) or return; | ||
| 464 | my $n = $store->iter_n_children($cat_iter2); | ||
| 465 | for my $i (0 .. $n - 1) { | ||
| 466 | my $child = $store->iter_nth_child($cat_iter2, $i) or next; | ||
| 467 | my $stored = $store->get($child, 2); | ||
| 468 | next unless defined $stored && $stored eq $value; | ||
| 469 | my $path = $store->get_path($child); | ||
| 470 | $view->expand_to_path($path); | ||
| 471 | $view->set_cursor($path, undef, FALSE); | ||
| 472 | $view->scroll_to_cell($path, undef, TRUE, 0.5, 0.0); | ||
| 473 | return; | ||
| 474 | } | ||
| 475 | } | ||
| 476 | |||
| 477 | sub _update_alpha_category { | ||
| 478 | my ($self, $label) = @_; | ||
| 479 | my $enabled = defined $label | ||
| 480 | && $label =~ / \A (?: Artists | Albums | Genres ) \z /x; | ||
| 481 | $self->_alpha_category($enabled ? $label : undef); | ||
| 482 | $self->alpha_view->set_sensitive($enabled ? TRUE : FALSE) | ||
| 483 | if $self->alpha_view; | ||
| 484 | } | ||
| 485 | |||
| 486 | sub _build_tracklist { | ||
| 487 | my ($self) = @_; | ||
| 488 | my $vbox = Gtk3::Box->new('vertical', 0); | ||
| 489 | |||
| 490 | my $sw = Gtk3::ScrolledWindow->new(); | ||
| 491 | $sw->set_policy('automatic', 'automatic'); | ||
| 492 | $sw->set_size_request(-1, 1); | ||
| 493 | $sw->set_propagate_natural_height(FALSE); | ||
| 494 | $sw->set_kinetic_scrolling(FALSE); | ||
| 495 | $sw->set_capture_button_press(FALSE); | ||
| 496 | $sw->set_overlay_scrolling(FALSE); | ||
| 497 | $vbox->pack_start($sw, TRUE, TRUE, 0); | ||
| 498 | |||
| 499 | my $count_lbl = Gtk3::Label->new(''); | ||
| 500 | $count_lbl->set_xalign(1.0); | ||
| 501 | $count_lbl->set_margin_end(6); | ||
| 502 | $count_lbl->set_margin_top(2); | ||
| 503 | $count_lbl->set_margin_bottom(2); | ||
| 504 | $self->track_count_label($count_lbl); | ||
| 505 | $vbox->pack_start($count_lbl, FALSE, FALSE, 0); | ||
| 506 | |||
| 507 | # ListStore columns: id, track#, title, artist, album, genre, year, duration_str, drive_id | ||
| 508 | my $store = Gtk3::ListStore->new( | ||
| 509 | 'Glib::Int', # 0 db id | ||
| 510 | 'Glib::String', # 1 track# | ||
| 511 | 'Glib::String', # 2 title | ||
| 512 | 'Glib::String', # 3 artist | ||
| 513 | 'Glib::String', # 4 album | ||
| 514 | 'Glib::String', # 5 genre | ||
| 515 | 'Glib::String', # 6 year | ||
| 516 | 'Glib::String', # 7 duration | ||
| 517 | 'Glib::String', # 8 drive_id | ||
| 518 | ); | ||
| 519 | $self->track_store($store); | ||
| 520 | |||
| 521 | my $view = Gtk3::TreeView->new($store); | ||
| 522 | $view->set_headers_visible(TRUE); | ||
| 523 | $view->set_fixed_height_mode(TRUE); | ||
| 524 | $view->get_selection()->set_mode('multiple'); | ||
| 525 | $view->signal_connect('row-activated' => sub { $self->_track_activated(@_) }); | ||
| 526 | $self->track_view($view); | ||
| 527 | |||
| 528 | my @cols = ( | ||
| 529 | ['#', 1, 40], | ||
| 530 | ['Title', 2, 220], | ||
| 531 | ['Artist', 3, 160], | ||
| 532 | ['Album', 4, 160], | ||
| 533 | ['Genre', 5, 100], | ||
| 534 | ['Year', 6, 60], | ||
| 535 | ['Duration', 7, 65], | ||
| 536 | ); | ||
| 537 | # Map: column-index → sidebar 'kind' for cells that act as navigation | ||
| 538 | # links to the corresponding sidebar category. | ||
| 539 | my %link_kind_by_col_idx = (3 => 'artist', 4 => 'album', 5 => 'genre'); | ||
| 540 | my %link_kind; # TreeViewColumn ref → kind string | ||
| 541 | for my $col_def (@cols) { | ||
| 542 | my ($title, $idx, $width) = @$col_def; | ||
| 543 | my $r = Gtk3::CellRendererText->new(); | ||
| 544 | my $c = Gtk3::TreeViewColumn->new_with_attributes($title, $r, text => $idx); | ||
| 545 | $c->set_resizable(TRUE); | ||
| 546 | $c->set_sort_column_id($idx); | ||
| 547 | $c->set_sizing('fixed'); | ||
| 548 | $c->set_fixed_width($width); | ||
| 549 | $view->append_column($c); | ||
| 550 | $link_kind{$c} = $link_kind_by_col_idx{$idx} | ||
| 551 | if exists $link_kind_by_col_idx{$idx}; | ||
| 552 | } | ||
| 553 | |||
| 554 | # Take full control of left-click so GTK's default handler (which | ||
| 555 | # calls set_cursor and auto-scrolls the clicked row into view) doesn't | ||
| 556 | # shift the viewport between the clicks of a double-click. | ||
| 557 | $view->signal_connect('button-press-event' => sub { | ||
| 558 | my ($w, $event) = @_; | ||
| 559 | |||
| 560 | if ($event->button == 3) { | ||
| 561 | $self->_tracklist_context_menu($event); | ||
| 562 | return TRUE; | ||
| 563 | } | ||
| 564 | |||
| 565 | return FALSE unless $event->button == 1; | ||
| 566 | |||
| 567 | my ($path, $col) = $w->get_path_at_pos($event->x, $event->y); | ||
| 568 | return FALSE unless $path; | ||
| 569 | |||
| 570 | if ($event->type eq '2button-press') { | ||
| 571 | $self->_play_at_path($path, no_scroll => 1); | ||
| 572 | return TRUE; | ||
| 573 | } | ||
| 574 | |||
| 575 | # Single-click on a "link" cell (Artist / Album / Genre) jumps the | ||
| 576 | # sidebar to that group. The sidebar's cursor-changed signal then | ||
| 577 | # repopulates the tracklist, so no further work is needed here. | ||
| 578 | if ($col && (my $kind = $link_kind{$col})) { | ||
| 579 | my $value = $self->_link_value_at($path, $kind); | ||
| 580 | if (defined $value && length $value) { | ||
| 581 | $self->_navigate_sidebar_to($kind, $value); | ||
| 582 | return TRUE; | ||
| 583 | } | ||
| 584 | } | ||
| 585 | |||
| 586 | my $sel = $w->get_selection(); | ||
| 587 | my $state = $event->state; | ||
| 588 | if ($state & 'control-mask') { | ||
| 589 | $sel->path_is_selected($path) | ||
| 590 | ? $sel->unselect_path($path) | ||
| 591 | : $sel->select_path($path); | ||
| 592 | } | ||
| 593 | elsif ($state & 'shift-mask') { | ||
| 594 | # Let GTK handle shift-click range extension. | ||
| 595 | return FALSE; | ||
| 596 | } | ||
| 597 | else { | ||
| 598 | $sel->unselect_all(); | ||
| 599 | $sel->select_path($path); | ||
| 600 | } | ||
| 601 | return TRUE; | ||
| 602 | }); | ||
| 603 | |||
| 604 | # Hover affordance: show the link/hand cursor over Artist and Album | ||
| 605 | # cells that hold a value, so users see those columns are clickable. | ||
| 606 | my $is_link_cursor = 0; | ||
| 607 | my $set_cursor = sub { | ||
| 608 | my ($want_link) = @_; | ||
| 609 | return if $want_link == $is_link_cursor; | ||
| 610 | my $window = $view->get_bin_window() or return; | ||
| 611 | if ($want_link) { | ||
| 612 | my $display = $window->get_display(); | ||
| 613 | my $cursor = Gtk3::Gdk::Cursor->new_for_display($display, 'hand2'); | ||
| 614 | $window->set_cursor($cursor); | ||
| 615 | } else { | ||
| 616 | $window->set_cursor(undef); | ||
| 617 | } | ||
| 618 | $is_link_cursor = $want_link; | ||
| 619 | }; | ||
| 620 | |||
| 621 | $view->signal_connect('motion-notify-event' => sub { | ||
| 622 | my ($w, $event) = @_; | ||
| 623 | my ($path, $col) = $w->get_path_at_pos($event->x, $event->y); | ||
| 624 | my $want_link = 0; | ||
| 625 | if ($path && $col && (my $kind = $link_kind{$col})) { | ||
| 626 | my $value = $self->_link_value_at($path, $kind); | ||
| 627 | $want_link = 1 if defined $value && length $value; | ||
| 628 | } | ||
| 629 | $set_cursor->($want_link); | ||
| 630 | return FALSE; | ||
| 631 | }); | ||
| 632 | |||
| 633 | $view->signal_connect('leave-notify-event' => sub { | ||
| 634 | $set_cursor->(0); | ||
| 635 | return FALSE; | ||
| 636 | }); | ||
| 637 | |||
| 638 | $sw->add($view); | ||
| 639 | return $vbox; | ||
| 640 | } | ||
| 641 | |||
| 642 | sub _build_searchbar { | ||
| 643 | my ($self) = @_; | ||
| 644 | my $hbox = Gtk3::Box->new('horizontal', 4); | ||
| 645 | $hbox->set_border_width(2); | ||
| 646 | |||
| 647 | my $label = Gtk3::Label->new('Search:'); | ||
| 648 | $hbox->pack_start($label, FALSE, FALSE, 4); | ||
| 649 | |||
| 650 | my $entry = Gtk3::SearchEntry->new(); | ||
| 651 | $entry->set_placeholder_text('Artist, album or title…'); | ||
| 652 | $entry->signal_connect('search-changed' => sub { $self->_on_search($entry->get_text()) }); | ||
| 653 | $self->search_entry($entry); | ||
| 654 | $hbox->pack_start($entry, TRUE, TRUE, 0); | ||
| 655 | |||
| 656 | my $clear = Gtk3::Button->new_with_label('Clear'); | ||
| 657 | $clear->signal_connect(clicked => sub { | ||
| 658 | $entry->set_text(''); | ||
| 659 | $self->_load_library(); | ||
| 660 | }); | ||
| 661 | $hbox->pack_start($clear, FALSE, FALSE, 0); | ||
| 662 | |||
| 663 | return $hbox; | ||
| 664 | } | ||
| 665 | |||
| 666 | sub _build_controls { | ||
| 667 | my ($self) = @_; | ||
| 668 | my $frame = Gtk3::Frame->new(); | ||
| 669 | my $vbox = Gtk3::Box->new('vertical', 2); | ||
| 670 | $vbox->set_border_width(4); | ||
| 671 | $frame->add($vbox); | ||
| 672 | |||
| 673 | # Now-playing label | ||
| 674 | $self->now_playing_label(Gtk3::Label->new('Not playing')); | ||
| 675 | $self->now_playing_label->set_ellipsize('end'); | ||
| 676 | $self->now_playing_label->set_xalign(0.0); | ||
| 677 | $vbox->pack_start($self->now_playing_label, FALSE, FALSE, 0); | ||
| 678 | |||
| 679 | # Progress bar + time labels | ||
| 680 | my $prog_hbox = Gtk3::Box->new('horizontal', 4); | ||
| 681 | $self->time_label(Gtk3::Label->new('0:00')); | ||
| 682 | $self->time_label->set_size_request(40, -1); | ||
| 683 | $prog_hbox->pack_start($self->time_label, FALSE, FALSE, 0); | ||
| 684 | |||
| 685 | $self->progress(Gtk3::Scale->new_with_range('horizontal', 0, 100, 1)); | ||
| 686 | $self->progress->set_draw_value(FALSE); | ||
| 687 | $self->progress->set_range(0, 1); | ||
| 688 | $self->progress->signal_connect('button-press-event' => sub { | ||
| 689 | $self->_progress_dragging(1); return FALSE; | ||
| 690 | }); | ||
| 691 | $self->progress->signal_connect('button-release-event' => sub { | ||
| 692 | $self->_progress_dragging(0); | ||
| 693 | $self->player->seek($self->progress->get_value()) if $self->player; | ||
| 694 | return FALSE; | ||
| 695 | }); | ||
| 696 | $prog_hbox->pack_start($self->progress, TRUE, TRUE, 0); | ||
| 697 | |||
| 698 | $self->dur_label(Gtk3::Label->new('0:00')); | ||
| 699 | $self->dur_label->set_size_request(40, -1); | ||
| 700 | $prog_hbox->pack_start($self->dur_label, FALSE, FALSE, 0); | ||
| 701 | $vbox->pack_start($prog_hbox, FALSE, FALSE, 0); | ||
| 702 | |||
| 703 | # Buttons + volume | ||
| 704 | my $btn_hbox = Gtk3::Box->new('horizontal', 4); | ||
| 705 | $vbox->pack_start($btn_hbox, FALSE, FALSE, 0); | ||
| 706 | |||
| 707 | $self->prev_btn($self->_icon_button('media-skip-backward', sub { $self->_prev_track() })); | ||
| 708 | $self->play_btn($self->_icon_button('media-playback-start', sub { $self->_toggle_play() })); | ||
| 709 | $self->stop_btn($self->_icon_button('media-playback-stop', sub { $self->_stop() })); | ||
| 710 | $self->next_btn($self->_icon_button('media-skip-forward', sub { $self->_next_track() })); | ||
| 711 | |||
| 712 | $btn_hbox->pack_start($self->prev_btn, FALSE, FALSE, 0); | ||
| 713 | $btn_hbox->pack_start($self->play_btn, FALSE, FALSE, 0); | ||
| 714 | $btn_hbox->pack_start($self->stop_btn, FALSE, FALSE, 0); | ||
| 715 | $btn_hbox->pack_start($self->next_btn, FALSE, FALSE, 0); | ||
| 716 | |||
| 717 | $btn_hbox->pack_start(Gtk3::Label->new(' Vol:'), FALSE, FALSE, 8); | ||
| 718 | $self->vol_scale(Gtk3::Scale->new_with_range('horizontal', 0, 100, 1)); | ||
| 719 | $self->vol_scale->set_value(80); | ||
| 720 | $self->vol_scale->set_size_request(100, -1); | ||
| 721 | $self->vol_scale->set_draw_value(FALSE); | ||
| 722 | $self->vol_scale->signal_connect('value-changed' => sub { | ||
| 723 | $self->player->set_volume($self->vol_scale->get_value()) if $self->player; | ||
| 724 | }); | ||
| 725 | $btn_hbox->pack_start($self->vol_scale, FALSE, FALSE, 0); | ||
| 726 | |||
| 727 | return $frame; | ||
| 728 | } | ||
| 729 | |||
| 730 | sub _icon_button { | ||
| 731 | my ($self, $icon_name, $cb) = @_; | ||
| 732 | my $btn = Gtk3::Button->new(); | ||
| 733 | $btn->set_image(Gtk3::Image->new_from_icon_name($icon_name, 'button')); | ||
| 734 | $btn->signal_connect(clicked => $cb); | ||
| 735 | return $btn; | ||
| 736 | } | ||
| 737 | |||
| 738 | # ---- Library loading ---- | ||
| 739 | |||
| 740 | sub _load_library { | ||
| 741 | my ($self) = @_; | ||
| 742 | $self->_populate_sidebar(); | ||
| 743 | $self->_populate_tracklist($self->db->all_tracks()); | ||
| 744 | my $count = $self->db->track_count(); | ||
| 745 | $self->_set_status("$count tracks in library"); | ||
| 746 | } | ||
| 747 | |||
| 748 | # Rebuild the sidebar tree (so renamed/added/dropped artists, albums, and | ||
| 749 | # genres are reflected) without losing the user's current selection or | ||
| 750 | # kicking off a tracklist reload. Used after a metadata edit when an | ||
| 751 | # artist/album/genre changed. | ||
| 752 | sub _refresh_sidebar_keep_selection { | ||
| 753 | my ($self) = @_; | ||
| 754 | my $store = $self->sidebar_store; | ||
| 755 | my $view = $self->sidebar_view; | ||
| 756 | |||
| 757 | my $sel; | ||
| 758 | if (my ($path) = $view->get_cursor()) { | ||
| 759 | if (my $iter = $store->get_iter($path)) { | ||
| 760 | $sel = { | ||
| 761 | type => $store->get($iter, 1), | ||
| 762 | value => $store->get($iter, 2), | ||
| 763 | }; | ||
| 764 | } | ||
| 765 | } | ||
| 766 | |||
| 767 | $self->_suppress_sidebar_activated(1); | ||
| 768 | $self->_populate_sidebar(); | ||
| 769 | |||
| 770 | if ($sel) { | ||
| 771 | my $cat = $store->get_iter_first; | ||
| 772 | TOP: while ($cat) { | ||
| 773 | my $check = sub { | ||
| 774 | my $iter = shift; | ||
| 775 | return ($store->get($iter, 1) // '') eq ($sel->{type} // '') | ||
| 776 | && ($store->get($iter, 2) // '') eq ($sel->{value} // ''); | ||
| 777 | }; | ||
| 778 | if ($check->($cat)) { | ||
| 779 | $view->set_cursor($store->get_path($cat), undef, FALSE); | ||
| 780 | last TOP; | ||
| 781 | } | ||
| 782 | my $n = $store->iter_n_children($cat); | ||
| 783 | for my $i (0 .. $n - 1) { | ||
| 784 | my $child = $store->iter_nth_child($cat, $i) or next; | ||
| 785 | next unless $check->($child); | ||
| 786 | my $cp = $store->get_path($child); | ||
| 787 | $view->expand_to_path($cp); | ||
| 788 | $view->set_cursor($cp, undef, FALSE); | ||
| 789 | last TOP; | ||
| 790 | } | ||
| 791 | last unless $store->iter_next($cat); | ||
| 792 | } | ||
| 793 | } | ||
| 794 | $self->_suppress_sidebar_activated(0); | ||
| 795 | } | ||
| 796 | |||
| 797 | sub _populate_sidebar { | ||
| 798 | my ($self) = @_; | ||
| 799 | my $store = $self->sidebar_store; | ||
| 800 | $store->clear(); | ||
| 801 | |||
| 802 | # All Tracks | ||
| 803 | my $all_iter = $store->append(undef); | ||
| 804 | $store->set($all_iter, 0, 'All Tracks', 1, 'all', 2, ''); | ||
| 805 | |||
| 806 | # Build display-sorted [display, raw] pairs so the sidebar's visible | ||
| 807 | # order matches what the user actually reads. Raw values (e.g. | ||
| 808 | # "2025-The Best of ZZ Top") differ from display ("The Best of ZZ | ||
| 809 | # Top") whenever _display_album/text strips a prefix or rewrites | ||
| 810 | # underscores, and sorting on the raw form scatters those entries | ||
| 811 | # into the wrong alphabetical slot. | ||
| 812 | my $by_display = sub { | ||
| 813 | my ($display_fn, @raw) = @_; | ||
| 814 | return map { $_->[1] } | ||
| 815 | sort { lc($a->[0]) cmp lc($b->[0]) } | ||
| 816 | map { [ $display_fn->($_), $_ ] } | ||
| 817 | @raw; | ||
| 818 | }; | ||
| 819 | |||
| 820 | # Artists | ||
| 821 | my $art_iter = $store->append(undef); | ||
| 822 | $store->set($art_iter, 0, 'Artists', 1, 'category', 2, ''); | ||
| 823 | for my $artist ($by_display->(\&_display_text, $self->db->all_artists())) { | ||
| 824 | my $iter = $store->append($art_iter); | ||
| 825 | $store->set($iter, 0, _display_text($artist), 1, 'artist', 2, $artist); | ||
| 826 | } | ||
| 827 | |||
| 828 | # Albums | ||
| 829 | my $alb_iter = $store->append(undef); | ||
| 830 | $store->set($alb_iter, 0, 'Albums', 1, 'category', 2, ''); | ||
| 831 | for my $album ($by_display->(\&_display_album, $self->db->all_albums())) { | ||
| 832 | my $iter = $store->append($alb_iter); | ||
| 833 | $store->set($iter, 0, _display_album($album), 1, 'album', 2, $album); | ||
| 834 | } | ||
| 835 | |||
| 836 | # Genres | ||
| 837 | my $gen_iter = $store->append(undef); | ||
| 838 | $store->set($gen_iter, 0, 'Genres', 1, 'category', 2, ''); | ||
| 839 | for my $genre ($by_display->(sub { $_[0] }, $self->db->all_genres())) { | ||
| 840 | my $iter = $store->append($gen_iter); | ||
| 841 | $store->set($iter, 0, $genre, 1, 'genre', 2, $genre); | ||
| 842 | } | ||
| 843 | |||
| 844 | # Folders | ||
| 845 | my $fld_iter = $store->append(undef); | ||
| 846 | $store->set($fld_iter, 0, 'Folders', 1, 'category', 2, ''); | ||
| 847 | for my $sf ($self->db->all_scan_folders()) { | ||
| 848 | my $iter = $store->append($fld_iter); | ||
| 849 | $store->set($iter, 0, $sf->{name}, 1, 'folder', 2, $sf->{drive_id}); | ||
| 850 | } | ||
| 851 | |||
| 852 | $self->sidebar_view->expand_all(); | ||
| 853 | } | ||
| 854 | |||
| 855 | # Positional (col-index, value) pairs for the display columns of a track row | ||
| 856 | # (columns 1-7: track#, title, artist, album, genre, year, duration). | ||
| 857 | # Columns 0 (id) and 8 (drive_id) are set separately where needed. | ||
| 858 | sub _track_row_cols { | ||
| 859 | my ($t) = @_; | ||
| 860 | return ( | ||
| 861 | 1, _track_num_str($t->{track_number}), | ||
| 862 | 2, _display_title($t->{title}) || '(Unknown)', | ||
| 863 | 3, _display_text($t->{artist}), | ||
| 864 | 4, _display_album($t->{album}), | ||
| 865 | 5, $t->{genre} // '', | ||
| 866 | 6, $t->{year} // '', | ||
| 867 | 7, _dur_str($t->{duration_ms}), | ||
| 868 | ); | ||
| 869 | } | ||
| 870 | |||
| 871 | sub _populate_tracklist { | ||
| 872 | my ($self, @tracks) = @_; | ||
| 873 | my $store = $self->track_store; | ||
| 874 | $store->clear(); | ||
| 875 | $self->_track_iter_map({}); | ||
| 876 | $self->_track_by_id({}); | ||
| 877 | $self->_playlist(\@tracks); | ||
| 878 | $self->_playing_row_ref(undef); | ||
| 879 | $self->_playing_track_id(undef); | ||
| 880 | |||
| 881 | for my $t (@tracks) { | ||
| 882 | my $iter = $store->append(); | ||
| 883 | $store->set($iter, | ||
| 884 | 0, $t->{id} // 0, | ||
| 885 | _track_row_cols($t), | ||
| 886 | 8, $t->{drive_id} // '', | ||
| 887 | ); | ||
| 888 | if ($t->{id}) { | ||
| 889 | $self->_track_iter_map->{$t->{id}} = $iter; | ||
| 890 | $self->_track_by_id->{$t->{id}} = $t; | ||
| 891 | } | ||
| 892 | } | ||
| 893 | |||
| 894 | my $n = scalar @tracks; | ||
| 895 | $self->track_count_label->set_text($n == 1 ? '1 track' : "$n tracks"); | ||
| 896 | } | ||
| 897 | |||
| 898 | sub _refresh_track_row { | ||
| 899 | my ($self, $track_id) = @_; | ||
| 900 | my $iter = $self->_track_iter_map->{$track_id} or return; | ||
| 901 | my $t = $self->db->get_track($track_id) or return; | ||
| 902 | $self->track_store->set($iter, _track_row_cols($t)); | ||
| 903 | # Keep the cached hashref in sync so subsequent edits start from the | ||
| 904 | # new values rather than the stale pre-edit snapshot. | ||
| 905 | $self->_track_by_id->{$track_id} = $t; | ||
| 906 | } | ||
| 907 | |||
| 908 | # ---- Playback ---- | ||
| 909 | |||
| 910 | sub _track_activated { | ||
| 911 | my ($self, $view, $path, $col) = @_; | ||
| 912 | $self->_play_at_path($path, no_scroll => 1); | ||
| 913 | } | ||
| 914 | |||
| 915 | sub _track_at_path { | ||
| 916 | my ($self, $path) = @_; | ||
| 917 | my $iter = $self->track_store->get_iter($path) or return; | ||
| 918 | my $id = $self->track_store->get($iter, 0); | ||
| 919 | return $self->_track_by_id->{$id}; | ||
| 920 | } | ||
| 921 | |||
| 922 | # Process pending GTK events so the UI stays responsive during a long, | ||
| 923 | # synchronous operation (progress bars, status updates, incremental scans). | ||
| 924 | sub _pump_events { | ||
| 925 | Gtk3::main_iteration_do(FALSE) while Gtk3::events_pending(); | ||
| 926 | } | ||
| 927 | |||
| 928 | # Value of the given "link" field ($kind: artist/album/genre) for the track | ||
| 929 | # at $path, or undef. Shared by the click-to-navigate and hover-cursor handlers. | ||
| 930 | sub _link_value_at { | ||
| 931 | my ($self, $path, $kind) = @_; | ||
| 932 | my $iter = $self->track_store->get_iter($path); | ||
| 933 | my $id = $iter ? $self->track_store->get($iter, 0) : undef; | ||
| 934 | my $track = $id ? $self->_track_by_id->{$id} : undef; | ||
| 935 | return $track ? $track->{$kind} : undef; | ||
| 936 | } | ||
| 937 | |||
| 938 | sub _current_path { | ||
| 939 | my ($self) = @_; | ||
| 940 | my $ref = $self->_playing_row_ref or return; | ||
| 941 | return unless $ref->valid(); | ||
| 942 | return $ref->get_path(); | ||
| 943 | } | ||
| 944 | |||
| 945 | sub _play_at_path { | ||
| 946 | my ($self, $path, %opts) = @_; | ||
| 947 | my $track = $self->_track_at_path($path) or return; | ||
| 948 | return unless $self->_init_api(); | ||
| 949 | |||
| 950 | eval { $self->player->play($track) }; | ||
| 951 | if ($@) { | ||
| 952 | $self->_show_error("Playback error: $@"); | ||
| 953 | return; | ||
| 954 | } | ||
| 955 | |||
| 956 | $self->_playing_track_id($track->{id}); | ||
| 957 | $self->_playing_row_ref(Gtk3::TreeRowReference->new($self->track_store, $path)); | ||
| 958 | $self->_update_now_playing($track); | ||
| 959 | $self->_highlight_path($path) unless $opts{no_scroll}; | ||
| 960 | } | ||
| 961 | |||
| 962 | sub _toggle_play { | ||
| 963 | my ($self) = @_; | ||
| 964 | if (!$self->player || $self->player->state eq 'stop') { | ||
| 965 | my $sel = $self->track_view->get_selection(); | ||
| 966 | my (undef, @paths) = $sel->get_selected_rows(); | ||
| 967 | my $path = @paths ? $paths[0] : Gtk3::TreePath->new_from_indices(0); | ||
| 968 | $self->_play_at_path($path); | ||
| 969 | } else { | ||
| 970 | return unless $self->_init_api(); | ||
| 971 | $self->player->pause_resume(); | ||
| 972 | } | ||
| 973 | } | ||
| 974 | |||
| 975 | sub _stop { | ||
| 976 | my ($self) = @_; | ||
| 977 | return unless $self->player; | ||
| 978 | $self->player->stop(); | ||
| 979 | $self->progress->set_value(0); | ||
| 980 | $self->time_label->set_text('0:00'); | ||
| 981 | $self->now_playing_label->set_text('Not playing'); | ||
| 982 | } | ||
| 983 | |||
| 984 | sub _next_track { | ||
| 985 | my ($self) = @_; | ||
| 986 | my $path = $self->_current_path(); | ||
| 987 | if ($path) { | ||
| 988 | my $iter = $self->track_store->get_iter($path); | ||
| 989 | return unless $iter && $self->track_store->iter_next($iter); | ||
| 990 | $self->_play_at_path($self->track_store->get_path($iter)); | ||
| 991 | } else { | ||
| 992 | $self->_play_at_path(Gtk3::TreePath->new_from_indices(0)) | ||
| 993 | if @{ $self->_playlist }; | ||
| 994 | } | ||
| 995 | } | ||
| 996 | |||
| 997 | sub _prev_track { | ||
| 998 | my ($self) = @_; | ||
| 999 | my $path = $self->_current_path() or return; | ||
| 1000 | return unless $path->prev(); | ||
| 1001 | $self->_play_at_path($path); | ||
| 1002 | } | ||
| 1003 | |||
| 1004 | # ---- Player callbacks ---- | ||
| 1005 | |||
| 1006 | sub _on_track_end { | ||
| 1007 | my ($self) = @_; | ||
| 1008 | $self->_next_track(); | ||
| 1009 | } | ||
| 1010 | |||
| 1011 | sub _on_position { | ||
| 1012 | my ($self, $pos, $dur) = @_; | ||
| 1013 | return if $self->_progress_dragging; | ||
| 1014 | $self->progress->set_range(0, $dur) if $dur; | ||
| 1015 | $self->progress->set_value($pos) if defined $pos; | ||
| 1016 | $self->time_label->set_text(_sec_str($pos)); | ||
| 1017 | $self->dur_label->set_text(_sec_str($dur)); | ||
| 1018 | |||
| 1019 | # Persist duration when mpv reports it for a track that doesn't have one yet. | ||
| 1020 | if ($dur && $dur > 0) { | ||
| 1021 | my $id = $self->_playing_track_id; | ||
| 1022 | my $track = $id ? $self->_track_by_id->{$id} : undef; | ||
| 1023 | if ($track && !$track->{duration_ms}) { | ||
| 1024 | my $ms = int($dur * 1000); | ||
| 1025 | $track->{duration_ms} = $ms; # mutate to prevent firing again | ||
| 1026 | $self->db->update_track_metadata($track->{id}, duration_ms => $ms); | ||
| 1027 | $self->_refresh_track_row($track->{id}); | ||
| 1028 | } | ||
| 1029 | } | ||
| 1030 | } | ||
| 1031 | |||
| 1032 | sub _on_state_change { | ||
| 1033 | my ($self, $state) = @_; | ||
| 1034 | my $icon = $state eq 'play' ? 'media-playback-pause' : 'media-playback-start'; | ||
| 1035 | $self->play_btn->set_image(Gtk3::Image->new_from_icon_name($icon, 'button')); | ||
| 1036 | if ($state eq 'stop') { | ||
| 1037 | $self->stop_btn->hide(); | ||
| 1038 | } else { | ||
| 1039 | $self->stop_btn->show(); | ||
| 1040 | } | ||
| 1041 | } | ||
| 1042 | |||
| 1043 | sub _player_poll { | ||
| 1044 | my ($self) = @_; | ||
| 1045 | if ($self->player) { | ||
| 1046 | eval { $self->player->poll() }; | ||
| 1047 | $log->warn("Player poll error: $@") if $@ && $log; | ||
| 1048 | } | ||
| 1049 | } | ||
| 1050 | |||
| 1051 | # ---- Sidebar activation ---- | ||
| 1052 | |||
| 1053 | sub _sidebar_activated { | ||
| 1054 | my ($self, $view) = @_; | ||
| 1055 | return if $self->_suppress_sidebar_activated; | ||
| 1056 | my ($path) = $view->get_cursor(); | ||
| 1057 | return unless $path; | ||
| 1058 | my $store = $self->sidebar_store; | ||
| 1059 | my $iter = $store->get_iter($path); | ||
| 1060 | my $type = $store->get($iter, 1); | ||
| 1061 | my $value = $store->get($iter, 2); | ||
| 1062 | my $label = $store->get($iter, 0); | ||
| 1063 | |||
| 1064 | # Resolve the alpha-nav category for the current selection. Leaf rows look | ||
| 1065 | # up their parent category's label; category headers use their own label. | ||
| 1066 | my $cat_label; | ||
| 1067 | if ($type eq 'category') { | ||
| 1068 | $cat_label = $label; | ||
| 1069 | } elsif ($type =~ / \A (?: artist | album | genre ) \z /x) { | ||
| 1070 | my $parent = $store->iter_parent($iter); | ||
| 1071 | $cat_label = $parent ? $store->get($parent, 0) : undef; | ||
| 1072 | } | ||
| 1073 | $self->_update_alpha_category($cat_label); | ||
| 1074 | |||
| 1075 | if ($type eq 'all') { | ||
| 1076 | $self->_populate_tracklist($self->db->all_tracks()); | ||
| 1077 | } elsif ($type eq 'artist') { | ||
| 1078 | $self->_populate_tracklist($self->db->tracks_by_artist($value)); | ||
| 1079 | } elsif ($type eq 'album') { | ||
| 1080 | $self->_populate_tracklist($self->db->tracks_by_album($value)); | ||
| 1081 | } elsif ($type eq 'genre') { | ||
| 1082 | $self->_populate_tracklist($self->db->tracks_by_genre($value)); | ||
| 1083 | } elsif ($type eq 'folder') { | ||
| 1084 | my $sf = $self->db->get_scan_folder_by_drive_id($value) or return; | ||
| 1085 | $self->_populate_tracklist($self->db->tracks_by_scan_folder($sf->{id})); | ||
| 1086 | } else { | ||
| 1087 | return; # category header selected — no tracklist change | ||
| 1088 | } | ||
| 1089 | |||
| 1090 | $self->_set_status(scalar(@{ $self->_playlist }) . ' tracks'); | ||
| 1091 | } | ||
| 1092 | |||
| 1093 | sub _sidebar_button_press { | ||
| 1094 | my ($self, $view, $event) = @_; | ||
| 1095 | return FALSE unless $event->button == 3; | ||
| 1096 | |||
| 1097 | my ($path) = $view->get_path_at_pos($event->x, $event->y); | ||
| 1098 | return FALSE unless $path; | ||
| 1099 | |||
| 1100 | my $store = $self->sidebar_store; | ||
| 1101 | my $iter = $store->get_iter($path); | ||
| 1102 | my $type = $store->get($iter, 1); | ||
| 1103 | return FALSE unless $type eq 'folder'; | ||
| 1104 | |||
| 1105 | my $drive_id = $store->get($iter, 2); | ||
| 1106 | my $sf = $self->db->get_scan_folder_by_drive_id($drive_id) or return FALSE; | ||
| 1107 | |||
| 1108 | my $menu = Gtk3::Menu->new(); | ||
| 1109 | $self->_add_menu_item($menu, 'Fetch Metadata for This Folder', sub { | ||
| 1110 | $self->_stop_metadata_fetch() if $self->_meta_watch_id; | ||
| 1111 | $self->_fetch_all_metadata($sf->{id}); | ||
| 1112 | }); | ||
| 1113 | $menu->show_all(); | ||
| 1114 | $menu->popup_at_pointer($event); | ||
| 1115 | return TRUE; | ||
| 1116 | } | ||
| 1117 | |||
| 1118 | # ---- Search ---- | ||
| 1119 | |||
| 1120 | sub _on_search { | ||
| 1121 | my ($self, $query) = @_; | ||
| 1122 | if (length $query >= 2) { | ||
| 1123 | $self->_populate_tracklist($self->db->search_tracks($query)); | ||
| 1124 | } elsif (length $query == 0) { | ||
| 1125 | $self->_populate_tracklist($self->db->all_tracks()); | ||
| 1126 | } | ||
| 1127 | } | ||
| 1128 | |||
| 1129 | # ---- Scanning ---- | ||
| 1130 | |||
| 1131 | sub _sync_all { | ||
| 1132 | my ($self) = @_; | ||
| 1133 | return unless $self->_init_api(); | ||
| 1134 | |||
| 1135 | my @folders = @{ $self->config->music_folders() }; | ||
| 1136 | unless (@folders) { | ||
| 1137 | $self->_show_error("No music folders configured.\nUse File → Add Music Folder."); | ||
| 1138 | return; | ||
| 1139 | } | ||
| 1140 | |||
| 1141 | $self->_show_sync_dialog(\@folders); | ||
| 1142 | } | ||
| 1143 | |||
| 1144 | sub _show_sync_dialog { | ||
| 1145 | my ($self, $folders) = @_; | ||
| 1146 | |||
| 1147 | my $dlg = Gtk3::Dialog->new_with_buttons( | ||
| 1148 | 'Syncing Library', $self->win, | ||
| 1149 | [qw/ modal destroy-with-parent /], | ||
| 1150 | 'Stop', 'cancel', | ||
| 1151 | ); | ||
| 1152 | $dlg->set_default_size(400, 160); | ||
| 1153 | |||
| 1154 | my $content = $dlg->get_content_area(); | ||
| 1155 | my $vbox = Gtk3::Box->new('vertical', 8); | ||
| 1156 | $vbox->set_border_width(12); | ||
| 1157 | $content->pack_start($vbox, TRUE, TRUE, 0); | ||
| 1158 | |||
| 1159 | my $status_lbl = Gtk3::Label->new('Preparing…'); | ||
| 1160 | $status_lbl->set_xalign(0.0); | ||
| 1161 | $status_lbl->set_ellipsize('middle'); | ||
| 1162 | $vbox->pack_start($status_lbl, FALSE, FALSE, 0); | ||
| 1163 | |||
| 1164 | my $progress = Gtk3::ProgressBar->new(); | ||
| 1165 | $progress->set_pulse_step(0.05); | ||
| 1166 | $vbox->pack_start($progress, FALSE, FALSE, 0); | ||
| 1167 | |||
| 1168 | my $count_lbl = Gtk3::Label->new('0 tracks found'); | ||
| 1169 | $count_lbl->set_xalign(0.0); | ||
| 1170 | $vbox->pack_start($count_lbl, FALSE, FALSE, 0); | ||
| 1171 | |||
| 1172 | $dlg->show_all(); | ||
| 1173 | |||
| 1174 | my $track_count = 0; | ||
| 1175 | my $total_removed = 0; | ||
| 1176 | my $total = scalar @$folders; | ||
| 1177 | my $current = 0; | ||
| 1178 | my $stopped = FALSE; | ||
| 1179 | |||
| 1180 | my $scanner = App::DrivePlayer::Scanner->new( | ||
| 1181 | drive => $self->drive, | ||
| 1182 | db => $self->db, | ||
| 1183 | on_progress => sub { | ||
| 1184 | my ($msg) = @_; | ||
| 1185 | $status_lbl->set_text($msg); | ||
| 1186 | $progress->pulse(); | ||
| 1187 | $self->_pump_events(); | ||
| 1188 | }, | ||
| 1189 | on_track_found => sub { | ||
| 1190 | $track_count++; | ||
| 1191 | $count_lbl->set_text("$track_count tracks found"); | ||
| 1192 | $self->_pump_events(); | ||
| 1193 | }, | ||
| 1194 | on_large_deletion => sub { | ||
| 1195 | my ($count, $folder_name) = @_; | ||
| 1196 | my $confirm = Gtk3::MessageDialog->new( | ||
| 1197 | $self->win, 'destroy-with-parent', 'warning', 'yes-no', | ||
| 1198 | "$count tracks would be removed from \"$folder_name\".\n\nProceed with deletion?", | ||
| 1199 | ); | ||
| 1200 | my $response = $confirm->run(); | ||
| 1201 | $confirm->destroy(); | ||
| 1202 | return $response eq 'yes'; | ||
| 1203 | }, | ||
| 1204 | ); | ||
| 1205 | $self->scanner($scanner); | ||
| 1206 | |||
| 1207 | $dlg->signal_connect(response => sub { | ||
| 1208 | $stopped = TRUE; | ||
| 1209 | $scanner->stop(); | ||
| 1210 | }); | ||
| 1211 | |||
| 1212 | for my $folder (@$folders) { | ||
| 1213 | last if $stopped; | ||
| 1214 | $current++; | ||
| 1215 | $status_lbl->set_text("Syncing folder $current/$total: $folder->{name}"); | ||
| 1216 | $progress->set_fraction($current / ($total + 1)); | ||
| 1217 | $self->_pump_events(); | ||
| 1218 | |||
| 1219 | my $result = eval { $scanner->scan_folder($folder->{id}, $folder->{name}) }; | ||
| 1220 | if ($@) { | ||
| 1221 | $self->_set_status("Error syncing $folder->{name}: $@"); | ||
| 1222 | } else { | ||
| 1223 | $total_removed += $result->{removed_tracks}; | ||
| 1224 | } | ||
| 1225 | } | ||
| 1226 | |||
| 1227 | my $done_msg = "Scanned $track_count tracks"; | ||
| 1228 | $done_msg .= ", $total_removed removed" if $total_removed > 0; | ||
| 1229 | $done_msg .= '.'; | ||
| 1230 | $progress->set_fraction(1.0); | ||
| 1231 | $status_lbl->set_text($done_msg); | ||
| 1232 | $self->_pump_events(); | ||
| 1233 | |||
| 1234 | $self->_load_library(); | ||
| 1235 | |||
| 1236 | # Keep the dialog up through the sheet sync — for a large folder this is a | ||
| 1237 | # long, synchronous operation, and destroying the dialog first left the app | ||
| 1238 | # looking frozen with no indication that work was still in progress. | ||
| 1239 | unless ($stopped) { | ||
| 1240 | $status_lbl->set_text('Syncing with Google Sheet…'); | ||
| 1241 | $progress->pulse(); | ||
| 1242 | $self->_pump_events(); | ||
| 1243 | $self->_sync_with_sheet(); | ||
| 1244 | } | ||
| 1245 | |||
| 1246 | $status_lbl->set_text('Sync complete.'); | ||
| 1247 | $progress->set_fraction(1.0); | ||
| 1248 | $self->_pump_events(); | ||
| 1249 | sleep 1; | ||
| 1250 | |||
| 1251 | $dlg->destroy(); | ||
| 1252 | } | ||
| 1253 | |||
| 1254 | # ---- Dialogs ---- | ||
| 1255 | |||
| 1256 | sub _settings_dialog { | ||
| 1257 | my ($self) = @_; | ||
| 1258 | $self->_settings_open(1); | ||
| 1259 | my $dlg = Gtk3::Dialog->new_with_buttons( | ||
| 1260 | 'Settings', $self->win, | ||
| 1261 | [qw/ modal destroy-with-parent /], | ||
| 1262 | 'Save', 'ok', | ||
| 1263 | 'Cancel', 'cancel', | ||
| 1264 | ); | ||
| 1265 | $dlg->set_default_size(520, -1); | ||
| 1266 | |||
| 1267 | my $vbox = $dlg->get_content_area(); | ||
| 1268 | $vbox->set_spacing(0); | ||
| 1269 | |||
| 1270 | # ---- Google API credentials ---- | ||
| 1271 | my $auth_frame = Gtk3::Frame->new('Google API Credentials'); | ||
| 1272 | $auth_frame->set_border_width(8); | ||
| 1273 | my $grid = Gtk3::Grid->new(); | ||
| 1274 | $grid->set_row_spacing(8); | ||
| 1275 | $grid->set_column_spacing(8); | ||
| 1276 | $grid->set_border_width(8); | ||
| 1277 | $auth_frame->add($grid); | ||
| 1278 | $vbox->pack_start($auth_frame, FALSE, FALSE, 0); | ||
| 1279 | |||
| 1280 | my $row = 0; | ||
| 1281 | my %entries; | ||
| 1282 | for my $field ( | ||
| 1283 | ['client_id', 'OAuth Client ID:', | ||
| 1284 | 'OAuth 2.0 Client ID from Google Cloud Console (Desktop app type).'], | ||
| 1285 | ['client_secret', 'OAuth Client Secret:', | ||
| 1286 | 'OAuth 2.0 Client Secret paired with the Client ID above.'], | ||
| 1287 | ['token_file', 'Token File:', | ||
| 1288 | 'Path to the OAuth2 token created by running ' | ||
| 1289 | . 'google_restapi_oauth_token_creator.'], | ||
| 1290 | ) { | ||
| 1291 | my ($key, $lbl, $tip) = @$field; | ||
| 1292 | my $lbl_w = Gtk3::Label->new($lbl); | ||
| 1293 | $lbl_w->set_xalign(1.0); | ||
| 1294 | $lbl_w->set_tooltip_text($tip); | ||
| 1295 | $grid->attach($lbl_w, 0, $row, 1, 1); | ||
| 1296 | my $e = Gtk3::Entry->new(); | ||
| 1297 | $e->set_hexpand(TRUE); | ||
| 1298 | $e->set_text($self->config->auth_config()->{$key} // ''); | ||
| 1299 | $e->set_visibility(FALSE) if $key eq 'client_secret'; | ||
| 1300 | $e->set_tooltip_text($tip); | ||
| 1301 | $grid->attach($e, 1, $row, 1, 1); | ||
| 1302 | $entries{$key} = $e; | ||
| 1303 | $row++; | ||
| 1304 | } | ||
| 1305 | |||
| 1306 | my $auth_note = Gtk3::Label->new(); | ||
| 1307 | $auth_note->set_markup( | ||
| 1308 | '<span size="small" foreground="#555555">' | ||
| 1309 | . 'Create a Desktop-app OAuth client at ' | ||
| 1310 | . '<a href="https://console.cloud.google.com/apis/credentials">' | ||
| 1311 | . 'Google Cloud Console → Credentials</a>, then enable the ' | ||
| 1312 | . '<a href="https://console.cloud.google.com/apis/library/drive.googleapis.com">' | ||
| 1313 | . 'Drive API</a>. Generate the token file by running ' | ||
| 1314 | . '<tt>google_restapi_oauth_token_creator</tt> in a terminal.' | ||
| 1315 | . '</span>' | ||
| 1316 | ); | ||
| 1317 | $auth_note->set_xalign(0.0); | ||
| 1318 | $auth_note->set_line_wrap(TRUE); | ||
| 1319 | $auth_note->set_max_width_chars(60); | ||
| 1320 | $grid->attach($auth_note, 1, $row, 1, 1); | ||
| 1321 | |||
| 1322 | # ---- Google Sheet sync ---- | ||
| 1323 | my $sheet_frame = Gtk3::Frame->new('Google Sheet Sync'); | ||
| 1324 | $sheet_frame->set_border_width(8); | ||
| 1325 | my $sheet_grid = Gtk3::Grid->new(); | ||
| 1326 | $sheet_grid->set_row_spacing(8); | ||
| 1327 | $sheet_grid->set_column_spacing(8); | ||
| 1328 | $sheet_grid->set_border_width(8); | ||
| 1329 | $sheet_frame->add($sheet_grid); | ||
| 1330 | $vbox->pack_start($sheet_frame, FALSE, FALSE, 0); | ||
| 1331 | |||
| 1332 | my $sid_lbl = Gtk3::Label->new('Spreadsheet ID:'); | ||
| 1333 | $sid_lbl->set_xalign(1.0); | ||
| 1334 | $sheet_grid->attach($sid_lbl, 0, 0, 1, 1); | ||
| 1335 | |||
| 1336 | my $sid_box = Gtk3::Box->new('horizontal', 6); | ||
| 1337 | my $sid_entry = Gtk3::Entry->new(); | ||
| 1338 | $sid_entry->set_hexpand(TRUE); | ||
| 1339 | $sid_entry->set_text($self->config->sheet_id()); | ||
| 1340 | $sid_entry->set_placeholder_text('Paste spreadsheet ID, or click Find or Create'); | ||
| 1341 | $sid_entry->set_tooltip_text( | ||
| 1342 | 'The spreadsheet ID is the long string between "/d/" and "/edit" ' | ||
| 1343 | . 'in a Google Sheets URL. Leave blank and click "Find or Create" ' | ||
| 1344 | . 'to have DrivePlayer find or create a sheet for you.' | ||
| 1345 | ); | ||
| 1346 | $sid_lbl->set_tooltip_text($sid_entry->get_tooltip_text()); | ||
| 1347 | $sid_box->pack_start($sid_entry, TRUE, TRUE, 0); | ||
| 1348 | |||
| 1349 | my $create_btn = Gtk3::Button->new_with_label('Find or Create…'); | ||
| 1350 | $create_btn->set_tooltip_text('Use existing DrivePlayer Library spreadsheet, or create one'); | ||
| 1351 | $create_btn->signal_connect(clicked => sub { | ||
| 1352 | return unless $self->_init_api(); | ||
| 1353 | $create_btn->set_sensitive(FALSE); | ||
| 1354 | $create_btn->set_label('Searching…'); | ||
| 1355 | $self->_pump_events(); | ||
| 1356 | |||
| 1357 | my $id; | ||
| 1358 | my @found = eval { | ||
| 1359 | $self->drive->list( | ||
| 1360 | filter => "name='DrivePlayer Library' and mimeType='application/vnd.google-apps.spreadsheet' and trashed=false", | ||
| 1361 | params => { fields => 'files(id,name)', pageSize => 1 }, | ||
| 1362 | ); | ||
| 1363 | }; | ||
| 1364 | if ($@) { | ||
| 1365 | $self->_show_error("Drive search failed:\n$@"); | ||
| 1366 | } elsif (@found) { | ||
| 1367 | $id = $found[0]{id}; | ||
| 1368 | } else { | ||
| 1369 | $create_btn->set_label('Creating…'); | ||
| 1370 | $self->_pump_events(); | ||
| 1371 | my $sheet = App::DrivePlayer::SheetDB->new(api => $self->rest_api); | ||
| 1372 | $id = eval { $sheet->create() }; | ||
| 1373 | $self->_show_error("Failed to create spreadsheet:\n$@") if $@; | ||
| 1374 | } | ||
| 1375 | $sid_entry->set_text($id) if $id; | ||
| 1376 | $create_btn->set_label('Find or Create…'); | ||
| 1377 | $create_btn->set_sensitive(TRUE); | ||
| 1378 | }); | ||
| 1379 | $sid_box->pack_start($create_btn, FALSE, FALSE, 0); | ||
| 1380 | $sheet_grid->attach($sid_box, 1, 0, 1, 1); | ||
| 1381 | |||
| 1382 | my $sheet_note = Gtk3::Label->new(); | ||
| 1383 | $sheet_note->set_markup( | ||
| 1384 | '<span size="small" foreground="#555555">' | ||
| 1385 | . 'The library syncs to this sheet automatically after each ' | ||
| 1386 | . 'Library → Sync. Useful for sharing metadata across devices or ' | ||
| 1387 | . 'editing tags in ' | ||
| 1388 | . '<a href="https://sheets.google.com/">Google Sheets</a>.' | ||
| 1389 | . '</span>' | ||
| 1390 | ); | ||
| 1391 | $sheet_note->set_xalign(0.0); | ||
| 1392 | $sheet_note->set_line_wrap(TRUE); | ||
| 1393 | $sheet_note->set_max_width_chars(60); | ||
| 1394 | $sheet_grid->attach($sheet_note, 1, 1, 1, 1); | ||
| 1395 | |||
| 1396 | # ---- Acoustic fingerprinting ---- | ||
| 1397 | my $fp_frame = Gtk3::Frame->new('Acoustic Fingerprinting (AcoustID)'); | ||
| 1398 | $fp_frame->set_border_width(8); | ||
| 1399 | my $fp_grid = Gtk3::Grid->new(); | ||
| 1400 | $fp_grid->set_row_spacing(8); | ||
| 1401 | $fp_grid->set_column_spacing(8); | ||
| 1402 | $fp_grid->set_border_width(8); | ||
| 1403 | $fp_frame->add($fp_grid); | ||
| 1404 | $vbox->pack_start($fp_frame, FALSE, FALSE, 0); | ||
| 1405 | |||
| 1406 | # fpcalc status row | ||
| 1407 | my $fp_lbl = Gtk3::Label->new('fpcalc:'); | ||
| 1408 | $fp_lbl->set_xalign(1.0); | ||
| 1409 | $fp_grid->attach($fp_lbl, 0, 0, 1, 1); | ||
| 1410 | |||
| 1411 | my $fp_status = Gtk3::Label->new(); | ||
| 1412 | $fp_status->set_xalign(0.0); | ||
| 1413 | |||
| 1414 | my $install_btn = Gtk3::Button->new_with_label('Install…'); | ||
| 1415 | $install_btn->set_tooltip_text( | ||
| 1416 | 'Installs libchromaprint-tools via apt (requires administrator password)' | ||
| 1417 | ); | ||
| 1418 | |||
| 1419 | my $fp_hbox = Gtk3::Box->new('horizontal', 8); | ||
| 1420 | $fp_hbox->pack_start($fp_status, FALSE, FALSE, 0); | ||
| 1421 | $fp_hbox->pack_start($install_btn, FALSE, FALSE, 0); | ||
| 1422 | $fp_grid->attach($fp_hbox, 1, 0, 1, 1); | ||
| 1423 | |||
| 1424 | # Helper: refresh the fpcalc status label | ||
| 1425 | my $refresh_fp_status = sub { | ||
| 1426 | if (App::DrivePlayer::MetadataFetcher::fpcalc_available()) { | ||
| 1427 | $fp_status->set_markup('<span foreground="#2d862d"><b>Installed</b></span>'); | ||
| 1428 | $install_btn->hide(); | ||
| 1429 | } | ||
| 1430 | else { | ||
| 1431 | $fp_status->set_markup( | ||
| 1432 | '<span foreground="#cc0000">Not installed</span>' | ||
| 1433 | . ' <span size="small" foreground="#666666">' | ||
| 1434 | . '(needed for fingerprint-based lookup)</span>' | ||
| 1435 | ); | ||
| 1436 | $install_btn->show(); | ||
| 1437 | } | ||
| 1438 | }; | ||
| 1439 | $refresh_fp_status->(); | ||
| 1440 | |||
| 1441 | $install_btn->signal_connect(clicked => sub { | ||
| 1442 | $install_btn->set_sensitive(FALSE); | ||
| 1443 | $fp_status->set_markup('<span foreground="#666666">Installing…</span>'); | ||
| 1444 | $self->_pump_events(); | ||
| 1445 | |||
| 1446 | my $pid = fork(); | ||
| 1447 | if (!defined $pid) { | ||
| 1448 | $fp_status->set_markup('<span foreground="#cc0000">Fork failed</span>'); | ||
| 1449 | $install_btn->set_sensitive(TRUE); | ||
| 1450 | return; | ||
| 1451 | } | ||
| 1452 | if ($pid == 0) { | ||
| 1453 | exec('pkexec', 'apt-get', 'install', '-y', 'libchromaprint-tools') | ||
| 1454 | or POSIX::_exit(1); | ||
| 1455 | } | ||
| 1456 | |||
| 1457 | # Poll every 500 ms until the child exits | ||
| 1458 | Glib::Timeout->add(500, sub { | ||
| 1459 | my $res = waitpid($pid, WNOHANG()); | ||
| 1460 | if ($res == $pid) { | ||
| 1461 | $refresh_fp_status->(); | ||
| 1462 | $install_btn->set_sensitive(TRUE); | ||
| 1463 | return FALSE; # remove timer | ||
| 1464 | } | ||
| 1465 | return TRUE; # keep polling | ||
| 1466 | }); | ||
| 1467 | }); | ||
| 1468 | |||
| 1469 | # AcoustID API key | ||
| 1470 | my $aid_lbl = Gtk3::Label->new('AcoustID API Key:'); | ||
| 1471 | $aid_lbl->set_xalign(1.0); | ||
| 1472 | $fp_grid->attach($aid_lbl, 0, 1, 1, 1); | ||
| 1473 | |||
| 1474 | my $aid_entry = Gtk3::Entry->new(); | ||
| 1475 | $aid_entry->set_hexpand(TRUE); | ||
| 1476 | $aid_entry->set_text($self->config->acoustid_key()); | ||
| 1477 | $aid_entry->set_placeholder_text('Get a free key at acoustid.org'); | ||
| 1478 | $aid_entry->set_tooltip_text( | ||
| 1479 | 'Free AcoustID API key — used with fpcalc to look up missing tags ' | ||
| 1480 | . 'by acoustic fingerprint.' | ||
| 1481 | ); | ||
| 1482 | $aid_lbl->set_tooltip_text($aid_entry->get_tooltip_text()); | ||
| 1483 | $fp_grid->attach($aid_entry, 1, 1, 1, 1); | ||
| 1484 | |||
| 1485 | $fp_lbl->set_tooltip_text( | ||
| 1486 | 'fpcalc (from chromaprint) generates audio fingerprints for ' | ||
| 1487 | . 'acoustic-ID lookup. Install it via apt if missing.' | ||
| 1488 | ); | ||
| 1489 | |||
| 1490 | my $aid_note = Gtk3::Label->new(); | ||
| 1491 | $aid_note->set_markup( | ||
| 1492 | '<span size="small" foreground="#555555">' | ||
| 1493 | . 'Register a free application at ' | ||
| 1494 | . '<a href="https://acoustid.org/new-application">acoustid.org</a> ' | ||
| 1495 | . 'to obtain a key. ' | ||
| 1496 | . '<a href="https://acoustid.org/">More info</a>.' | ||
| 1497 | . '</span>' | ||
| 1498 | ); | ||
| 1499 | $aid_note->set_xalign(0.0); | ||
| 1500 | $aid_note->set_line_wrap(TRUE); | ||
| 1501 | $aid_note->set_max_width_chars(60); | ||
| 1502 | $fp_grid->attach($aid_note, 1, 2, 1, 1); | ||
| 1503 | |||
| 1504 | # ---- Config file path (informational) ---- | ||
| 1505 | my $info_grid = Gtk3::Grid->new(); | ||
| 1506 | $info_grid->set_row_spacing(4); | ||
| 1507 | $info_grid->set_column_spacing(8); | ||
| 1508 | $info_grid->set_border_width(8); | ||
| 1509 | $vbox->pack_start($info_grid, FALSE, FALSE, 0); | ||
| 1510 | |||
| 1511 | my $cfg_key = Gtk3::Label->new('Config file:'); | ||
| 1512 | $cfg_key->set_xalign(1.0); | ||
| 1513 | $info_grid->attach($cfg_key, 0, 0, 1, 1); | ||
| 1514 | my $cfg_lbl = Gtk3::Label->new($self->config->config_file()); | ||
| 1515 | $cfg_lbl->set_xalign(0.0); | ||
| 1516 | $cfg_lbl->set_selectable(TRUE); | ||
| 1517 | $info_grid->attach($cfg_lbl, 1, 0, 1, 1); | ||
| 1518 | |||
| 1519 | $dlg->show_all(); | ||
| 1520 | # Re-apply visibility after show_all (show_all overrides hide()) | ||
| 1521 | $refresh_fp_status->(); | ||
| 1522 | |||
| 1523 | my $response = $dlg->run(); | ||
| 1524 | |||
| 1525 | if ($response eq 'ok') { | ||
| 1526 | my $auth = $self->config->auth_config(); | ||
| 1527 | my %before = map { $_ => ($auth->{$_} // '') } keys %entries; | ||
| 1528 | for my $key (keys %entries) { | ||
| 1529 | $auth->{$key} = $entries{$key}->get_text(); | ||
| 1530 | } | ||
| 1531 | $self->config->_data->{acoustid_key} = $aid_entry->get_text(); | ||
| 1532 | $self->config->_data->{sheet_id} = $sid_entry->get_text(); | ||
| 1533 | $self->config->save(); | ||
| 1534 | |||
| 1535 | my $auth_changed = grep { | ||
| 1536 | $before{$_} ne ($auth->{$_} // '') | ||
| 1537 | } keys %entries; | ||
| 1538 | |||
| 1539 | if ($auth_changed && $self->rest_api) { | ||
| 1540 | $self->_reinit_api(); | ||
| 1541 | $self->_set_status('Settings saved. Reconnected to Google Drive.'); | ||
| 1542 | } else { | ||
| 1543 | $self->_set_status('Settings saved.'); | ||
| 1544 | } | ||
| 1545 | } | ||
| 1546 | $dlg->destroy(); | ||
| 1547 | $self->_settings_open(0); | ||
| 1548 | } | ||
| 1549 | |||
| 1550 | sub _tracklist_context_menu { | ||
| 1551 | my ($self, $event) = @_; | ||
| 1552 | |||
| 1553 | my ($path) = $self->track_view->get_path_at_pos($event->x, $event->y); | ||
| 1554 | return unless $path; | ||
| 1555 | $self->track_view->get_selection()->select_path($path); | ||
| 1556 | my $track = $self->_track_at_path($path); | ||
| 1557 | |||
| 1558 | my $menu = Gtk3::Menu->new(); | ||
| 1559 | |||
| 1560 | my $play_item = Gtk3::MenuItem->new_with_label('Play'); | ||
| 1561 | $play_item->signal_connect(activate => sub { $self->_play_at_path($path) }); | ||
| 1562 | $menu->append($play_item); | ||
| 1563 | |||
| 1564 | my $edit_item = Gtk3::MenuItem->new_with_label('Edit…'); | ||
| 1565 | $edit_item->signal_connect(activate => sub { | ||
| 1566 | $self->_edit_metadata_dialog($track) if $track; | ||
| 1567 | }); | ||
| 1568 | $menu->append($edit_item); | ||
| 1569 | |||
| 1570 | $menu->show_all(); | ||
| 1571 | $menu->popup_at_pointer($event); | ||
| 1572 | } | ||
| 1573 | |||
| 1574 | sub _edit_metadata_dialog { | ||
| 1575 | my ($self, $track) = @_; | ||
| 1576 | |||
| 1577 | my $dlg = Gtk3::Dialog->new_with_buttons( | ||
| 1578 | 'Edit Metadata', $self->win, | ||
| 1579 | [qw/ modal destroy-with-parent /], | ||
| 1580 | 'Save', 'ok', | ||
| 1581 | 'Cancel', 'cancel', | ||
| 1582 | ); | ||
| 1583 | $dlg->set_default_size(460, 280); | ||
| 1584 | |||
| 1585 | my $grid = Gtk3::Grid->new(); | ||
| 1586 | $grid->set_row_spacing(6); | ||
| 1587 | $grid->set_column_spacing(8); | ||
| 1588 | $grid->set_border_width(12); | ||
| 1589 | $dlg->get_content_area()->add($grid); | ||
| 1590 | |||
| 1591 | # LRM (U+200E) is an invisible left-to-right marker. Prepending it to | ||
| 1592 | # an Entry's text forces the internal PangoLayout's base direction to | ||
| 1593 | # LTR, which keeps short RTL content (Arabic, Hebrew, …) flush with the | ||
| 1594 | # left edge instead of the right. The glyphs within still render in | ||
| 1595 | # their natural direction, so "راغب علامة" still looks correct. | ||
| 1596 | # We strip the marker on read so it never reaches the DB or a query. | ||
| 1597 | my $LRM = "\x{200E}"; | ||
| 1598 | my $put = sub { | ||
| 1599 | my ($entry, $val) = @_; | ||
| 1600 | $val //= ''; | ||
| 1601 | $entry->set_text(length $val ? $LRM . $val : ''); | ||
| 1602 | }; | ||
| 1603 | my $get = sub { | ||
| 1604 | my ($entry) = @_; | ||
| 1605 | my $v = $entry->get_text(); | ||
| 1606 | $v =~ s/[\x{200E}\x{200F}]//g; # LRM + RLM | ||
| 1607 | return $v; | ||
| 1608 | }; | ||
| 1609 | |||
| 1610 | my %entries; | ||
| 1611 | my $row = 0; | ||
| 1612 | for my $field ( | ||
| 1613 | [ title => 'Title:' ], | ||
| 1614 | [ artist => 'Artist:' ], | ||
| 1615 | [ album => 'Album:' ], | ||
| 1616 | [ genre => 'Genre:' ], | ||
| 1617 | [ track_number => 'Track Number:' ], | ||
| 1618 | [ year => 'Year:' ], | ||
| 1619 | [ comment => 'Comment:' ], | ||
| 1620 | ) { | ||
| 1621 | my ($key, $lbl) = @$field; | ||
| 1622 | my $label = Gtk3::Label->new($lbl); | ||
| 1623 | $label->set_xalign(1.0); | ||
| 1624 | $grid->attach($label, 0, $row, 1, 1); | ||
| 1625 | my $entry = Gtk3::Entry->new(); | ||
| 1626 | $entry->set_hexpand(TRUE); | ||
| 1627 | $entry->set_direction('ltr'); | ||
| 1628 | $entry->set_alignment(0.0); | ||
| 1629 | $put->($entry, $track->{$key}); | ||
| 1630 | $grid->attach($entry, 1, $row, 1, 1); | ||
| 1631 | $entries{$key} = $entry; | ||
| 1632 | $row++; | ||
| 1633 | } | ||
| 1634 | |||
| 1635 | my $fetch_btn = Gtk3::Button->new_with_label('Fetch'); | ||
| 1636 | $fetch_btn->set_halign('end'); | ||
| 1637 | $fetch_btn->set_tooltip_text( | ||
| 1638 | 'Look up missing fields online (text search, then AcoustID ' | ||
| 1639 | . 'fingerprint). Only blank fields are filled — to refresh a ' | ||
| 1640 | . 'populated field, clear it first.' | ||
| 1641 | ); | ||
| 1642 | # Treat whitespace-only fields as blank for both the query we build and | ||
| 1643 | # the emptiness test below — a stray space is almost never what the user | ||
| 1644 | # meant and it would otherwise block the fetch from filling the field. | ||
| 1645 | my $trimmed = sub { | ||
| 1646 | my $s = shift // ''; | ||
| 1647 | $s =~ s/\A\s+//; | ||
| 1648 | $s =~ s/\s+\z//; | ||
| 1649 | return $s; | ||
| 1650 | }; | ||
| 1651 | |||
| 1652 | $fetch_btn->signal_connect(clicked => sub { | ||
| 1653 | # Build a track-like hashref from current dialog contents so the | ||
| 1654 | # lookup uses whatever the user has typed so far. | ||
| 1655 | my %current = (drive_id => $track->{drive_id}); | ||
| 1656 | for my $key (keys %entries) { | ||
| 1657 | my $val = $trimmed->($get->($entries{$key})); | ||
| 1658 | $current{$key} = length $val ? $val : undef; | ||
| 1659 | } | ||
| 1660 | $fetch_btn->set_sensitive(FALSE); | ||
| 1661 | $fetch_btn->set_label('Fetching…'); | ||
| 1662 | $self->_pump_events(); | ||
| 1663 | |||
| 1664 | my $meta = $self->_lookup_metadata(\%current); | ||
| 1665 | |||
| 1666 | $fetch_btn->set_label('Fetch'); | ||
| 1667 | $fetch_btn->set_sensitive(TRUE); | ||
| 1668 | |||
| 1669 | return unless $meta; | ||
| 1670 | my @filled; | ||
| 1671 | for my $key (keys %entries) { | ||
| 1672 | my $cur = $trimmed->($get->($entries{$key})); | ||
| 1673 | my $new = $meta->{$key}; | ||
| 1674 | if ($log) { | ||
| 1675 | $log->debug(sprintf | ||
| 1676 | 'Fetch fill %s: cur=[%s] meta=[%s]', | ||
| 1677 | $key, $cur, $new // '(undef)'); | ||
| 1678 | } | ||
| 1679 | next if length $cur; | ||
| 1680 | next unless defined $new && length $new; | ||
| 1681 | $put->($entries{$key}, "$new"); # LRM-prefixed, LTR layout | ||
| 1682 | push @filled, $key; | ||
| 1683 | } | ||
| 1684 | $self->_pump_events(); | ||
| 1685 | $log->debug('Fetch filled: ' . (@filled ? join(',', @filled) : '(none)')) | ||
| 1686 | if $log; | ||
| 1687 | }); | ||
| 1688 | $grid->attach($fetch_btn, 0, $row, 2, 1); | ||
| 1689 | $row++; | ||
| 1690 | |||
| 1691 | my $fetch_help = Gtk3::Label->new(); | ||
| 1692 | $fetch_help->set_markup( | ||
| 1693 | '<span size="small" foreground="#555555">' | ||
| 1694 | . 'Fetch only fills blank fields. To replace a field with looked-up ' | ||
| 1695 | . 'data, clear it first and then click Fetch.' | ||
| 1696 | . '</span>' | ||
| 1697 | ); | ||
| 1698 | $fetch_help->set_xalign(0.0); | ||
| 1699 | $fetch_help->set_line_wrap(TRUE); | ||
| 1700 | $fetch_help->set_max_width_chars(60); | ||
| 1701 | $grid->attach($fetch_help, 0, $row, 2, 1); | ||
| 1702 | |||
| 1703 | $dlg->show_all(); | ||
| 1704 | if ($dlg->run() eq 'ok') { | ||
| 1705 | my %fields; | ||
| 1706 | for my $key (keys %entries) { | ||
| 1707 | # Trim leading/trailing whitespace so "Beatles " and "Beatles" | ||
| 1708 | # don't end up as separate sidebar entries. | ||
| 1709 | my $val = $trimmed->($get->($entries{$key})); | ||
| 1710 | $fields{$key} = length($val) ? $val : undef; | ||
| 1711 | } | ||
| 1712 | # Coerce numeric fields | ||
| 1713 | for my $key (qw( track_number year )) { | ||
| 1714 | $fields{$key} = $fields{$key} ? int($fields{$key}) : undef; | ||
| 1715 | } | ||
| 1716 | |||
| 1717 | # Detect whether the sidebar tree (Artists / Albums / Genres) needs | ||
| 1718 | # rebuilding because a grouping field changed. | ||
| 1719 | my $sidebar_dirty = 0; | ||
| 1720 | for my $f (qw( artist album genre )) { | ||
| 1721 | next if (($track->{$f} // '') eq ($fields{$f} // '')); | ||
| 1722 | $sidebar_dirty = 1; | ||
| 1723 | last; | ||
| 1724 | } | ||
| 1725 | |||
| 1726 | # If the user changed an artist/album/genre value that other tracks | ||
| 1727 | # also use, offer to apply the rename to every matching track. This | ||
| 1728 | # is what lets a single mojibake fix clean up the lingering sidebar | ||
| 1729 | # entry instead of leaving it stuck behind the still-broken siblings. | ||
| 1730 | my @propagate; # ([field, old, new, sibling_count], ...) | ||
| 1731 | for my $f (qw( artist album genre )) { | ||
| 1732 | my $old = $track->{$f} // ''; | ||
| 1733 | my $new = $fields{$f} // ''; | ||
| 1734 | next if $old eq $new; | ||
| 1735 | next unless length $old; # only meaningful when there's an old | ||
| 1736 | # value to rename away from | ||
| 1737 | my $n = $self->db->count_tracks_with_field($f, $old, $track->{id}); | ||
| 1738 | push @propagate, [$f, $old, $new, $n] if $n > 0; | ||
| 1739 | } | ||
| 1740 | |||
| 1741 | my $apply_to_all = 0; | ||
| 1742 | if (@propagate) { | ||
| 1743 | my $body = "Apply these changes to all matching tracks?\n\n"; | ||
| 1744 | for my $p (@propagate) { | ||
| 1745 | my ($f, $old, $new, $n) = @$p; | ||
| 1746 | my $shown_new = length $new ? "'$new'" : '(empty)'; | ||
| 1747 | $body .= sprintf(" \x{2022} Rename %s '%s' to %s (%d other %s)\n", | ||
| 1748 | $f, $old, $shown_new, | ||
| 1749 | $n, $n == 1 ? 'track' : 'tracks'); | ||
| 1750 | } | ||
| 1751 | my $confirm = Gtk3::MessageDialog->new( | ||
| 1752 | $self->win, 'destroy-with-parent', 'question', 'none', $body | ||
| 1753 | ); | ||
| 1754 | $confirm->add_button('Only this track', 'no'); | ||
| 1755 | $confirm->add_button('Apply to all', 'yes'); | ||
| 1756 | $confirm->set_default_response('yes'); | ||
| 1757 | my $resp = $confirm->run(); | ||
| 1758 | $confirm->destroy(); | ||
| 1759 | $apply_to_all = ($resp eq 'yes'); | ||
| 1760 | } | ||
| 1761 | |||
| 1762 | my @synced_ids; | ||
| 1763 | if ($apply_to_all) { | ||
| 1764 | for my $p (@propagate) { | ||
| 1765 | my ($f, $old, $new) = @$p; | ||
| 1766 | # Capture ids before the rename so we can sync each affected | ||
| 1767 | # row to the sheet with its new value. | ||
| 1768 | push @synced_ids, $self->db->track_ids_with_field($f, $old); | ||
| 1769 | $self->db->rename_field($f, $old, $new); | ||
| 1770 | } | ||
| 1771 | } | ||
| 1772 | |||
| 1773 | $self->db->update_track_metadata($track->{id}, %fields); | ||
| 1774 | # Refresh the single row in place so the user's sidebar selection | ||
| 1775 | # and tracklist scroll position are preserved. A full _load_library | ||
| 1776 | # would clear the sidebar store and reload all_tracks, bumping them | ||
| 1777 | # back to the top-level "All Tracks" view. | ||
| 1778 | $self->_refresh_track_row($track->{id}); | ||
| 1779 | if ($apply_to_all) { | ||
| 1780 | # Other tracks' rows may now show different artist/album/genre | ||
| 1781 | # text; refresh each that changed. | ||
| 1782 | my %seen = ($track->{id} => 1); | ||
| 1783 | for my $tid (@synced_ids) { | ||
| 1784 | next if $seen{$tid}++; | ||
| 1785 | $self->_refresh_track_row($tid); | ||
| 1786 | } | ||
| 1787 | } | ||
| 1788 | $self->_refresh_sidebar_keep_selection() if $sidebar_dirty || $apply_to_all; | ||
| 1789 | # Targeted single-row sheet sync — avoids rewriting every worksheet | ||
| 1790 | # tab for a single metadata edit. | ||
| 1791 | $self->_auto_sync_track_to_sheet($track->{id}); | ||
| 1792 | if ($apply_to_all) { | ||
| 1793 | my %seen = ($track->{id} => 1); | ||
| 1794 | for my $tid (@synced_ids) { | ||
| 1795 | next if $seen{$tid}++; | ||
| 1796 | $self->_auto_sync_track_to_sheet($tid); | ||
| 1797 | } | ||
| 1798 | } | ||
| 1799 | } | ||
| 1800 | $dlg->destroy(); | ||
| 1801 | } | ||
| 1802 | |||
| 1803 | sub _clear_library { | ||
| 1804 | my ($self) = @_; | ||
| 1805 | my $dlg = Gtk3::MessageDialog->new( | ||
| 1806 | $self->win, 'destroy-with-parent', 'question', 'yes-no', | ||
| 1807 | 'Clear the entire music library? This will remove all scanned tracks.' | ||
| 1808 | ); | ||
| 1809 | my $response = $dlg->run(); | ||
| 1810 | $dlg->destroy(); | ||
| 1811 | return unless $response eq 'yes'; | ||
| 1812 | |||
| 1813 | for my $sf ($self->db->all_scan_folders()) { | ||
| 1814 | $self->db->delete_scan_folder($sf->{drive_id}); | ||
| 1815 | } | ||
| 1816 | $self->_load_library(); | ||
| 1817 | $self->_set_status('Library cleared.'); | ||
| 1818 | } | ||
| 1819 | |||
| 1820 | # ---- Helpers ---- | ||
| 1821 | |||
| 1822 | sub _update_now_playing { | ||
| 1823 | my ($self, $track) = @_; | ||
| 1824 | my $text = ''; | ||
| 1825 | $text .= _display_text($track->{artist}) . ' — ' if $track->{artist}; | ||
| 1826 | $text .= _display_title($track->{title}) || '(Unknown)'; | ||
| 1827 | $text .= ' [' . _display_album($track->{album}) . ']' if $track->{album}; | ||
| 1828 | $self->now_playing_label->set_text($text); | ||
| 1829 | $self->win->set_title("Drive Player — $text"); | ||
| 1830 | } | ||
| 1831 | |||
| 1832 | sub _highlight_path { | ||
| 1833 | my ($self, $path) = @_; | ||
| 1834 | my $view = $self->track_view; | ||
| 1835 | my $sel = $view->get_selection(); | ||
| 1836 | $sel->unselect_all(); | ||
| 1837 | $sel->select_path($path); | ||
| 1838 | |||
| 1839 | # Only scroll if the row isn't already visible — re-centring an on-screen | ||
| 1840 | # row is the "extra scrolling" the user sees. | ||
| 1841 | my ($first, $last) = $view->get_visible_range(); | ||
| 1842 | return if $first && $last | ||
| 1843 | && $path->compare($first) >= 0 | ||
| 1844 | && $path->compare($last) <= 0; | ||
| 1845 | |||
| 1846 | $view->scroll_to_cell($path, undef, TRUE, 0.5, 0.0); | ||
| 1847 | } | ||
| 1848 | |||
| 1849 | sub _set_status { | ||
| 1850 | my ($self, $msg) = @_; | ||
| 1851 | $self->statusbar->pop($self->_status_ctx); | ||
| 1852 | $self->statusbar->push($self->_status_ctx, $msg); | ||
| 1853 | } | ||
| 1854 | |||
| 1855 | sub _show_error { | ||
| 1856 | my ($self, $msg) = @_; | ||
| 1857 | my $dlg = Gtk3::MessageDialog->new( | ||
| 1858 | $self->win, 'destroy-with-parent', 'error', 'ok', $msg | ||
| 1859 | ); | ||
| 1860 | $dlg->run(); | ||
| 1861 | $dlg->destroy(); | ||
| 1862 | |||
| 1863 | if (_is_auth_error($msg) && !$self->_settings_open) { | ||
| 1864 | $self->_settings_dialog(); | ||
| 1865 | } | ||
| 1866 | } | ||
| 1867 | |||
| 1868 | # Heuristic: does an error message look like a Google API auth/connection | ||
| 1869 | # failure that the user can fix in the Settings dialog (bad credentials, | ||
| 1870 | # expired/revoked token, etc.)? | ||
| 1871 | sub _is_auth_error { | ||
| 1872 | my ($msg) = @_; | ||
| 1873 | return 0 unless defined $msg && length $msg; | ||
| 1874 | |||
| 1875 | return 1 if $msg =~ m{ | ||
| 1876 | \b (?: 401 | 403 ) \b # unauthorized / forbidden | ||
| 1877 | | \b invalid _ grant \b | ||
| 1878 | | \b invalid _ token \b | ||
| 1879 | | \b invalid _ client \b | ||
| 1880 | | \b token \b .* \b (?: expired | revoked ) \b | ||
| 1881 | | \b (?: expired | revoked ) \b .* \b token \b | ||
| 1882 | | unauthenti(?: cated | c ) | ||
| 1883 | }xi; | ||
| 1884 | |||
| 1885 | return 1 if $msg =~ m{ \b 400 \b }x | ||
| 1886 | && $msg =~ m{ | ||
| 1887 | \b (?: token | grant | oauth | credential s? | auth ) \b | ||
| 1888 | }xi; | ||
| 1889 | |||
| 1890 | return 0; | ||
| 1891 | } | ||
| 1892 | |||
| 1893 | sub _quit { | ||
| 1894 | my ($self) = @_; | ||
| 1895 | $self->_stop_metadata_fetch() if $self->_meta_watch_id; | ||
| 1896 | $self->player->quit() if $self->player; | ||
| 1897 | Gtk3->main_quit(); | ||
| 1898 | } | ||
| 1899 | |||
| 1900 | # ---- Formatting helpers ---- | ||
| 1901 | |||
| 1902 | sub _dur_str { | ||
| 1903 | my ($ms) = @_; | ||
| 1904 | return '' unless defined $ms && $ms > 0; | ||
| 1905 | return _sec_str($ms / 1000); | ||
| 1906 | } | ||
| 1907 | |||
| 1908 | sub _sec_str { | ||
| 1909 | my ($sec) = @_; | ||
| 1910 | return '0:00' unless defined $sec; | ||
| 1911 | $sec = int($sec); | ||
| 1912 | my $m = int($sec / 60); | ||
| 1913 | my $s = $sec % 60; | ||
| 1914 | return sprintf("%d:%02d", $m, $s); | ||
| 1915 | } | ||
| 1916 | |||
| 1917 | sub _track_num_str { | ||
| 1918 | my ($n) = @_; | ||
| 1919 | return '' unless defined $n && $n > 0; | ||
| 1920 | return sprintf("%02d", $n); | ||
| 1921 | } | ||
| 1922 | |||
| 1923 | # Display-only cosmetics: turn underscores back into spaces for | ||
| 1924 | # title / artist / album strings that came from filenames. The DB | ||
| 1925 | # keeps the raw value so lookups and sheet-sync continue to match. | ||
| 1926 | sub _display_text { | ||
| 1927 | my ($s) = @_; | ||
| 1928 | return '' unless defined $s && length $s; | ||
| 1929 | $s =~ tr/_/ /; | ||
| 1930 | return $s; | ||
| 1931 | } | ||
| 1932 | |||
| 1933 | # Same as _display_text, plus strips a leading "YYYY-" from album | ||
| 1934 | # names (19xx / 20xx). Defensive cover for rows scanned before the | ||
| 1935 | # Scanner learned to peel the year off. | ||
| 1936 | sub _display_album { | ||
| 1937 | my ($s) = @_; | ||
| 1938 | return '' unless defined $s && length $s; | ||
| 1939 | $s =~ s{ \A (?: 19 | 20 ) \d{2} - }{}x; | ||
| 1940 | $s =~ tr/_/ /; | ||
| 1941 | return $s; | ||
| 1942 | } | ||
| 1943 | |||
| 1944 | # Title-specific: strip a leading track-number prefix like "01 ", | ||
| 1945 | # "01 - ", "01. ", "01-" before applying the underscore transform. | ||
| 1946 | # Accepts 1-3 digit numbers so compilation tracks up to 999 still | ||
| 1947 | # get cleaned. | ||
| 1948 | sub _display_title { | ||
| 1949 | my ($s) = @_; | ||
| 1950 | return '' unless defined $s && length $s; | ||
| 1951 | # Swap underscores to spaces first so "01_Attention" becomes "01 Attention" | ||
| 1952 | # and the track-number prefix below can match it. | ||
| 1953 | $s =~ tr/_/ /; | ||
| 1954 | $s =~ s{ | ||
| 1955 | \A | ||
| 1956 | \s* # optional leading whitespace | ||
| 1957 | \d{1,3} # 1-3 digit track number | ||
| 1958 | [\s.\-]+ # separator: space, dot, hyphen | ||
| 1959 | }{}x; | ||
| 1960 | return $s; | ||
| 1961 | } | ||
| 1962 | |||
| 1963 | 1; | ||
| 1964 | |||
| 1965 | __END__ |