From 6c8504238ddbd96deea577df58c043b95cb1068d Mon Sep 17 00:00:00 2001 From: Eric Wong Date: Mon, 7 Dec 2015 02:34:28 +0000 Subject: tracklist: swap functionality This (from the point of the client) will atomically swap two tracks. This should allow easily implementing of a tracklist editor. --- lib/dtas/player/client_handler.rb | 8 ++++++++ lib/dtas/tracklist.rb | 21 +++++++++++++++++++++ test/test_tracklist.rb | 11 +++++++++++ 3 files changed, 40 insertions(+) diff --git a/lib/dtas/player/client_handler.rb b/lib/dtas/player/client_handler.rb index e0af295..17cd6c3 100644 --- a/lib/dtas/player/client_handler.rb +++ b/lib/dtas/player/client_handler.rb @@ -696,6 +696,14 @@ module DTAS::Player::ClientHandler # :nodoc: io.emit('OK') end + def _dpc_tl_swap(io, msg) + usage = 'ERR usage: "tl swap TRACK_ID_A TRACK_ID_B"' + a_id = msg.shift or return io.emit(usage) + b_id = msg.shift or return io.emit(usage) + @tl.swap(a_id.to_i, b_id.to_i) or return io.emit('MISSING') + io.emit('OK') + end + def __bp_prev_next(io, msg, cur, bp) case type = msg[1] when nil, "track" diff --git a/lib/dtas/tracklist.rb b/lib/dtas/tracklist.rb index b9abe55..7366799 100644 --- a/lib/dtas/tracklist.rb +++ b/lib/dtas/tracklist.rb @@ -220,4 +220,25 @@ class DTAS::Tracklist # :nodoc: end @goto_pos = prev_idx end + + def swap(a_id, b_id) + ok = { a_id => a_idx = [], b_id => b_idx = [] } + @list.each_with_index do |t,i| + ary = ok.delete(t.track_id) or next + ary[0] = i + break if ok.empty? + end + a_idx = a_idx[0] or return + b_idx = b_idx[0] or return + @list[a_idx], @list[b_idx] = @list[b_idx], @list[a_idx] + unless @shuffle + [ :@goto_pos, :@pos ].each do |v| + case instance_variable_get(v) + when a_idx then instance_variable_set(v, b_idx) + when b_idx then instance_variable_set(v, a_idx) + end + end + end + true + end end diff --git a/test/test_tracklist.rb b/test/test_tracklist.rb index c918ff7..c05090c 100644 --- a/test/test_tracklist.rb +++ b/test/test_tracklist.rb @@ -120,4 +120,15 @@ class TestTracklist < Testcase assert_kind_of Integer, tl.add_track('y') assert_equal 2, tl.instance_variable_get(:@list).size end + + def test_swap + tl = DTAS::Tracklist.new + list_add(tl, %w(a b c d e f g)) + mapping = _build_mapping(tl) + assert tl.swap(mapping['a'], mapping['g']) + assert_equal %w(g b c d e f a), list_to_path(tl) + + assert_nil tl.swap(-2, -3), 'no swap on invalid' + assert_equal %w(g b c d e f a), list_to_path(tl) + end end -- cgit v1.2.3-24-ge0c7