File: quodlibet.py

package info (click to toggle)
quodlibet 2.4-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 5,004 kB
  • sloc: python: 26,934; ansic: 596; makefile: 2
file content (361 lines) | stat: -rwxr-xr-x 13,175 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright 2004-2005 Joe Wreschnig, Michael Urman, IƱigo Serna
# <quod-libet-development@googlegroups.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.

import os
import signal
import sys
import tempfile

import quodlibet

from quodlibet import config
from quodlibet import const
from quodlibet import util
from quodlibet.util.uri import URI

play = False

def main():
    import quodlibet.player

    config.init(const.CONFIG)

    library = quodlibet.init(library=const.LIBRARY,
                             icon="quodlibet",
                             name="Quod Libet",
                             title=const.PROCESS_TITLE_QL)

    os.environ["PULSE_PROP_media.role"] = "music"
    os.environ["PULSE_PROP_application.icon_name"] = "quodlibet"

    for backend in [config.get("player", "backend"), "nullbe"]:
        try:
            player = quodlibet.init_backend(backend, library.librarian)
        except quodlibet.player.error, error:
            print_e("%s. %s" % (error.short_desc, error.long_desc))
        else:
            break

    from quodlibet import browsers
    from quodlibet.qltk.songlist import SongList

    try: ratings = config.getint("settings", "ratings")
    except (ValueError, TypeError): pass
    else: util.RATING_PRECISION = 1.0/ratings

    try: default_rating = config.getfloat("settings", "default_rating")
    except (ValueError, TypeError): pass
    else: const.DEFAULT_RATING = default_rating

    if config.get("settings", "headers").split() == []:
       config.set("settings", "headers", "title")
    headers = config.get("settings", "headers").split()
    SongList.set_all_column_headers(headers)

    for opt in config.options("header_maps"):
        val = config.get("header_maps", opt)
        util.tags.add(opt, val)

    in_all =("~filename ~uri ~#lastplayed ~#rating ~#playcount ~#skipcount "
             "~#added ~#bitrate ~current ~#laststarted ~basename "
             "~dirname").split()
    for Kind in browsers.browsers:
        if Kind.headers is not None: Kind.headers.extend(in_all)
        Kind.init(library)

    window = init_plugins(player, library)

    from quodlibet.qltk.remote import FSInterface, FIFOControl
    from quodlibet.qltk.tracker import SongTracker
    try:
        from quodlibet.qltk.dbus_ import DBusHandler
    except ImportError:
        DBusHandler = lambda player, library: None

    FSInterface(player)
    FIFOControl(library, window, player)
    DBusHandler(player, library)
    SongTracker(library.librarian, player, window.playlist)

    if play:
        player.paused = False

    quodlibet.enable_periodic_save(save_library=True)

    from quodlibet.qltk import session
    session.init("quodlibet", window)

    quodlibet.main(window)

    print_d("Shutting down player device %r." % player.version_info)
    quodlibet.player.quit(player)

    quodlibet.library.save(force=True)
    config.save(const.CONFIG)

    print_d("Finished shutdown.")

def init_plugins(player, library):
    from quodlibet.plugins.editing import EditingPlugins
    from quodlibet.plugins.songsmenu import SongsMenuPlugins
    from quodlibet.plugins.events import EventPlugins
    from quodlibet.plugins.playorder import PlayOrderPlugins
    from quodlibet.qltk.songsmenu import SongsMenu
    from quodlibet.qltk.properties import SongProperties
    from quodlibet import widgets

    widgets.watcher = library.librarian

    SongsMenu.plugins = SongsMenuPlugins(
        [os.path.join(const.BASEDIR, "plugins", "songsmenu"),
         os.path.join(const.USERDIR, "plugins", "songsmenu")], "songsmenu")
    SongsMenu.plugins.rescan()

    SongProperties.plugins = EditingPlugins(
        [os.path.join(const.BASEDIR, "plugins", "editing"),
         os.path.join(const.USERDIR, "plugins", "editing")], "editing")

    playorder = PlayOrderPlugins(
        [os.path.join(const.BASEDIR, "plugins", "playorder"),
         os.path.join(const.USERDIR, "plugins", "playorder")], "playorder")
    playorder.rescan()

    # main window
    from quodlibet.qltk.quodlibetwindow import QuodLibetWindow
    window = QuodLibetWindow(library, player)
    widgets.main = window

    events = EventPlugins(library.librarian, player, [
        os.path.join(const.BASEDIR, "plugins", "events"),
        os.path.join(const.USERDIR, "plugins", "events")], "events")
    events.rescan()

    for p in [playorder, SongsMenu.plugins, SongProperties.plugins, events]:
        window.connect('destroy', p.destroy)

    return window

def print_fifo(command):
    if not os.path.exists(const.CURRENT):
        raise SystemExit("not-running")
    else:
        fd, filename = tempfile.mkstemp()
        try:
            os.unlink(filename)
            # mkfifo fails if the file exists, so this is safe.
            os.mkfifo(filename, 0600)

            signal.signal(signal.SIGALRM, lambda: "" + 2)
            signal.alarm(1)
            f = file(const.CONTROL, "w")
            signal.signal(signal.SIGALRM, signal.SIG_IGN)
            f.write(command + " " + filename)
            f.close()

            f = file(filename, "r")
            sys.stdout.write(f.read())
            try: os.unlink(filename)
            except EnvironmentError: pass
            f.close()
            raise SystemExit
        except TypeError:
            try: os.unlink(filename)
            except EnvironmentError: pass
            raise SystemExit("not-running")

def print_playing(fstring="<artist~album~tracknumber~title>"):
    from quodlibet.formats._audio import AudioFile
    from quodlibet.parse import Pattern

    try:
        text = open(const.CURRENT, "rb").read()
        song = AudioFile()
        song.from_dump(text)
        print_(Pattern(fstring).format(song))
        raise SystemExit
    except (OSError, IOError):
        print_(_("No song is currently playing."))
        raise SystemExit(True)

def print_query(query):
    '''Queries library, dumping filenames of matches to stdout

        See Issue 716
    '''
    print_d("Querying library for %r" %query)
    import quodlibet.library
    library = quodlibet.library.init(const.LIBRARY)
    songs = library.query(query)
    #songs.sort()
    sys.stdout.write("\n".join([song("~filename") for song in songs]) + "\n")
    raise SystemExit

def isrunning():
    return os.path.exists(const.CONTROL)

def control(c):
    if not isrunning():
        raise SystemExit(_("Quod Libet is not running."))
    else:
        try:
            # This is a total abuse of Python! Hooray!
            signal.signal(signal.SIGALRM, lambda: "" + 2)
            signal.alarm(1)
            f = file(const.CONTROL, "w")
            signal.signal(signal.SIGALRM, signal.SIG_IGN)
            f.write(c)
            f.close()
        except (OSError, IOError, TypeError):
            print_w(_("Unable to write to %s. Removing it.") % const.CONTROL)
            try: os.unlink(const.CONTROL)
            except OSError: pass
            if c != 'focus':
                raise SystemExit(True)
        else:
            raise SystemExit

def process_arguments():
    controls = ["next", "previous", "play", "pause", "play-pause",
                "hide-window", "show-window", "toggle-window",
                "focus", "quit", "unfilter", "refresh", "force-previous"]
    controls_opt = ["seek", "order", "repeat", "query", "volume", "filter",
                    "set-rating", "set-browser", "open-browser", "random",
                    "song-list", "queue"]

    options = util.OptionParser(
        "Quod Libet", const.VERSION,
        _("a music library and player"),
        _("[option]"))

    options.add("print-playing", help=_("Print the playing song and exit"))
    options.add("start-playing", help=_("Begin playing immediately"))

    for opt, help in [
        ("next", _("Jump to next song")),
        ("previous",
            _("Jump to previous song or restart if near the beginning")),
        ("force-previous", _("Jump to previous song")),
        ("play", _("Start playback")),
        ("pause", _("Pause playback")),
        ("play-pause", _("Toggle play/pause mode")),
        ("volume-up", _("Turn up volume")),
        ("volume-down", _("Turn down volume")),
        ("status", _("Print player status")),
        ("hide-window", _("Hide main window")),
        ("show-window", _("Show main window")),
        ("toggle-window", _("Toggle main window visibility")),
        ("focus", _("Focus the running player")),
        ("unfilter", _("Remove active browser filters")),
        ("refresh", _("Refresh and rescan library")),
        ("print-playlist", _("Print the current playlist")),
        ("print-queue", _("Print the contents of the queue")),
        ("quit", _("Exit Quod Libet")),
        ]: options.add(opt, help=help)

    for opt, help, arg in [
        ("seek", _("Seek within the playing song"), _("[+|-][HH:]MM:SS")),
        ("order", _("Set or toggle the playback order"),
            "[order]|toggle"),
        ("repeat", _("Turn repeat off, on, or toggle it"), "0|1|t"),
        ("volume", _("Set the volume"), "(+|-|)0..100"),
        ("query", _("Search your audio library"), _("query")),
        ("play-file", _("Play a file"), Q_("command|filename")),
        ("set-rating", _("Rate the playing song"), "0.0..1.0"),
        ("set-browser", _("Set the current browser"), "BrowserName"),
        ("open-browser", _("Open a new browser"), "BrowserName"),
        ("queue", _("Show or hide the queue"), "on|off|t"),
        ("song-list", _("Show or hide the main song list"), "on|off|t"),
        ("random", _("Filter on a random value"), Q_("command|tag")),
        ("filter", _("Filter on a tag value"), _("tag=value")),
        ("enqueue", _("Enqueue a file or query"), "%s|%s" % (
            Q_("command|filename"), _("query"))),
        ("enqueue-files", _("Enqueue comma-separated files"), "%s[,%s..]" % (
            _("filename"), _("filename"))),
        ("print-query", _("Print filenames of results of query to stdout"), 
            _("query")),
        ("unqueue", _("Unqueue a file or query"), "%s|%s" % (
            Q_("command|filename"), _("query"))),
        ]: options.add(opt, help=help, arg=arg)

    options.add("sm-config-prefix", arg="dummy")
    options.add("sm-client-id", arg="prefix")
    options.add("screen", arg="dummy")

    def is_vol(str):
        if str[0] in '+-':
            if len(str) == 1: return True
            str = str[1:]
        return str.isdigit()
    def is_time(str):
        if str[0] not in "+-0123456789": return False
        elif str[0] in "+-": str = str[1:]
        parts = str.split(":")
        if len(parts) > 3: return False
        else: return not (False in [p.isdigit() for p in parts])
    def is_float(str):
        try: float(str)
        except ValueError: return False
        else: return True

    validators = {
        "order": ["0", "1", "t", "toggle", "inorder", "shuffle",
                  "weighted", "onesong"].__contains__,
        "repeat": ["0", "1", "t", "on", "off", "toggle"].__contains__,
        "volume": is_vol,
        "seek": is_time,
        "set-rating": is_float,
        }

    opts, args = options.parse()
    for command, arg in opts.items():
        if command in controls: control(command)
        elif command in controls_opt:
            if command in validators and not validators[command](arg):
                print_e(_("Invalid argument for '%s'.") % command)
                print_e(_("Try %s --help.") % sys.argv[0])
                raise SystemExit(True)
            else: control(command + " " + arg)
        elif command == "status": print_fifo("status")
        elif command == "print-playlist": print_fifo("dump-playlist")
        elif command == "print-queue": print_fifo("dump-queue")
        elif command == "volume-up": control("volume +")
        elif command == "volume-down": control("volume -")
        elif command == "enqueue" or command == "unqueue":
            try:
                filename = URI(arg).filename
            except ValueError:
                filename = arg
            control(command + " " + filename)
        elif command == "enqueue-files":
            control(command + " " + arg)
        elif command == "play-file":
            try:
                filename = URI(arg).filename
            except ValueError:
                filename = os.path.abspath(util.expanduser(arg))
            if os.path.isdir(filename): control("add-directory " + filename)
            else: control("add-file " + filename)
        elif command == "print-playing":
            try: print_playing(args[0])
            except IndexError: print_playing()
        elif command == "print-query":
            print_query(arg)
        elif command == "start-playing":
            global play
            play = True

if __name__ == "__main__":
    quodlibet._init_signal()

    process_arguments()
    if isrunning() and not quodlibet.const.DEBUG:
        print_(_("Quod Libet is already running."))
        control('focus')
    main()