#!/usr/bin/env python3 import gi, sys, os, mutagen, base64, json gi.require_version('Gtk', '3.0') from gi.repository import Gtk, Gdk, GLib, GdkPixbuf, GObject class PreferencesWindow(Gtk.Dialog): def __init__(self, app, mpd): Gtk.Dialog.__init__(self, title = "Sonist 基础设置") self.set_default_size(464, 320) self.app = app self.mpd = mpd self.layout = self.get_content_area() config = app.config_data grid = Gtk.Grid(column_spacing = 8, row_spacing = 16) txt1 = Gtk.Label('MPD地址: ') txt2 = Gtk.Label('MPD端口: ') txt3 = Gtk.Label('音乐目录: ') txt4 = Gtk.Label('更新数据库: ') txt5 = Gtk.Label(' 重新扫描会清空播放列表并停止播放') txt6 = Gtk.Label('当前歌曲数: ') txt7 = Gtk.Label('0 首') input1 = Gtk.Entry(placeholder_text = '默认 127.0.0.1') input2 = Gtk.SpinButton.new_with_range(min = 1024, max = 65535, step = 1) input3 = Gtk.Entry(placeholder_text = '默认读取 $HOME/.mpd/mpd.conf 中定义的目录') btn = Gtk.Button(label = '重新扫描并重建播放列表') btn.connect('clicked', self.scan_music) input1.set_size_request(312, -1) input1.set_text(config['host']) input2.set_value(config['port']) input3.set_text(config['music_directory']) grid.attach(txt1, 0, 0, 1, 1) grid.attach(input1, 2, 0, 1, 1) grid.attach(txt2, 0, 1, 1, 1) grid.attach(input2, 2, 1, 1, 1) grid.attach(txt3, 0, 2, 1, 1) grid.attach(input3, 2, 2, 1, 1) grid.attach(txt4, 0, 3, 1, 1) box = Gtk.Box() box.add(btn) grid.attach(box, 2, 3, 1, 1) grid.attach(txt6, 0, 4, 1, 1) grid.attach(txt7, 2, 4, 1, 1) self.scan_result = txt7 self.host_input = input1 self.port_input = input2 self.dir_input = input3 self.scan_input = btn self.layout.set_border_width(32) self.layout.add(grid) self.add_button('关闭', 0) self.add_button('保存', 1) self.set_keep_above(True) self.connect("response", self.on_button_clicked) mpd.connect('online', lambda o: self.get_mpd_music()) def get_mpd_music(self, force = False): res = self.mpd.stats() tips = '扫描完成... 共' if force else '' self.scan_result.set_text(f"{tips}{res.get('songs')} 首") def scan_music(self, btn): need_resume = self.mpd.status().get('state') == 'play' self.mpd.update() self.mpd.stop() self.mpd.clear() songs = self.mpd.listall() for it in songs: self.mpd.add(it['file']) self.get_mpd_music(True) if need_resume: self.mpd.play() def show(self): if self.mpd.connected: self.get_mpd_music() else: self.scan_result.set_text("MPD 未运行...") self.show_all() self.run() def on_button_clicked(self, dialog, res): data = {} # 1 为保存按钮 if res == 1: data['host'] = self.host_input.get_text() data['port'] = int(self.port_input.get_value()) data['music_directory'] = self.dir_input.get_text() self.app.config_data = data with open(self.app.config_file, 'w') as f: buff = json.dumps(data) f.write(buff) self.hide()