#!/usr/bin/python
#Filename:<>

from PyQt4 import QtCore,QtGui
import sys

try:
    import psyco
    psyco.full()
except:
    pass

class Player( QtCore.QObject ):
    def __init__(self, wid):
        QtCore.QObject.__init__(self)
        self.opt_list = ()
        self.opt_list = ['/home/haha/eyes.mpeg', '-wid', str(wid), '-ao', 'null', '-slave', '-quiet']
        self.proc = QtCore.QProcess()

    def go(self):
        self.connect(self.proc, QtCore.SIGNAL('readyReadStandardOutput()'), self._clear_mp_buff)
        self.connect(self.proc, QtCore.SIGNAL('finished(int)'), self.test)
        self.proc.start('mplayer', self.opt_list)

    def pause(self):
        self.proc.writeData('pause\n')

    def stop(self):
        self.proc.close()

    def test(self, argv):
        if argv == 0 or argv == 1:
            print 'received finished state:', argv
            self.proc.close()
        else:
            print 'unknow finished state:', argv

    def _clear_mp_buff(self):
        self.proc.readAllStandardOutput()

class Main( QtGui.QWidget ):
    def __init__(self):
        QtGui.QWidget.__init__(self)

        self.frame = QtGui.QFrame(self)
        self.btn_frame = QtGui.QFrame(self.frame)
        self.btn_layout = QtGui.QHBoxLayout(self.btn_frame)

        self.setup_btn(['play', 'stop', 'quit', 'pause'])
        self.container = QtGui.QX11EmbedContainer(self.frame)
        self.container.setGeometry(0, 50, 320, 320)
        self.player = Player(self.container.winId())

        self.frame.resize(480, 320)

    def setup_btn(self, btn_list):
        btn_list.reverse()
        while True:
            if len(btn_list) == 0:
                break
            else:
                btn = btn_list.pop()
                setattr(self, btn, QtGui.QPushButton(btn, self.btn_frame))
                self.connect(getattr(self, btn), QtCore.SIGNAL('clicked()'), getattr(self, btn+'_func', self.func_todo))
                self.btn_layout.addWidget(getattr(self, btn))

    def stop_func(self):
        self.player.stop()

    def play_func(self):
        self.player.go()

    def quit_func(self):
        self.player.stop()
        QtGui.qApp.quit()

    def pause_func(self):
        self.player.pause()

    def func_todo(self):
        QtGui.QMessageBox.information(self, 'WujiMaji', 'the function is NOT available now')

    def closeEvent(self, event):
        self.player.stop()


################
# main routine #
################
if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    main = Main()
    main.show()
    app.exec_()
