# -*- coding:latin-1 -*-

import os
import sys
import time
import cPickle
import base64
import atexit

from PySide import QtCore, QtGui

from Code.Traducir import *
import Code.MotorInterno as MotorInterno

import Code.ControlPosicion as ControlPosicion
import Code.Partida as Partida
import Code.Util as Util

import Code.QT.Iconos as Iconos
import Code.QT.Controles as Controles
import Code.QT.Colocacion as Colocacion
import Code.QT.QTUtil as QTUtil


#==========================================================================================================================================
CONFIGURACION = "C"
FEN = "F"
TERMINAR = "T"
#==========================================================================================================================================

#==========================================================================================================================================
class Ventana( QtGui.QDialog ) :

    def __init__( self, cpu ) :
        QtGui.QDialog.__init__(self)

        self.cpu = cpu
        self.ficheroVideo = cpu.ficheroVideo
        self.motor = None

        self.liData = []
        self.almFEN = {}

        self.fen = ""

        self.setWindowTitle( cpu.titulo )
        self.setWindowIcon( Iconos.Motor() )
        flags = QtCore.Qt.Dialog | QtCore.Qt.WindowTitleHint | QtCore.Qt.WindowMinimizeButtonHint | QtCore.Qt.WindowMaximizeButtonHint| QtCore.Qt.WindowStaysOnTopHint
        self.setWindowFlags( flags )

        self.setBackgroundRole(QtGui.QPalette.Light)
        self.setStyleSheet( "QTextEdit { background-color: rgb( 250,250,250); }" )

        self.em = Controles.EM(self).soloLectura()
        liAcciones = (
                        ( tr("TB_TERMINAR"), Iconos.Mosca_Terminar(), "terminar"),
                        ( tr("MOSCA_CONTINUAR"), Iconos.Mosca_Continuar(), "play"),
                        ( tr("MOSCA_PARAR"), Iconos.Mosca_Pausa(), "pause"),
                        ( tr("MOSCA_PORTAPAPELES"), Iconos.MoverGrabar(), "portapapelesUltJug"),
                        ( tr("ANALIZAR_COLOR"), Iconos.P_16c(), "color"),
                    )
        self.tb = Controles.TB( self, liAcciones, siTexto = False, tamIcon=16 )

        self.tb.liAcciones[1].setVisible( False )
        self.siPlay = True
        self.siBlancas = True
        self.siNegras = True

        self.creaRestoControles()

        self.timer = QtCore.QTimer(self)
        self.connect(self.timer, QtCore.SIGNAL("timeout()"), cpu.compruebaInput )
        self.timer.start(200)

        atexit.register( self.nosvamos )

        self.recuperarVideo( )

    #--------------------------------------------------------------------------------------------------------------------------------
    def siAnalizar(self):
        siW = " w " in self.fen
        if not self.siPlay or \
            (siW and (not self.siBlancas) ) or \
            ((not siW) and (not self.siNegras) ) :
            return False
        return True

    #--------------------------------------------------------------------------------------------------------------------------------
    def color(self):
        menu = Controles.LMenu()
        menu.opcion( "blancas", tr("BLANCAS"), Iconos.PuntoNaranja() )
        menu.opcion( "negras", tr("NEGRAS"), Iconos.PuntoNegro() )
        menu.opcion( "blancasnegras", tr("BLANCAS_Y_NEGRAS"), Iconos.PuntoVerde() )
        resp = menu.lanza()
        if resp :
            self.siNegras = True
            self.siBlancas = True
            if resp == "blancas" :
                self.siNegras = False
            elif resp == "negras" :
                self.siBlancas = False
            if self.siAnalizar() :
                self.ponFen(self.fen)

    #--------------------------------------------------------------------------------------------------------------------------------
    def nosvamos(self):
        self.guardarVideo()
        if self.motor :
            self.motor.close()


    #--------------------------------------------------------------------------------------------------------------------------------
    def comentario(self, una ):
        puntuacion = una["score"].replace( "cp", "").strip()
        depth = una["depth"].strip()
        return " {%s D%s} "%( puntuacion, depth )

    #--------------------------------------------------------------------------------------------------------------------------------
    def portapapelesUltJug(self):
        if self.liData and self.siAnalizar() :
            una = self.liData[-1]
            pgn = una["pgn"]
            li = pgn.split( " " )
            n = 2 if "..." in pgn else 1
            resp = " ".join(li[0:n])
            resp += self.comentario( una )
            if len(li) > n :
                resp += " ".join(li[n:])
            QTUtil.ponPortapapeles( resp )

    #--------------------------------------------------------------------------------------------------------------------------------
    def guardarVideo(self):
        dic = {}

        pos = self.pos()
        dic["_POSICION_"] = "%d,%d"%(pos.x(),pos.y())

        tam = self.size()
        dic["_TAMAÑO_"] = "%d,%d"%(tam.width(),tam.height())

        Util.guardaDIC( dic, self.ficheroVideo )

    # -----------------------------------------------------------------------------------------
    def recuperarVideo(self) :

        if Util.tamFichero( self.ficheroVideo ) > 0 :
            dic = Util.recuperaDIC( self.ficheroVideo )
            if dic :
                wE, hE = QTUtil.tamEscritorio()
                x,y = dic["_POSICION_"].split(",")
                x = int(x)
                y = int(y)
                if not( 0 <= x <= (wE-50) ) :
                    x = 0
                if not( 0 <= y <= (hE-50) ) :
                    y = 0
                self.move( x, y )
                w, h = dic["_TAMAÑO_"].split(",")
                w = int(w)
                h = int(h)
                if w > wE :
                    w = wE
                elif w < 20 :
                    w = 20
                if h > hE :
                    h = hE
                elif h < 20 :
                    h = 20
                self.resize( w, h )

    # -----------------------------------------------------------------------------------------
    def lanzaMotor( self ) :
        self.motor = QtCore.QProcess()

        self.buffer = ""

        self.liOrdenes = []

        self.esperaOK = None

        self.lock = False

        exe = self.cpu.configMotor.ejecutable()
        self.motor.setWorkingDirectory ( os.path.abspath(os.path.dirname(exe)) )
        self.motor.start( exe, [], mode = QtCore.QIODevice.Unbuffered | QtCore.QIODevice.ReadWrite )
        self.motor.waitForStarted()
        self.connect(self.motor, QtCore.SIGNAL("readyReadStandardOutput()"), self.readOutput)

        self.orden_ok( "uci", "uciok" )

        for opcion, valor in self.cpu.configMotor.liUCI :
            if valor is None :
                orden = "setoption name %s"%opcion
            else :
                orden = "setoption name %s value %s"%(opcion, valor)
            self.ready_ok( orden )

        self.runOrdenes()

    # -----------------------------------------------------------------------------------------
    def miraBuffer( self ) :
        self.lock = True
        li = self.buffer.split( "\n" )

        siInfo = False
        for linea in li :
            if linea.startswith( "info " ) and " pv " in linea and " score " in linea:
                dClaves = self.miraClaves( linea, ( "multipv", "depth", "seldepth", "score", "time", "nodes", "pv", "hashfull", "tbhits", "nps" ) )
                dClaves["pgn"] = self.pgn(dClaves["pv"])
                self.liData.append( dClaves )
                siInfo = True
        if not siInfo :
            if "bestmove" in self.buffer :
                for linea in li :
                    if linea.startswith( "bestmove " ):
                        self.em.ponHtml(linea)
                        self.buffer = ""
                        self.lock = False
                        return

        resto = li[-1]
        if self.buffer.endswith( "\n" ) :
            resto += "\n"
        self.buffer = resto

        if siInfo :
            txt = '<table border="1" cellpadding="4" cellspacing="0" style="border-color: #ACA899">'
            ndata = len(self.liData)
            for n in range( ndata-1, -1, -1 ) :
                una = self.liData[n]
                if una :
                    txt += "<tr>"
                    txt += "<td>%s</td>"%una["depth"]
                    txt += '<td ><center><b>%s</b></center></td>'%una["score"].replace("cp ", "")
                    li = una["pgn"].split(" ")
                    if "..." in li[0] :
                        del li[0]
                    nli = len(li)
                    txt += '<td><center><b>%s</b></center></td>'%li[0]
                    if nli > 1 :
                        txt += "<td>%s</td>"%li[1]
                    if nli > 2 :
                        txt += "<td>%s</td>"%(" ".join(li[2:]), )
                    txt += "</tr>"

            txt += "</table>"
            if self.siAnalizar() :
                self.em.ponHtml(txt)

        self.lock = False

    # -----------------------------------------------------------------------------------------
    def pgn( self, pv ) :
        self.partida.liJugadas = []
        self.partida.ultPosicion = self.partida.iniPosicion.copia()
        self.partida.leerPV( pv )

        return self.partida.pgnSP()

    # -----------------------------------------------------------------------------------------
    def miraClaves( self, mensaje, liClaves ) :
        dClaves = {}
        clave = ""
        dato = ""
        for palabra in mensaje.split( " " ) :
            if palabra in liClaves :
                if clave :
                    dClaves[clave] = dato.strip()
                clave = palabra
                dato = ""
            else :
                dato += " " + palabra
        if clave :
            dClaves[clave] = dato.strip()
        return dClaves

    # -----------------------------------------------------------------------------------------
    def readOutput( self ) :
        if not self.lock :
            txt = self.motor.readAllStandardOutput()
            # print txt
            if txt :
                self.buffer += str(txt)
                if self.esperaOK :
                    if self.esperaOK in self.buffer and self.buffer.endswith( "\n" ) :
                        self.buffer = ""
                else :
                    self.miraBuffer()
            self.runOrdenes()
        else :
            time.sleep(0.1)

    # -----------------------------------------------------------------------------------------
    def orden_ok( self, orden, ok=None ) :
        self.liOrdenes.append( (orden, ok) )

    # -----------------------------------------------------------------------------------------
    def ready_ok( self, orden ) :
        self.orden_ok( orden )
        self.orden_ok("isready", "readyok")

    # -----------------------------------------------------------------------------------------
    def orden_fen( self, fen ) :
        posicionInicial = ControlPosicion.ControlPosicion()
        posicionInicial.leeFen(fen)

        self.partida = Partida.Partida( posicionInicial )

        self.ready_ok( "stop" )

        self.ready_ok( "ucinewgame" )
        self.ready_ok( "position fen %s"%fen )

        self.orden_ok( "go infinite", None )

    # -----------------------------------------------------------------------------------------
    def runOrdenes( self ) :
        if self.liOrdenes :
            self.siOrden = True
            orden, ok = self.liOrdenes[0]
            del self.liOrdenes[0]
            self.escribe( orden )
            if ok :
                self.esperaOK = ok
            else :
                self.esperaOK = None
                self.runOrdenes()
        else :
            self.esperaOK = None

    # -----------------------------------------------------------------------------------------
    def escribe( self, linea ) :
        self.motor.write( str(linea) + "\n" )


#==========================================================================================================================================
class VentanaSiguiente( Ventana ) :

    #--------------------------------------------------------------------------------------------------------------------------------
    def creaRestoControles( self ) :

        layout = Colocacion.V().control(self.tb).control( self.em ).margen(1)

        self.setLayout( layout )

        self.lanzaMotor()

    #--------------------------------------------------------------------------------------------------------------------------------
    def procesarTB( self ) :
        clave = self.sender().clave
        if clave == "terminar" :
            self.accept()
        elif clave == "pause" :
            self.siPlay = False
            self.liData = []
            self.tb.liAcciones[1].setVisible( True )
            self.tb.liAcciones[2].setVisible( False )
            self.ready_ok( "stop" )
            self.runOrdenes()
        elif clave == "play" :
            self.siPlay = True
            self.liData = []
            self.tb.liAcciones[1].setVisible( False )
            self.tb.liAcciones[2].setVisible( True )
            self.ponFen(self.fen)
        elif clave == "portapapeles" :
            self.portapapeles()
        elif clave == "portapapelesUltJug" :
            self.portapapelesUltJug()
        elif clave == "color" :
            self.color()

    # -----------------------------------------------------------------------------------------
    def ponFen( self, fen ) :
        if fen :

            if fen != self.fen :
                html = self.em.html()
                if self.fen and html :
                    self.almFEN[self.fen] = html
                self.liData = []

            self.fen = fen
            if self.siAnalizar() :
                if len(self.liData) == 0 :
                    self.em.ponHtml("")
                    self.orden_fen( fen )
                    self.runOrdenes()
            else :
                html = self.almFEN.get(fen, "")
                self.em.ponHtml(html)
                self.ready_ok( "stop" )
                self.runOrdenes()

        else :
            self.em.ponHtml("")
            self.ready_ok( "stop" )
            self.runOrdenes()



#==========================================================================================================================================
class VentanaCapturas( VentanaSiguiente ) :

    #--------------------------------------------------------------------------------------------------------------------------------
    def __init__( self, cpu ) :
        VentanaSiguiente.__init__(self,cpu)

    # -----------------------------------------------------------------------------------------
    def ponFen( self, fen ) :
        dew = " w "
        deb = " b "
        de, a = (dew, deb) if dew in fen else ( deb, dew )
        fen = fen.replace( de, a )
        VentanaSiguiente.ponFen( self, fen )

#==========================================================================================================================================
class VentanaJugadas( Ventana ) :

    #--------------------------------------------------------------------------------------------------------------------------------
    def creaRestoControles( self ) :

        self.lbJug = Controles.LB(self).alinCentrado()

        self.emJug = Controles.EM(self).capturaDobleClick( self.miraMovimiento ).soloLectura()

        layout = Colocacion.V().control(self.tb).control(self.emJug).control(self.lbJug).control( self.em ).margen(1)

        self.setLayout( layout )

        self.mi = MotorInterno.MotorInterno()
        self.lifens = {}

        self.siMotorTrabajando = False
        self.em.hide()
        self.lbJug.hide()
        self.siPrimeraVez = True

    #--------------------------------------------------------------------------------------------------------------------------------
    def portapapelesUltJug(self):
        if self.liData and self.siAnalizar() :
            una = self.liData[-1]
            pgn = una["pgn"]
            if "..." in pgn :
                pgn = pgn.lstrip( "0123456789. ")
            li = pgn.split( " " )
            resp = self.pgn1 + " " + li[0]
            resp += self.comentario( una )
            if len(li) > 1 :
                resp += " ".join(li[1:])


            QTUtil.ponPortapapeles( resp )

    #--------------------------------------------------------------------------------------------------------------------------------
    def paraMotorJugada( self ) :

        self.lbJug.hide()
        self.em.hide()

        # Si el motor está trabajando -> stop
        if self.siMotorTrabajando :
            self.ready_ok( "stop" )
            self.runOrdenes()
            self.siMotorTrabajando = False

    #--------------------------------------------------------------------------------------------------------------------------------
    def lanzaMotorJugada( self, pgn, fen ) :
        self.em.ponHtml( "" )
        if self.siAnalizar() :
            self.lbJug.ponTexto( "<b>%s<b>"%pgn)
            self.lbJug.show()
            self.em.show()
            # Si no hay motor, se lanza
            if self.motor is None :
                self.lanzaMotor()
            self.siMotorTrabajando = True
            self.liData = []
            self.orden_fen( fen )
            self.runOrdenes()

    #--------------------------------------------------------------------------------------------------------------------------------
    def miraMovimiento( self, event ) :
        pos = self.emJug.posicion()
        txt = self.emJug.texto()

        ini = pos-1
        while ini >= 0 :
            c = txt[ini]
            if c in "\n ," :
                ini += 1
                break
            ini -= 1
        fin = pos
        ntxt = len(txt)
        while fin < ntxt :
            c = txt[fin]
            if c in "\n ," :
                break
            fin += 1

        pgn = txt[ini:fin]
        fen, pgn1 = self.dfens.get(pgn,(None,None) )

        if fen is None :
            self.paraMotorJugada()

        else :
            self.pgn1 = pgn1
            self.lanzaMotorJugada( pgn, fen )


    #--------------------------------------------------------------------------------------------------------------------------------
    def procesarTB( self ) :
        clave = self.sender().clave
        if clave == "terminar" :
            self.accept()
        elif clave == "pause" :
            self.siPlay = False
            self.paraMotorJugada()
            self.liData = []
            self.tb.liAcciones[1].setVisible( True )
            self.tb.liAcciones[2].setVisible( False )
        elif clave == "portapapeles" :
            self.portapapeles()
        elif clave == "portapapelesUltJug" :
            self.portapapelesUltJug()
        elif clave == "color" :
            self.color()
        else :
            self.siPlay = True
            self.liData = []
            self.tb.liAcciones[1].setVisible( False )
            self.tb.liAcciones[2].setVisible( True )
            self.ponFen(self.fen)

    # -----------------------------------------------------------------------------------------
    def ponFen( self, fen ) :
        if fen :
            if fen != self.fen :
                html = self.emJug.html()
                if self.fen and html :
                    self.almFEN[self.fen] = html
                self.em.ponHtml("")
                self.emJug.ponHtml("")
                self.liData = []

            self.fen = fen
            if self.siAnalizar() :
                self.ponJugadas()
            else :
                html = self.almFEN.get(fen, "")
                self.emJug.ponHtml(html)
                self.ready_ok( "stop" )
                self.runOrdenes()
        else :
            self.paraMotorJugada()
            self.em.ponHtml("")
            self.emJug.ponHtml("")
            self.liData = []


    # -----------------------------------------------------------------------------------------
    def pgn_fen( self, pv ) :
        pgn = self.pgn( pv )
        fen = self.partida.ultPosicion.fen()
        return pgn, fen

    # -----------------------------------------------------------------------------------------
    def ponJugadas( self ) :

        self.paraMotorJugada()

        if self.siPrimeraVez :
            self.siPrimeraVez = False
            self.lbJug.ponTexto( tr("MOSCA_TIP_JUGADAS") )
            self.lbJug.show()


        posicionInicial = ControlPosicion.ControlPosicion()
        posicionInicial.leeFen(self.fen)

        self.dfens = {}

        self.partida = Partida.Partida( posicionInicial )

        self.mi.ponFen( self.fen )
        liMovs = self.mi.dameMovimientos()
        jaqs = ""
        caps = ""
        rest = ""
        for mov in liMovs :
            pgn1, fen = self.pgn_fen( mov.pv() )
            pgn = pgn1.lstrip("0123456789. " )
            self.dfens[pgn] = fen,pgn1
            pgn += ", "
            si = False
            if "x" in pgn :
                caps += pgn
                si = True
            if ("+" in pgn) or ("#" in pgn) :
                jaqs += pgn
                si = True
            if not si :
                rest += pgn

        txt = '<table border="1" cellpadding="4" cellspacing="0" style="border-color: #ACA899">'

        txt += "<tr><th>%s</th><td>%s</td></tr>"%(tr( "MOSCA_XJAQUES"),jaqs.rstrip( " ," ) )
        txt += "<tr><th>%s</th><td>%s</td></tr>"%(tr( "MOSCA_XCAPTURAS"),caps.rstrip( " ," ) )
        txt += "<tr><th>%s</th><td>%s</td></tr>"%(tr( "MOSCA_XRESTO"), rest.rstrip( " ," ) )

        txt += "</table>"
        # txt += "<small>%s</small>"%tr("MOSCA_TIP_JUGADAS")
        self.emJug.ponHtml(txt)
        self.em.ponHtml("")

#==========================================================================================================================================
class Orden :
    def __init__( self ) :
        self.clave = ""
        self.titulo = ""
        self.dv = {}

    def ponVar( self, nombre, valor ) :
        self.dv[nombre] = valor

    def bloqueEnvio( self ) :
        texto = base64.encodestring(cPickle.dumps(self.dv))
        prologo = "1234567890:"
        return "%s%s%05d%s"%(prologo,self.clave, len(texto), texto )

    def dicTexto( self, texto ) :
        if texto :
            self.dv = cPickle.loads( base64.decodestring(texto) )
        else :
            self.dv = {}
        return self.dv

    def __str__( self) :
        return "%s-%s-%s"%(self.clave,self.titulo, str(self.dv) )


#==========================================================================================================================================
class CPU( ) :

    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    def __init__( self ) :
        # io
        self.newin = os.fdopen(sys.stdin.fileno(), 'r', 0)
        self.newout = os.fdopen(sys.stdout.fileno(), 'w', 0)

        self.configuracion = None
        self.configMotor = None
        self.titulo = None

        self.ventana = None
        self.motor = None
    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=


    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    def run( self ) :

        # Primero espera la orden de lucas
        while True :
            orden = self.recibe()
            if orden :
                break
            time.sleep( 0.1 )

        self.procesa( orden )

    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=


    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    def recibe( self ) :
        self.newin.seek(0, os.SEEK_END)
        if self.newin.tell() == 0 :
            return None

        while True :
            x = self.newin.read(1)
            if x == ":" :
                x = self.newin.read(6)
                orden = Orden()
                orden.clave = x[0]
                numero = int(x[1:6])
                if numero :
                    orden.dicTexto( self.newin.read(numero) )
                return orden
    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=


    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    def envia( self, orden ) :
        self.newout.write( orden.bloqueEnvio() )
    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    def procesa( self, orden ) :
        clave = orden.clave
        if clave == CONFIGURACION :
            self.configuracion = orden.dv["CONFIGURACION"]
            self.titulo = orden.dv["TITULO"]
            self.configMotor = orden.dv["CONFIG_MOTOR"]
            self.ficheroVideo = orden.dv["FVIDEO"]
            self.tipo = orden.dv["TIPO"]
            self.lanzaVentana()

        elif clave == FEN :
            self.ventana.ponFen( orden.dv["FEN"] )

    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    def lanzaVentana( self ) :
        app = QtGui.QApplication([])

        app.setStyle(QtGui.QStyleFactory.create("CleanLooks"))
        QtGui.QApplication.setPalette(QtGui.QApplication.style().standardPalette())

        # Leemos la traducción ( enviada en config? )
        self.configuracion.releeTRA( True )

        fichlng = "Translations/lk_%s.qm"%self.configuracion.lng()

        if os.path.isfile(fichlng) :
            translator = QtCore.QTranslator()
            translator.load(fichlng)
            app.installTranslator(translator)

        # Lanzamos la pantalla
        if self.tipo == "S" :
            self.ventana = VentanaSiguiente( self )
        elif self.tipo == "C" :
            self.ventana = VentanaCapturas( self )
        else :
            self.ventana = VentanaJugadas( self )
        self.ventana.show()

        return app.exec_()


    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    def compruebaInput( self ) :
        orden = self.recibe()
        if orden :
            self.procesa( orden )

    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    def dispatch( self, texto ) :
        if texto :
            self.ventana.ponTexto( texto )
        QTUtil.refreshGUI()

        return True

    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    def cierraVentana( self ) :
        self.ventana.reject()
    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    def cierraMotor( self ) :
        if self.motor :
            self.motor.apagar()
    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

#==========================================================================================================================================


#==========================================================================================================================================


if __name__=="__main__" :

    reload(sys)
    sys.setdefaultencoding("latin-1")

    ferr = open("bug.mosca", "at")
    sys.stderr = ferr

    cpu = CPU()
    cpu.run()


    ferr.close()
#==========================================================================================================================================
