Permalink
Browse files

Simpler and cleaner way to call a method on the MPD client

Before, it was required to pass by the .call() method.  Now, we can call
directly the command we are interested in, which is more convenient and much
clearer.
.call() is still availabl, since it has a "complex" logic inside, and used for
two calls which only the MPD command to execute from a string as argument.
  • Loading branch information...
1 parent 3f0c18d commit d0b4fd4e44a2b7a44ae26dd695947754469b729d @multani committed Oct 31, 2011
Showing with 104 additions and 97 deletions.
  1. +9 −9 sonata/cli.py
  2. +24 −26 sonata/current.py
  3. +9 −9 sonata/library.py
  4. +36 −37 sonata/main.py
  5. +17 −7 sonata/mpdhelper.py
  6. +9 −9 sonata/playlists.py
View
18 sonata/cli.py
@@ -139,9 +139,9 @@ def mpd_connect(self):
if not password:
password = self.config.password[self.config.profile_num]
- self.MPDH.call('connect', host, port)
+ self.MPDH.connect(host, port)
if password:
- self.MPDH.call('password', password)
+ self.MPDH.password(password)
def execute_cmd(self, cmd):
self.status = self.MPDH.status()
@@ -154,19 +154,19 @@ def execute_cmd(self, cmd):
getattr(self, "_execute_%s" % cmd)()
def _execute_play(self):
- self.MPDH.call('play')
+ self.MPDH.play()
def _execute_pause(self):
- self.MPDH.call('pause', 1)
+ self.MPDH.pause(1)
def _execute_stop(self):
- self.MPDH.call('stop')
+ self.MPDH.stop()
def _execute_next(self):
- self.MPDH.call('next')
+ self.MPDH.next()
def _execute_prev(self):
- self.MPDH.call('previous')
+ self.MPDH.previous()
def _execute_bool(self, cmd):
"""Set the reverse the value of cmd"""
@@ -180,9 +180,9 @@ def _execute_repeat(self):
def _execute_pp(self):
if self.status['state'] in ['play']:
- self.MPDH.call('pause', 1)
+ self.MPDH.pause(1)
elif self.status['state'] in ['pause', 'stop']:
- self.MPDH.call('play')
+ self.MPDH.play()
def _execute_info(self):
if self.status['state'] in ['play', 'pause']:
View
50 sonata/current.py
@@ -236,10 +236,9 @@ def current_update(self, prevstatus_playlist, new_playlist_length):
self.current.set_model(None)
if prevstatus_playlist:
- changed_songs = self.MPDH.call('plchanges',
- prevstatus_playlist)
+ changed_songs = self.MPDH.plchanges(prevstatus_playlist)
else:
- changed_songs = self.MPDH.call('plchanges', 0)
+ changed_songs = self.MPDH.plchanges(0)
self.current_songs = []
newlen = int(new_playlist_length)
@@ -482,11 +481,11 @@ def sort(self, mode, column=None):
songs.sort(key=lambda x: x["sortby"])
pos = 0
- self.MPDH.call('command_list_ok_begin')
+ self.MPDH.command_list_ok_begin()
for item in songs:
- self.MPDH.call('moveid', item["id"], pos)
+ self.MPDH.moveid(item["id"], pos)
pos += 1
- self.MPDH.call('command_list_end')
+ self.MPDH.command_list_end()
self.iterate_now()
self.header_update_column_indicators()
@@ -520,12 +519,12 @@ def on_sort_reverse(self, _action):
gtk.main_iteration()
top = 0
bot = len(self.currentdata)-1
- self.MPDH.call('command_list_ok_begin')
+ self.MPDH.command_list_ok_begin()
while top < bot:
- self.MPDH.call('swap', top, bot)
+ self.MPDH.swap(top, bot)
top = top + 1
bot = bot - 1
- self.MPDH.call('command_list_end')
+ self.MPDH.command_list_end()
self.iterate_now()
def on_dnd(self, treeview, drag_context, x, y, selection, _info,
@@ -554,8 +553,7 @@ def on_dnd(self, treeview, drag_context, x, y, selection, _info,
paths[i] = paths[i][len(musicdir):]
if len(paths[i]) == 0:
paths[i] = "/"
- listallinfo = self.MPDH.call('listallinfo',
- paths[i])
+ listallinfo = self.MPDH.listallinfo(paths[i])
for item in listallinfo:
if 'file' in item:
mpdpaths.append(mpdh.get(item, 'file'))
@@ -583,7 +581,7 @@ def on_dnd(self, treeview, drag_context, x, y, selection, _info,
else:
songid = len(self.currentdata)
for mpdpath in mpdpaths:
- self.MPDH.call('addid', mpdpath, songid)
+ self.MPDH.addid(mpdpath, songid)
self.iterate_now()
return
@@ -606,7 +604,7 @@ def on_dnd(self, treeview, drag_context, x, y, selection, _info,
# We will manipulate self.current_songs and model to prevent
# the entire playlist from refreshing
offset = 0
- self.MPDH.call('command_list_ok_begin')
+ self.MPDH.command_list_ok_begin()
for source in drag_sources:
index, i, songid, text = source
if drop_info:
@@ -619,10 +617,10 @@ def on_dnd(self, treeview, drag_context, x, y, selection, _info,
self.current_songs.insert(dest, self.current_songs[index])
if dest < index + 1:
self.current_songs.pop(index + 1)
- self.MPDH.call('moveid', songid, dest)
+ self.MPDH.moveid(songid, dest)
else:
self.current_songs.pop(index)
- self.MPDH.call('moveid', songid, dest - 1)
+ self.MPDH.moveid(songid, dest - 1)
model.insert(dest, model[index])
moved_iters += [model.get_iter((dest,))]
model.remove(i)
@@ -631,17 +629,17 @@ def on_dnd(self, treeview, drag_context, x, y, selection, _info,
self.current_songs[index])
if dest < index:
self.current_songs.pop(index + 1)
- self.MPDH.call('moveid', songid, dest + 1)
+ self.MPDH.moveid(songid, dest + 1)
else:
self.current_songs.pop(index)
- self.MPDH.call('moveid', songid, dest)
+ self.MPDH.moveid(songid, dest)
model.insert(dest + 1, model[index])
moved_iters += [model.get_iter((dest + 1,))]
model.remove(i)
else:
#dest = int(self.status['playlistlength']) - 1
dest = len(self.currentdata) - 1
- self.MPDH.call('moveid', songid, dest)
+ self.MPDH.moveid(songid, dest)
self.current_songs.insert(dest + 1, self.current_songs[index])
self.current_songs.pop(index)
model.insert(dest + 1, model[index])
@@ -658,7 +656,7 @@ def on_dnd(self, treeview, drag_context, x, y, selection, _info,
# decreased by 1
if index < source[0] < dest:
source[0] -= 1
- self.MPDH.call('command_list_end')
+ self.MPDH.command_list_end()
# we are manipulating the model manually for speed, so...
self.current_update_skip = True
@@ -683,7 +681,7 @@ def on_current_click(self, _treeview, path, _column):
return
try:
i = model.get_iter(path)
- self.MPDH.call('playid', self.current_get_songid(i, model))
+ self.MPDH.playid(self.current_get_songid(i, model))
except:
pass
self.sel_rows = False
@@ -727,7 +725,7 @@ def searchfilter_on_enter(self, _entry):
song_id = self.current_get_songid(model.get_iter_first(), model)
if song_id:
self.searchfilter_toggle(None)
- self.MPDH.call('playid', song_id)
+ self.MPDH.playid(song_id)
def searchfilter_feed_loop(self, editable):
# Lets only trigger the searchfilter_loop if 200ms pass
@@ -927,7 +925,7 @@ def on_remove(self):
if len(selected) == len(self.currentdata) and \
not self.filterbox_visible:
# Everything is selected, clear:
- self.MPDH.call('clear')
+ self.MPDH.clear()
elif len(selected) > 0:
# we are manipulating the model manually for speed, so...
self.current_update_skip = True
@@ -936,18 +934,18 @@ def on_remove(self):
# If we remove an item from the filtered results, this
# causes a visual refresh in the interface.
self.current.set_model(None)
- self.MPDH.call('command_list_ok_begin')
+ self.MPDH.command_list_ok_begin()
for path in selected:
if not self.filterbox_visible:
rownum = path[0]
else:
rownum = self.filter_row_mapping[path[0]]
i = self.currentdata.get_iter((rownum, 0))
- self.MPDH.call('deleteid', self.current_get_songid(i,
- self.currentdata))
+ self.MPDH.deleteid(
+ self.current_get_songid(i, self.currentdata))
# Prevents the entire playlist from refreshing:
self.current_songs.pop(rownum)
self.currentdata.remove(i)
- self.MPDH.call('command_list_end')
+ self.MPDH.command_list_end()
if not self.filterbox_visible:
self.current.set_model(model)
View
18 sonata/library.py
@@ -548,7 +548,7 @@ def library_populate_filesystem_data(self, path):
# Use cache if possible...
bd = self.lib_view_filesystem_cache
else:
- for item in self.MPDH.call('lsinfo', path):
+ for item in self.MPDH.lsinfo(path):
if 'directory' in item:
name = mpdh.get(item, 'directory').split('/')[-1]
data = self.library_set_data(path=mpdh.get(item,
@@ -625,7 +625,7 @@ def library_populate_toplevel_data(self, genreview=False, artistview=False,
elif albumview:
albums = []
untagged_found = False
- for item in self.MPDH.call('listallinfo', '/'):
+ for item in self.MPDH.listallinfo('/'):
if 'file' in item and 'album' in item:
album = mpdh.get(item, 'album')
artist = mpdh.get(item, 'artist', self.NOTAG)
@@ -857,14 +857,14 @@ def library_return_list_items(self, itemtype, genre=None, artist=None,
for song in songs:
items.append(mpdh.get(song, itemtype))
else:
- items = self.MPDH.call('list', itemtype, *s)
+ items = self.MPDH.list(itemtype, *s)
for item in items:
if len(item) > 0:
results.append(item)
else:
if genre is None and artist is None and album is None and year \
is None:
- for item in self.MPDH.call('list', itemtype):
+ for item in self.MPDH.list(itemtype):
if len(item) > 0:
results.append(item)
if ignore_case:
@@ -895,7 +895,7 @@ def library_return_count(self, genre=None, artist=None, album=None,
else:
- count = self.MPDH.call('count', *s)
+ count = self.MPDH.count(*s)
playtime += mpdh.get(count, 'playtime', 0, True)
num_songs += mpdh.get(count, 'songs', 0, True)
@@ -1016,7 +1016,7 @@ def library_return_search_items(self, genre=None, artist=None, album=None,
if len(args_tuple) == 0:
return None, 0, 0
- items = self.MPDH.call('search', *args_tuple)
+ items = self.MPDH.search(*args_tuple)
if items is not None:
for item in items:
if strip_type is None or (strip_type is not None and not \
@@ -1263,7 +1263,7 @@ def get_path_child_filenames(self, return_root, selected_only=True):
def library_get_path_files_recursive(self, path):
results = []
- for item in self.MPDH.call('lsinfo', path):
+ for item in self.MPDH.lsinfo(path):
if 'directory' in item:
results = results + self.library_get_path_files_recursive(
mpdh.get(item, 'directory'))
@@ -1373,8 +1373,8 @@ def libsearchfilter_do_search(self, searchby, todo):
if not self.prevlibtodo_base in todo:
# Do library search based on first two letters:
self.prevlibtodo_base = todo[:2]
- self.prevlibtodo_base_results = self.MPDH.call('search', searchby,
- self.prevlibtodo_base)
+ self.prevlibtodo_base_results = self.MPDH.search(searchby,
+ self.prevlibtodo_base)
subsearch = False
else:
subsearch = True
View
73 sonata/main.py
@@ -1092,17 +1092,17 @@ def _mpd_connect(self, _blocking, force):
return
self.trying_connection = True
if self.user_connect or force:
- self.MPDH.call('disconnect')
+ self.MPDH.disconnect()
host, port, password = misc.mpd_env_vars()
if not host:
host = self.config.host[self.config.profile_num]
if not port:
port = self.config.port[self.config.profile_num]
if not password:
password = self.config.password[self.config.profile_num]
- self.MPDH.call('connect', host, port)
+ self.MPDH.connect(host, port)
if len(password) > 0:
- self.MPDH.call('password', password)
+ self.MPDH.password(password)
test = self.MPDH.status()
if test:
self.conn = True
@@ -1121,8 +1121,8 @@ def _mpd_connect(self, _blocking, force):
def mpd_disconnect(self):
if self.conn:
- self.MPDH.call('close')
- self.MPDH.call('disconnect')
+ self.MPDH.close()
+ self.MPDH.disconnect()
self.conn = False
def on_connectkey_pressed(self, _event=None):
@@ -1411,14 +1411,14 @@ def on_add_item(self, _widget, play_after=False):
playid = self.status['playlistlength']
if self.current_tab == self.TAB_LIBRARY:
items = self.library.get_path_child_filenames(True)
- self.MPDH.call('command_list_ok_begin')
+ self.MPDH.command_list_ok_begin()
for item in items:
- self.MPDH.call('add', item)
- self.MPDH.call('command_list_end')
+ self.MPDH.add(item)
+ self.MPDH.command_list_end()
elif self.current_tab == self.TAB_PLAYLISTS:
model, selected = self.playlists_selection.get_selected_rows()
for path in selected:
- self.MPDH.call('load',
+ self.MPDH.load(
misc.unescape_html(
model.get_value(model.get_iter(path), 1)))
elif self.current_tab == self.TAB_STREAMS:
@@ -1431,9 +1431,9 @@ def on_add_item(self, _widget, play_after=False):
if self.status['random'] == '1':
# If we are in random mode, we want to play a random song
# instead:
- self.MPDH.call('play')
+ self.MPDH.play()
else:
- self.MPDH.call('play', int(playid))
+ self.MPDH.play(int(playid))
def add_selected_to_playlist(self, plname):
if self.current_tab == self.TAB_LIBRARY:
@@ -1443,10 +1443,10 @@ def add_selected_to_playlist(self, plname):
else:
raise Exception("This tab doesn't support playlists")
- self.MPDH.call('command_list_ok_begin')
+ self.MPDH.command_list_ok_begin()
for song in songs:
- self.MPDH.call('playlistadd', plname, song)
- self.MPDH.call('command_list_end')
+ self.MPDH.playlistadd(plname, song)
+ self.MPDH.command_list_end()
def stream_parse_and_add(self, item):
# We need to do different things depending on if this is
@@ -1476,7 +1476,7 @@ def stream_parse_and_add(self, item):
if f:
if misc.is_binary(f):
# Binary file, just add it:
- self.MPDH.call('add', item)
+ self.MPDH.add(item)
else:
if "[playlist]" in f:
# pls:
@@ -1489,10 +1489,10 @@ def stream_parse_and_add(self, item):
self.stream_parse_m3u(f)
else:
# Something else..
- self.MPDH.call('add', item)
+ self.MPDH.add(item)
else:
# Hopefully just a regular stream, try to add it:
- self.MPDH.call('add', item)
+ self.MPDH.add(item)
def stream_parse_pls(self, f):
lines = f.split("\n")
@@ -1502,18 +1502,18 @@ def stream_parse_pls(self, f):
if delim > 0:
line = line[delim:]
if len(line) > 7 and line[0:7] == 'http://':
- self.MPDH.call('add', line)
+ self.MPDH.add(line)
elif len(line) > 6 and line[0:6] == 'ftp://':
- self.MPDH.call('add', line)
+ self.MPDH.add(line)
def stream_parse_m3u(self, f):
lines = f.split("\n")
for line in lines:
line = line.replace('\r', '')
if len(line) > 7 and line[0:7] == 'http://':
- self.MPDH.call('add', line)
+ self.MPDH.add(line)
elif len(line) > 6 and line[0:6] == 'ftp://':
- self.MPDH.call('add', line)
+ self.MPDH.add(line)
def on_replace_item_play(self, widget):
self.on_replace_item(widget, True)
@@ -2226,7 +2226,7 @@ def mpd_shuffle(self, _action):
ui.change_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH))
while gtk.events_pending():
gtk.main_iteration()
- self.MPDH.call('shuffle')
+ self.MPDH.shuffle()
def on_menu_popup(self, _widget):
self.update_menu_visibility()
@@ -2886,29 +2886,29 @@ def on_volume_raise(self, _action):
self.volumebutton.set_value(new_volume)
def on_volume_change(self, _button, new_volume):
- self.MPDH.call('setvol', int(new_volume))
+ self.MPDH.setvol(int(new_volume))
def mpd_pp(self, _widget, _key=None):
if self.conn and self.status:
if self.status['state'] in ('stop', 'pause'):
- self.MPDH.call('play')
+ self.MPDH.play()
elif self.status['state'] == 'play':
- self.MPDH.call('pause', '1')
+ self.MPDH.pause('1')
self.iterate_now()
def mpd_stop(self, _widget, _key=None):
if self.conn:
- self.MPDH.call('stop')
+ self.MPDH.stop()
self.iterate_now()
def mpd_prev(self, _widget, _key=None):
if self.conn:
- self.MPDH.call('previous')
+ self.MPDH.previous()
self.iterate_now()
def mpd_next(self, _widget, _key=None):
if self.conn:
- self.MPDH.call('next')
+ self.MPDH.next()
self.iterate_now()
def on_remove(self, _widget):
@@ -2932,9 +2932,8 @@ def on_remove(self, _widget):
gtk.RESPONSE_YES:
iters = [model.get_iter(path) for path in selected]
for i in iters:
- self.MPDH.call('rm',
- misc.unescape_html(
- self.playlistsdata.get_value(i, 1)))
+ self.MPDH.rm(misc.unescape_html(
+ self.playlistsdata.get_value(i, 1)))
self.playlists.populate()
elif self.current_tab == self.TAB_STREAMS:
treeviewsel = self.streams_selection
@@ -2977,7 +2976,7 @@ def on_remove(self, _widget):
def mpd_clear(self, _widget):
if self.conn:
- self.MPDH.call('clear')
+ self.MPDH.clear()
self.iterate_now()
def _toggle_clicked(self, command, widget):
@@ -3087,14 +3086,14 @@ def prefs_infofile_changed(self, entry, _event):
def prefs_crossfade_changed(self, crossfade_spin):
crossfade_value = crossfade_spin.get_value_as_int()
- self.MPDH.call('crossfade', crossfade_value)
+ self.MPDH.crossfade(crossfade_value)
def prefs_crossfade_toggled(self, button, crossfade_spin):
crossfade_value = crossfade_spin.get_value_as_int()
if button.get_active():
- self.MPDH.call('crossfade', crossfade_value)
+ self.MPDH.crossfade(crossfade_value)
else:
- self.MPDH.call('crossfade', 0)
+ self.MPDH.crossfade(0)
def prefs_playback_toggled(self, button):
self.config.show_playback = button.get_active()
@@ -3186,7 +3185,7 @@ def prefs_trayicon_toggled(self, button, minimize):
self.tray_icon.hide()
def seek(self, song, seektime):
- self.MPDH.call('seek', song, seektime)
+ self.MPDH.seek(song, seektime)
self.iterate_now()
def on_link_click(self, linktype):
@@ -3494,7 +3493,7 @@ def on_about(self, _action):
stats = None
if self.conn:
# Extract some MPD stats:
- mpdstats = self.MPDH.call('stats')
+ mpdstats = self.MPDH.stats()
stats = {'artists': mpdstats['artists'],
'albums': mpdstats['albums'],
'songs': mpdstats['songs'],
View
24 sonata/mpdhelper.py
@@ -1,4 +1,5 @@
+import functools
import locale
import sys
import os
@@ -8,12 +9,20 @@
class MPDHelper(object):
def __init__(self, client):
- self.client = client
+ self._client = client
self.suppress_error = False
+ def __getattr__(self, attr):
+ """Catch-all for methods with no special implementation."""
+ # XXX we still pass through the .call() method, since the original code
+ # expected this, and this method does some additionnal postprocessing in
+ # case of error. If .call() is cleaned up, maybe we can somehow merge
+ # .__getattr__() and .call() together.
+ return functools.partial(self.call, attr)
+
def call(self, command, *args):
try:
- retval = getattr(self.client, command)(*args)
+ retval = getattr(self._client, command)(*args)
except:
# XXX make the distinction between bad getattr() call and bad MPD
# call?
@@ -32,6 +41,7 @@ def call(self, command, *args):
def status(self):
result = self.call('status')
+ # XXX why we return different things here?
if result and 'state' in result:
return result
else:
@@ -46,7 +56,7 @@ def version(self):
# another server (or the same, upgraded). We should compute this once,
# after the initial client connection.
try:
- version = getattr(self.client, "mpd_version", "0.0")
+ version = getattr(self._client, "mpd_version", "0.0")
return version.split(".")
except:
# XXX what exception are we expecting here!?
@@ -76,12 +86,12 @@ def update(self, paths):
dirs = remove_list_duplicates(dirs, True)
if len(dirs) > 32 and self.version >= (0, 14):
- self.client.update('/')
+ self._client.update('/')
else:
- self.client.command_list_ok_begin()
+ self._client.command_list_ok_begin()
for directory in dirs:
- self.client.update(directory)
- self.client.command_list_end()
+ self._client.update(directory)
+ self._client.command_list_end()
def get(mapping, key, alt='', *sanitize_args):
View
18 sonata/playlists.py
@@ -130,15 +130,15 @@ def on_playlist_save(self, _action):
'savePlaylistError', plname):
return
self.playlist_create(plname)
- self.MPDH.call('playlistclear', plname)
+ self.MPDH.playlistclear(plname)
self.add_selected_to_playlist(plname)
def playlist_create(self, playlistname, oldname=None):
- self.MPDH.call('rm', playlistname)
+ self.MPDH.rm(playlistname)
if oldname is not None:
- self.MPDH.call('rename', oldname, playlistname)
+ self.MPDH.rename(oldname, playlistname)
else:
- self.MPDH.call('save', playlistname)
+ self.MPDH.save(playlistname)
self.populate()
self.iterate_now()
@@ -154,7 +154,7 @@ def on_playlist_menu_click(self, action):
default=self.config.existing_playlist_option)
if response == 1: # Overwrite
self.config.existing_playlist_option = response
- self.MPDH.call('playlistclear', plname)
+ self.MPDH.playlistclear(plname)
self.add_selected_to_playlist(plname)
elif response == 2: # Append songs:
self.config.existing_playlist_option = response
@@ -163,9 +163,9 @@ def on_playlist_menu_click(self, action):
def playlist_name_exists(self, title, role, plname, skip_plname=""):
# If the playlist already exists, and the user does not want to
# replace it, return True; In all other cases, return False
- playlists = self.MPDH.call('listplaylists')
+ playlists = self.MPDH.listplaylists()
if playlists is None:
- playlists = self.MPDH.call('lsinfo')
+ playlists = self.MPDH.lsinfo()
for item in playlists:
if 'playlist' in item:
if mpdh.get(item, 'playlist') == plname and \
@@ -210,9 +210,9 @@ def populate(self):
if self.connected():
self.playlistsdata.clear()
playlistinfo = []
- playlists = self.MPDH.call('listplaylists')
+ playlists = self.MPDH.listplaylists()
if playlists is None:
- playlists = self.MPDH.call('lsinfo')
+ playlists = self.MPDH.lsinfo()
for item in playlists:
if 'playlist' in item:
playlistinfo.append(misc.escape_html(mpdh.get(item,

0 comments on commit d0b4fd4

Please sign in to comment.