def write(self): fn = self.filename with open(fn, "wb") as f: for song in self._list: if isinstance(song, string_types): f.write(fsn2bytes(song, "utf-8") + b"\n") else: f.write(fsn2bytes(song("~filename"), "utf-8") + b"\n") if self._last_fn != fn: self.__delete_file(self._last_fn) self._last_fn = fn
def send_message(cls, message): assert isinstance(message, fsnative) try: return fifo.write_fifo(cls._PATH, fsn2bytes(message, None)) except EnvironmentError as e: raise RemoteError(e)
def test_bytes2fsn(): assert bytes2fsn(b"foo", "utf-8") == fsnative(u"foo") assert (bytes2fsn(fsn2bytes(fsnative(u"\u1234"), "utf-8"), "utf-8") == fsnative(u"\u1234")) with pytest.raises(ValueError): bytes2fsn(b"\x00", "utf-8") with pytest.raises(ValueError): bytes2fsn(b"\x00\x00", "utf-16-le") with pytest.raises(TypeError): bytes2fsn(object(), "utf-8") with pytest.raises(TypeError): bytes2fsn(u"data", "utf-8") if os.name == "nt": with pytest.raises(ValueError): bytes2fsn(b"data", "notanencoding") with pytest.raises(ValueError): bytes2fsn(b"data", None) with pytest.raises(TypeError): bytes2fsn(b"data", object()) assert bytes2fsn(b"foo", "utf-8") == bytes2fsn(b"foo")
def fsn2glib(path): """Takes a fsnative path and returns a glib filename""" if PY2: return fsn2bytes(path, "utf-8") else: return path
def test_response(self): with temp_filename() as fn: mock = Mock(resp=bytes2fsn(b"resp", None)) remote = QuodLibetUnixRemote(None, mock) remote._callback(b"\x00foo\x00" + fsn2bytes(fn, None) + b"\x00") self.assertEqual(mock.lines, [bytes2fsn(b"foo", None)]) with open(fn, "rb") as h: self.assertEqual(h.read(), b"resp")
def selection_set_songs(selection_data, songs): """Stores filenames of the passed songs in a Gtk.SelectionData""" filenames = [] for filename in (song["~filename"] for song in songs): filenames.append(fsn2bytes(filename, "utf-8")) type_ = Gdk.atom_intern("text/x-quodlibet-songs", True) selection_data.set(type_, 8, b"\x00".join(filenames))
def test_selection_set_songs(self): song = AudioFile() song["~filename"] = fsnative(u"foo") sel = MockSelData() qltk.selection_set_songs(sel, [song]) assert sel.data == fsn2bytes(fsnative(u"foo"), "utf-8") assert qltk.selection_get_filenames(sel) == [fsnative(u"foo")]
def get_devices_from_path(udev_ctx, path): """A list of device attribute dicts for the given device path and all its parents. Either returns a non empty list or raises EnvironmentError. """ path = fsn2bytes(path2fsn(path), None) enum = udev.UdevEnumerate.new(udev_ctx) if not enum: raise EnvironmentError # only match the device we want if enum.add_match_property(b"DEVNAME", path) != 0: enum.unref() raise EnvironmentError # search for it if enum.scan_devices() != 0: enum.unref() raise EnvironmentError # take the first entry entry = enum.get_list_entry() if not entry: enum.unref() raise EnvironmentError sys_path = entry.get_name() enum.unref() device = udev.UdevDevice.new_from_syspath(udev_ctx, sys_path) if not device: raise EnvironmentError devices = [] while device: devices.append(device) device = device.get_parent() device_attrs = [] for device in devices: entry = device.get_properties_list_entry() if not entry: continue attrs = {} for e in entry: name = e.get_name() value = e.get_value() attrs[name] = escape_decode(value) device_attrs.append(attrs) # the first device owns its parents devices[0].unref() return device_attrs
def set_current_dir(path): """Set the current chooser directory. Args: path (fsnative) """ assert isinstance(path, fsnative) data = fsn2bytes(path, "utf-8") config.setbytes("memory", "chooser_dir", data)
def _on_selection_changed(self, tree_selection): model, rows = tree_selection.get_selected_rows() selected_paths = [model[row][0] for row in rows] if selected_paths: data = fsn2bytes("\n".join(selected_paths), "utf-8") else: data = b"" config.setbytes("browsers", "filesystem", data)
def test_main(self): v = fsnative(u"foo") self.assertTrue(isinstance(v, fsnative)) v2 = glib2fsn(fsn2glib(v)) self.assertTrue(isinstance(v2, fsnative)) self.assertEqual(v, v2) v3 = bytes2fsn(fsn2bytes(v, "utf-8"), "utf-8") self.assertTrue(isinstance(v3, fsnative)) self.assertEqual(v, v3)
def test_parse_onesong(self): with temp_filename() as name: with open(name, "wb") as af: target = self.prefix target += fsn2bytes(get_data_path("silence-44-s.ogg"), "utf-8") af.write(target) with open(name, "rb") as f: pl = self.Parse(f, name) self.failUnlessEqual(len(pl), 1) self.failUnlessEqual(pl[0]("title"), "Silence") pl.delete()
def test_parse_onesong(self): h, name = mkstemp() os.close(h) with open(name, "wb") as f: target = self.prefix target += fsn2bytes(get_data_path("silence-44-s.ogg"), "utf-8") f.write(target) list = self.Parse(name) os.unlink(name) self.failUnlessEqual(len(list), 1) self.failUnlessEqual(list[0]("title"), "Silence") list.delete()
def __write(self, widget, model): filenames = [row[0]["~filename"] for row in model] try: with open(QUEUE, "wb") as f: for filename in filenames: try: line = fsn2bytes(filename, "utf-8") except ValueError: print_exc() continue f.write(line + b"\n") except EnvironmentError: print_exc()
def set_scan_dirs(dirs): """Saves a list of fs paths which should be scanned Args: list """ assert all(isinstance(d, fsnative) for d in dirs) if is_windows(): joined = fsnative(u":").join(dirs) else: joined = join_escape(dirs, fsnative(u":")) config.setbytes("settings", "scan", fsn2bytes(joined, "utf-8"))
def _py3_to_py2(items): is_win = is_windows() new_list = [] for i in items: inst = dict.__new__(i.__class__) for key, value in i.items(): if key in ("~filename", "~mountpoint") and not is_win: value = fsn2bytes(value, None) try: key = key.encode("ascii") except UnicodeEncodeError: pass dict.__setitem__(inst, key, value) new_list.append(inst) return new_list
def _normalize_darwin_path(filename, canonicalise=False): filename = path2fsn(filename) if canonicalise: filename = os.path.realpath(filename) filename = os.path.normpath(filename) data = fsn2bytes(filename, "utf-8") decoded = data.decode("utf-8", "quodlibet-osx-path-decode") try: return bytes2fsn( NSString.fileSystemRepresentation(decoded), "utf-8") except ValueError: return filename
def _callback(self, data): try: messages = list(fifo.split_message(data)) except ValueError: print_w("invalid message: %r" % data) return for command, path in messages: command = bytes2fsn(command, None) response = self._cmd_registry.handle_line(self._app, command) if path is not None: path = bytes2fsn(path, None) with open(path, "wb") as h: if response is not None: assert isinstance(response, fsnative) h.write(fsn2bytes(response, None))
def export_metadata(songs, target_path): """Raises OSError/IOError""" with open(target_path, 'wb') as out: for song in songs: out.write(fsn2bytes(song('~basename'), "utf-8")) out.write(os.linesep.encode("utf-8")) for key in sorted(song.keys()): if key.startswith('~'): continue for val in song.list(key): line = '%s=%s' % (key, val) out.write(line.encode("utf-8")) out.write(os.linesep.encode("utf-8")) out.write(os.linesep.encode("utf-8"))
def write_fifo(fifo_path, data): """Writes the data to the FIFO and returns a response. Args: fifo_path (pathlike) data (bytes) Returns: bytes Raises: EnvironmentError: In case of timeout and other errors """ assert isinstance(data, bytes) fd, filename = mkstemp() try: os.close(fd) os.unlink(filename) # mkfifo fails if the file exists, so this is safe. os.mkfifo(filename, 0o600) _write_fifo( fifo_path, b"\x00" + data + b"\x00" + fsn2bytes(filename, None) + b"\x00") try: signal.signal(signal.SIGALRM, lambda: "" + 2) signal.alarm(FIFO_TIMEOUT) with open(filename, "rb") as h: signal.signal(signal.SIGALRM, signal.SIG_IGN) return h.read() except TypeError: # In case the main instance deadlocks we can write to it, but # reading will time out. Assume it is broken and delete the # fifo. try: os.unlink(fifo_path) except OSError: pass raise EnvironmentError("timeout") finally: try: os.unlink(filename) except EnvironmentError: pass
def parse_command(line): """Parses a MPD command (without trailing newline) Returns (command, [arguments]) or raises ParseError in case of an error. """ assert isinstance(line, bytes) parts = re.split(b"[ \\t]+", line, maxsplit=1) if not parts: raise ParseError("empty command") command = parts[0] if len(parts) > 1: lex = shlex.shlex(bytes2fsn(parts[1], "utf-8"), posix=True) lex.whitespace_split = True lex.commenters = "" lex.quotes = "\"" lex.whitespace = " \t" args = [fsn2bytes(a, "utf-8") for a in lex] else: args = [] try: command = command.decode("utf-8") except ValueError as e: raise ParseError(e) dec_args = [] for arg in args: try: arg = arg.decode("utf-8") except ValueError as e: raise ParseError(e) dec_args.append(arg) return command, dec_args
def fsnative2glib(path): if PY2: return fsn2bytes(path, "utf-8") else: return path
def send_message(cls, message): data = fsn2bytes(path2fsn(message), "utf-8") try: winpipe.write_pipe(cls._NAME, data) except EnvironmentError as e: raise RemoteError(e)
def fsnative2bytes(path): return fsn2bytes(path, "utf-8")